PageSourceSearch

https://stacktips.com/articles

html stacktips.com collected 2026-10-01 10:25:37 UTC 2,433,814 bytes, 1 lines download raw bytes

1<!DOCTYPE html><html lang="en" class="google_sans_de2ab2d4-module__jhlsca__variable google_sans_7052cbd-module__Nlg93G__variable jetbrains_mono_8911b945-module__BziYTW__variable sriracha_9bad02da-module__Vayo6a__variable h-full antialiased"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" href="/_next/static/media/409c52c0b1658041-s.p.2bve6knowi8om.woff2" as="font" crossorigin="" type="font/woff2"/><link rel="preload" href="/_next/static/media/47d6d6c1e6da10b8.p.40-jm68xkzcno.woff2" as="font" crossorigin="" type="font/woff2"/><link rel="preload" href="/_next/static/media/70bc3e132a0a741e-s.p.3t6q91iet4nsy.woff2" as="font" crossorigin="" type="font/woff2"/><link rel="preload" as="image" imageSrcSet="/_next/image?url=%2Fbrand%2Flogo-light1.png&amp;w=256&amp;q=75 1x, /_next/image?url=%2Fbrand%2Flogo-light1.png&amp;w=384&amp;q=75 2x"/><link rel="preload" as="image" imageSrcSet="/_next/image?url=%2Fbrand%2Flogo-dark1.png&amp;w=256&amp;q=75 1x, /_next/image?url=%2Fbrand%2Flogo-dark1.png&amp;w=384&amp;q=75 2x"/><link rel="stylesheet" href="/_next/static/chunks/31h00aiyhac91.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/1qqh6g_pdlocw.js"/>
1<script src="/_next/static/chunks/27jktro2p5rq9.js" async=""></script>
1<script src="/_next/static/chunks/2s1sgaq5qwht2.js" async=""></script>
1<script src="/_next/static/chunks/2_hsmj0srgg2i.js" async=""></script>
1<script src="/_next/static/chunks/turbopack-1kkpmh0-wbyr6.js" async=""></script>
1<script src="/_next/static/chunks/0zl4fdmf-9zey.js" async=""></script>
1<script src="/_next/static/chunks/20l7v14ur27g4.js" async=""></script>
1<script src="/_next/static/chunks/2_aqbasgm93x0.js" async=""></script>
1<script src="/_next/static/chunks/1-8s9_t85wwr4.js" async=""></script>
1<script src="/_next/static/chunks/0d40cfc_crt89.js" async=""></script>
1<script src="/_next/static/chunks/0a3lk9460xb-w.js" async=""></script>
1<meta name="theme-color" content="#fafafa"/><meta property="og:logo" content="https://stacktips.com/brand/icon-dark.png"/><meta name="next-size-adjust" content=""/><title>Tutorials | StackTips</title><meta name="description" content="All tutorials on Java, Spring Boot, Android, and web development."/><link rel="manifest" href="/manifest.webmanifest"/><link rel="canonical" href="https://stacktips.com/articles"/><link rel="icon" href="/brand/icon-light.png" type="image/png"/><link rel="icon" href="/brand/icon-dark.png" type="image/png" media="(prefers-color-scheme: dark)"/><link rel="apple-touch-icon" href="/brand/icon-dark.png"/>
1<script type="text/javascript">(function(){try{var t=localStorage.getItem("theme");if(t==="dark"||t==="light")document.documentElement.setAttribute("data-theme",t);var resolved=t==="dark"||t==="light"?t:(window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");var m=document.querySelector('meta[name="theme-color"]');if(m)m.setAttribute("content",resolved==="dark"?"#000000":"#fafafa")}catch(e){}})()</script>
1<script src="/_next/static/chunks/0cz1d0mv5g_q7.js" noModule=""></script>
1</head><body class="min-h-full flex flex-col bg-paper text-ink"><div hidden=""><!--$--><!--/$--></div><header class="sticky top-0 z-40 transition-colors duration-200 bg-surface"><div class="relative flex h-16 w-full items-center gap-4 px-4 sm:px-6 lg:px-12"><a class="flex items-center" href="/"><img alt="StackTips" width="140" height="32" decoding="async" data-nimg="1" class="theme-logo-light h-8 w-auto" style="color:transparent" srcSet="/_next/image?url=%2Fbrand%2Flogo-light1.png&amp;w=256&amp;q=75 1x, /_next/image?url=%2Fbrand%2Flogo-light1.png&amp;w=384&amp;q=75 2x" src="/_next/image?url=%2Fbrand%2Flogo-light1.png&amp;w=384&amp;q=75"/><img alt="StackTips" width="140" height="32" decoding="async" data-nimg="1" class="theme-logo-dark h-8 w-auto" style="color:transparent" srcSet="/_next/image?url=%2Fbrand%2Flogo-dark1.png&amp;w=256&amp;q=75 1x, /_next/image?url=%2Fbrand%2Flogo-dark1.png&amp;w=384&amp;q=75 2x" src="/_next/image?url=%2Fbrand%2Flogo-dark1.png&amp;w=384&amp;q=75"/></a><nav class="relative hidden h-full items-center self-stretch px-4 md:flex lg:px-6"><a class="px-3 py-2 text-sm font-medium transition-colors hover:text-ink text-ink-muted" href="/courses">Courses</a><a aria-current="page" class="px-3 py-2 text-sm font-medium transition-colors hover:text-ink text-ink" href="/articles">Tutorials</a><a class="px-3 py-2 text-sm font-medium transition-colors hover:text-ink text-ink-muted" href="/topics">Topics</a><a class="px-3 py-2 text-sm font-medium transition-colors hover:text-ink text-ink-muted" href="/quizzes">Quizzes</a><div class="relative flex h-full items-center"><button type="button" class="flex items-center gap-1 px-3 py-2 text-sm font-medium text-ink-muted transition-colors hover:text-ink" aria-expanded="false">Community<svg width="10" height="10" viewBox="0 0 10 10" fill="none" aria-hidden="true"><path d="M2 3.5 5 6.5 8 3.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"></path></svg></button></div><span aria-hidden="true" class="pointer-events-none absolute -z-10 rounded-full bg-surface-strong transition-all duration-200 ease-out" style="left:0;width:0;top:0;height:0;opacity:0"></span></nav><div class="ml-auto flex items-center gap-1"><div class="md:hidden"><button type="button" aria-label="Toggle menu" aria-expanded="false" class="inline-flex h-8 w-8 items-center justify-center rounded-full text-ink-muted transition-colors hover:bg-surface hover:text-ink"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-menu h-[18px] w-[18px]" aria-hidden="true"><path d="M4 5h16"></path><path d="M4 12h16"></path><path d="M4 19h16"></path></svg></button></div><div class="hidden items-center gap-1 md:flex"><button type="button" aria-label="Search" class="inline-flex h-8 items-center gap-2 rounded-full border border-transparent pl-2.5 pr-2 text-ink-muted transition-colors hover:border-border hover:text-ink min-[1300px]:hidden"><svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true"><circle cx="9" cy="9" r="6.5" stroke="currentColor" stroke-width="1.6"></circle><path d="M17.5 17.5 14 14" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"></path></svg><kbd class="rounded border border-border px-1.5 py-0.5 font-mono text-[10px] font-medium leading-none text-ink-faint">⌘K</kbd></button><button type="button" aria-label="Search" class="hidden h-9 w-64 items-center gap-2.5 rounded-full border border-border bg-surface-strong/60 px-3.5 text-left text-ink-muted transition-colors hover:border-ink-faint hover:text-ink min-[1300px]:flex"><svg width="16" height="16" viewBox="0 0 20 20" fill="none" class="shrink-0" aria-hidden="true"><circle cx="9" cy="9" r="6.5" stroke="currentColor" stroke-width="1.6"></circle><path d="M17.5 17.5 14 14" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"></path></svg><span class="flex-1 truncate text-sm">Search ..</span><kbd class="shrink-0 rounded border border-border px-1.5 py-0.5 font-mono text-[10px] font-medium leading-none text-ink-faint">⌘K</kbd></button><button type="button" aria-label="Switch to dark theme" class="inline-flex h-8 w-8 items-center justify-center rounded-full text-ink-muted transition-colors hover:bg-surface hover:text-ink">
1<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M13.5 9.65A5.75 5.75 0 0 1 6.35 2.5a5.75 5.75 0 1 0 7.15 7.15Z" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"></path></svg></button><a href="/rss.xml" aria-label="RSS feed" class="inline-flex h-8 w-8 items-center justify-center rounded-full text-ink-muted transition-colors hover:bg-surface hover:text-ink"><svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true"><circle cx="5" cy="15" r="1.6" fill="currentColor"></circle><path d="M4 8.5a7.5 7.5 0 0 1 7.5 7.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"></path><path d="M4 3.5A12.5 12.5 0 0 1 16.5 16" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"></path></svg></a><div class="relative"><button type="button" aria-label="Follow StackTips" aria-expanded="false" class="inline-flex h-8 w-8 items-center justify-center rounded-full text-ink-muted transition-colors hover:bg-surface hover:text-ink"><svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path d="M10 17.2s-6.7-4.1-6.7-8.85A3.85 3.85 0 0 1 10 5.85 3.85 3.85 0 0 1 16.7 8.35c0 4.75-6.7 8.85-6.7 8.85Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"></path></svg></button></div></div></div></div></header><main class="flex-1"><div class="mx-auto max-w-7xl px-4 py-14 sm:px-6"><h1 class="font-display text-balance text-4xl font-medium tracking-tighter text-ink sm:text-5xl">Tutorials</h1><p class="mt-4 max-w-2xl text-lg leading-relaxed text-ink-muted">Step-by-step tutorials to master Java, Spring, Python, Android and Git concepts. From beginner-friendly guides to advanced techniques.</p><div class="mt-8"><div><div class="grid gap-x-12 gap-y-10 sm:grid-cols-2 lg:grid-cols-3"><a class="group flex items-start gap-3" href="/articles/building-your-first-rest-api-with-spring-boot"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(145 60% var(--ph-bg-l, 94%));--ph-b:hsl(185 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(145 45% var(--ph-fg-l, 45%))" aria-hidden="true"><defs><pattern id="p-buildingyourfirstrestapiwithspringboot" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="3" cy="3" r="2" fill="currentColor" opacity="0.5"></circle></pattern></defs><rect width="100%" height="100%" fill="url(#p-buildingyourfirstrestapiwithspringboot)"></rect></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#6cb4401a;border-color:#6cb440;color:#6cb440" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Spring Boot</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Building Your First REST API with Spring Boot</h3><p class="mt-3 text-xs text-ink-faint">30<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/setting-up-your-first-spring-boot-project"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(84 60% var(--ph-bg-l, 94%));--ph-b:hsl(124 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(84 45% var(--ph-fg-l, 45%))" aria-hidden="true"><circle cx="60" cy="40" r="26" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.4"></circle><circle cx="60" cy="40" r="16" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.55"></circle><circle cx="86" cy="40" r="4" fill="currentColor" opacity="0.7"></circle><circle cx="60" cy="14" r="3" fill="currentColor" opacity="0.5"></circle></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#6cb4401a;border-color:#6cb440;color:#6cb440" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Spring Boot</span>
1<h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Setting Up Your First Spring Boot Project</h3><p class="mt-3 text-xs text-ink-faint">8<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/configuration-management-in-spring-boot"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><img src="/media/post/None_configuration-management-in-spring-boot.jpeg" alt="" loading="lazy" class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"/><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#6cb4401a;border-color:#6cb440;color:#6cb440" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Spring Boot</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Configuration Management in Spring Boot</h3><p class="mt-3 text-xs text-ink-faint">15<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/prerequisites-for-spring-boot-development"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(140 60% var(--ph-bg-l, 94%));--ph-b:hsl(180 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(140 45% var(--ph-fg-l, 45%))" aria-hidden="true"><defs><pattern id="p-prerequisitesforspringbootdevelopment" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="3" cy="3" r="2" fill="currentColor" opacity="0.5"></circle></pattern></defs><rect width="100%" height="100%" fill="url(#p-prerequisitesforspringbootdevelopment)"></rect></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#6cb4401a;border-color:#6cb440;color:#6cb440" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Spring Boot</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Prerequisites for Spring Boot Development</h3><p class="mt-3 text-xs text-ink-faint">11<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/java-17-interview-questions-and-answers"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><img src="/media/posts/java-17-interview-questions-and-answers.jpeg" alt="" loading="lazy" class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"/><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Java 17 Interview Questions and Answers</h3><p class="mt-3 text-xs text-ink-faint">16<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/spring-boot-interview-questions-and-answers"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(96 60% var(--ph-bg-l, 94%));--ph-b:hsl(136 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(96 45% var(--ph-fg-l, 45%))" aria-hidden="true"><path d="M0 40 Q 20 20 40 40 T 80 40 T 120 40" stroke="currentColor" stroke-width="3" fill="none" opacity="0.55"></path><path d="M0 60 Q 20 40 40 60 T 80 60 T 120 60" stroke="currentColor" stroke-width="3" fill="none" opacity="0.35"></path><path d="M0 20 Q 20 0 40 20 T 80 20 T 120 20" stroke="currentColor" stroke-width="3" fill="none" opacity="0.35"></path></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#6cb4401a;border-color:#6cb440;color:#6cb440" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Spring Boot</span>
1<h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Spring, Spring Boot Interview Question Answers</h3><p class="mt-3 text-xs text-ink-faint">26<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/most-popular-java-interview-questions-and-answers"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(118 60% var(--ph-bg-l, 94%));--ph-b:hsl(158 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(118 45% var(--ph-fg-l, 45%))" aria-hidden="true"><line x1="-40" y1="0" x2="40" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="-24" y1="0" x2="56" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="-8" y1="0" x2="72" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="8" y1="0" x2="88" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="24" y1="0" x2="104" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="40" y1="0" x2="120" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="56" y1="0" x2="136" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="72" y1="0" x2="152" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="88" y1="0" x2="168" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="104" y1="0" x2="184" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Most Popular Java Interview Questions and Answers</h3><p class="mt-3 text-xs text-ink-faint">38<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/essential-mongodb-optimization-tips-for-spring-boot"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><img src="/media/post/690_Essential_MongoDB_Optimization_Tips_for_Spring_Boot_Application-min.png" alt="" loading="lazy" class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"/><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#6cb4401a;border-color:#6cb440;color:#6cb440" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Spring Boot</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Essential MongoDB Optimization Tips for Spring Boot Applications</h3><p class="mt-3 text-xs text-ink-faint">25<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/introduction-to-java-collections"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(311 60% var(--ph-bg-l, 94%));--ph-b:hsl(351 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(311 45% var(--ph-fg-l, 45%))" aria-hidden="true"><path d="M0 40 Q 20 20 40 40 T 80 40 T 120 40" stroke="currentColor" stroke-width="3" fill="none" opacity="0.55"></path><path d="M0 60 Q 20 40 40 60 T 80 60 T 120 60" stroke="currentColor" stroke-width="3" fill="none" opacity="0.35"></path><path d="M0 20 Q 20 0 40 20 T 80 20 T 120 20" stroke="currentColor" stroke-width="3" fill="none" opacity="0.35"></path></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span>
1<h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Introduction to Java Collections</h3><p class="mt-3 text-xs text-ink-faint">3<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/hashtable-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(259 60% var(--ph-bg-l, 94%));--ph-b:hsl(299 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(259 45% var(--ph-fg-l, 45%))" aria-hidden="true"><circle cx="60" cy="40" r="26" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.4"></circle><circle cx="60" cy="40" r="16" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.55"></circle><circle cx="86" cy="40" r="4" fill="currentColor" opacity="0.7"></circle><circle cx="60" cy="14" r="3" fill="currentColor" opacity="0.5"></circle></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Hashtable in Java</h3><p class="mt-3 text-xs text-ink-faint">3<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/treemap-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(325 60% var(--ph-bg-l, 94%));--ph-b:hsl(5 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(325 45% var(--ph-fg-l, 45%))" aria-hidden="true"><defs><pattern id="p-treemapinjava" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="3" cy="3" r="2" fill="currentColor" opacity="0.5"></circle></pattern></defs><rect width="100%" height="100%" fill="url(#p-treemapinjava)"></rect></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">TreeMap in Java</h3><p class="mt-3 text-xs text-ink-faint">9<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/identityhashmap-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(29 60% var(--ph-bg-l, 94%));--ph-b:hsl(69 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(29 45% var(--ph-fg-l, 45%))" aria-hidden="true"><circle cx="60" cy="40" r="26" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.4"></circle><circle cx="60" cy="40" r="16" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.55"></circle><circle cx="86" cy="40" r="4" fill="currentColor" opacity="0.7"></circle><circle cx="60" cy="14" r="3" fill="currentColor" opacity="0.5"></circle></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">IdentityHashMap in Java</h3><p class="mt-3 text-xs text-ink-faint">5<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/linkedhashmap-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(30 60% var(--ph-bg-l, 94%));--ph-b:hsl(70 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(30 45% var(--ph-fg-l, 45%))" aria-hidden="true"><defs><pattern id="p-linkedhashmapinjava" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="3" cy="3" r="2" fill="currentColor" opacity="0.5"></circle></pattern></defs><rect width="100%" height="100%" fill="url(#p-linkedhashmapinjava)"></rect></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span>
1<h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">LinkedHashMap in Java</h3><p class="mt-3 text-xs text-ink-faint">9<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/hashmap-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(221 60% var(--ph-bg-l, 94%));--ph-b:hsl(261 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(221 45% var(--ph-fg-l, 45%))" aria-hidden="true"><path d="M0 40 Q 20 20 40 40 T 80 40 T 120 40" stroke="currentColor" stroke-width="3" fill="none" opacity="0.55"></path><path d="M0 60 Q 20 40 40 60 T 80 60 T 120 60" stroke="currentColor" stroke-width="3" fill="none" opacity="0.35"></path><path d="M0 20 Q 20 0 40 20 T 80 20 T 120 20" stroke="currentColor" stroke-width="3" fill="none" opacity="0.35"></path></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">HashMap in Java</h3><p class="mt-3 text-xs text-ink-faint">12<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/arraydeque-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(108 60% var(--ph-bg-l, 94%));--ph-b:hsl(148 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(108 45% var(--ph-fg-l, 45%))" aria-hidden="true"><line x1="-40" y1="0" x2="40" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="-24" y1="0" x2="56" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="-8" y1="0" x2="72" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="8" y1="0" x2="88" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="24" y1="0" x2="104" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="40" y1="0" x2="120" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="56" y1="0" x2="136" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="72" y1="0" x2="152" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="88" y1="0" x2="168" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="104" y1="0" x2="184" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">ArrayDeque in Java</h3><p class="mt-3 text-xs text-ink-faint">8<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/delayqueue"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(354 60% var(--ph-bg-l, 94%));--ph-b:hsl(34 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(354 45% var(--ph-fg-l, 45%))" aria-hidden="true"><circle cx="60" cy="40" r="26" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.4"></circle><circle cx="60" cy="40" r="16" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.55"></circle><circle cx="86" cy="40" r="4" fill="currentColor" opacity="0.7"></circle><circle cx="60" cy="14" r="3" fill="currentColor" opacity="0.5"></circle></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span>
1<h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">DelayQueue in Java</h3><p class="mt-3 text-xs text-ink-faint">7<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/priorityqueue-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(222 60% var(--ph-bg-l, 94%));--ph-b:hsl(262 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(222 45% var(--ph-fg-l, 45%))" aria-hidden="true"><line x1="0" y1="0" x2="120" y2="0" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="14" x2="120" y2="14" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="28" x2="120" y2="28" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="42" x2="120" y2="42" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="56" x2="120" y2="56" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="70" x2="120" y2="70" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="0" x2="0" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="14" y1="0" x2="14" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="28" y1="0" x2="28" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="42" y1="0" x2="42" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="56" y1="0" x2="56" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="70" y1="0" x2="70" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">PriorityQueue in Java</h3><p class="mt-3 text-xs text-ink-faint">9<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/treeset-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(47 60% var(--ph-bg-l, 94%));--ph-b:hsl(87 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(47 45% var(--ph-fg-l, 45%))" aria-hidden="true"><line x1="0" y1="0" x2="120" y2="0" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="14" x2="120" y2="14" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="28" x2="120" y2="28" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="42" x2="120" y2="42" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="56" x2="120" y2="56" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="70" x2="120" y2="70" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="0" x2="0" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="14" y1="0" x2="14" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="28" y1="0" x2="28" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="42" y1="0" x2="42" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="56" y1="0" x2="56" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="70" y1="0" x2="70" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span>
1<h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">TreeSet in Java</h3><p class="mt-3 text-xs text-ink-faint">7<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/linkedhashset-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(144 60% var(--ph-bg-l, 94%));--ph-b:hsl(184 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(144 45% var(--ph-fg-l, 45%))" aria-hidden="true"><circle cx="60" cy="40" r="26" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.4"></circle><circle cx="60" cy="40" r="16" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.55"></circle><circle cx="86" cy="40" r="4" fill="currentColor" opacity="0.7"></circle><circle cx="60" cy="14" r="3" fill="currentColor" opacity="0.5"></circle></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">LinkedHashSet in Java</h3><p class="mt-3 text-xs text-ink-faint">5<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/hashset-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(303 60% var(--ph-bg-l, 94%));--ph-b:hsl(343 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(303 45% var(--ph-fg-l, 45%))" aria-hidden="true"><line x1="-40" y1="0" x2="40" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="-24" y1="0" x2="56" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="-8" y1="0" x2="72" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="8" y1="0" x2="88" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="24" y1="0" x2="104" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="40" y1="0" x2="120" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="56" y1="0" x2="136" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="72" y1="0" x2="152" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="88" y1="0" x2="168" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="104" y1="0" x2="184" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">HashSet in Java</h3><p class="mt-3 text-xs text-ink-faint">13<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/stack-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(157 60% var(--ph-bg-l, 94%));--ph-b:hsl(197 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(157 45% var(--ph-fg-l, 45%))" aria-hidden="true"><line x1="0" y1="0" x2="120" y2="0" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="14" x2="120" y2="14" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="28" x2="120" y2="28" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="42" x2="120" y2="42" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="56" x2="120" y2="56" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="70" x2="120" y2="70" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="0" y1="0" x2="0" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="14" y1="0" x2="14" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="28" y1="0" x2="28" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="42" y1="0" x2="42" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="56" y1="0" x2="56" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line><line x1="70" y1="0" x2="70" y2="80" stroke="currentColor" stroke-width="1" opacity="0.3"></line></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span>
1<h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Stack in Java</h3><p class="mt-3 text-xs text-ink-faint">7<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/vector-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(40 60% var(--ph-bg-l, 94%));--ph-b:hsl(80 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(40 45% var(--ph-fg-l, 45%))" aria-hidden="true"><defs><pattern id="p-vectorinjava" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="3" cy="3" r="2" fill="currentColor" opacity="0.5"></circle></pattern></defs><rect width="100%" height="100%" fill="url(#p-vectorinjava)"></rect></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Vector in Java</h3><p class="mt-3 text-xs text-ink-faint">8<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/copyonwritearraylist-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(239 60% var(--ph-bg-l, 94%));--ph-b:hsl(279 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(239 45% var(--ph-fg-l, 45%))" aria-hidden="true"><circle cx="60" cy="40" r="26" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.4"></circle><circle cx="60" cy="40" r="16" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.55"></circle><circle cx="86" cy="40" r="4" fill="currentColor" opacity="0.7"></circle><circle cx="60" cy="14" r="3" fill="currentColor" opacity="0.5"></circle></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">CopyOnWriteArrayList in Java</h3><p class="mt-3 text-xs text-ink-faint">8<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/linkedlist-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(164 60% var(--ph-bg-l, 94%));--ph-b:hsl(204 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(164 45% var(--ph-fg-l, 45%))" aria-hidden="true"><circle cx="60" cy="40" r="26" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.4"></circle><circle cx="60" cy="40" r="16" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.55"></circle><circle cx="86" cy="40" r="4" fill="currentColor" opacity="0.7"></circle><circle cx="60" cy="14" r="3" fill="currentColor" opacity="0.5"></circle></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">LinkedList in Java</h3><p class="mt-3 text-xs text-ink-faint">17<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/arraylist-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(124 60% var(--ph-bg-l, 94%));--ph-b:hsl(164 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(124 45% var(--ph-fg-l, 45%))" aria-hidden="true"><circle cx="60" cy="40" r="26" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.4"></circle><circle cx="60" cy="40" r="16" stroke="currentColor" stroke-width="1.5" fill="none" opacity="0.55"></circle><circle cx="86" cy="40" r="4" fill="currentColor" opacity="0.7"></circle><circle cx="60" cy="14" r="3" fill="currentColor" opacity="0.5"></circle></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span>
1<h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">ArrayList in Java</h3><p class="mt-3 text-xs text-ink-faint">22<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/static-keyowrd-in-java"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><div class="h-full w-full" style="--ph-a:hsl(73 60% var(--ph-bg-l, 94%));--ph-b:hsl(113 60% var(--ph-bg-l2, 90%));background:linear-gradient(135deg, var(--ph-a), var(--ph-b))"><svg viewBox="0 0 120 80" preserveAspectRatio="xMidYMid slice" class="h-full w-full" style="color:hsl(73 45% var(--ph-fg-l, 45%))" aria-hidden="true"><line x1="-40" y1="0" x2="40" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="-24" y1="0" x2="56" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="-8" y1="0" x2="72" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="8" y1="0" x2="88" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="24" y1="0" x2="104" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="40" y1="0" x2="120" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="56" y1="0" x2="136" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="72" y1="0" x2="152" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="88" y1="0" x2="168" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line><line x1="104" y1="0" x2="184" y2="80" stroke="currentColor" stroke-width="4" opacity="0.35"></line></svg></div><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#F898201a;border-color:#F89820;color:#F89820" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Java</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Static Variables, Methods, and Class</h3><p class="mt-3 text-xs text-ink-faint">9<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/importing-csv-data-into-postgresql-using-spring-boot-batch"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><img src="/media/post/668_thumbnail.001-min.jpeg" alt="" loading="lazy" class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"/><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#6cb4401a;border-color:#6cb440;color:#6cb440" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Spring Boot</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Importing CSV Data into PostgreSQL using Spring Boot Batch</h3><p class="mt-3 text-xs text-ink-faint">37<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/rest-clients-in-spring"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><img src="/media/post/667_rest-clients-in-spring-framework.jpeg" alt="" loading="lazy" class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"/><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#6cb4401a;border-color:#6cb440;color:#6cb440" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Spring Boot</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Digging into HTTP Clients in Spring: From RestTemplate to HTTP Interface</h3><p class="mt-3 text-xs text-ink-faint">25<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/using-flyway-for-database-migration-in-spring-boot"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><img src="/media/post/666_using-flyway-for-database-migration-in-springboot.png" alt="" loading="lazy" class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"/><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#6cb4401a;border-color:#6cb440;color:#6cb440" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Spring Boot</span>
1<h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Using Flyway for Database Migration in Spring Boot</h3><p class="mt-3 text-xs text-ink-faint">26<!-- --> min read</p></div></a><a class="group flex items-start gap-3" href="/articles/understanding-spring-boot-project-structure"><div class="relative h-20 w-32 shrink-0 overflow-hidden rounded-md"><img src="/media/post/664_spring-boot-project-structure.jpeg" alt="" loading="lazy" class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"/><div class="absolute inset-0 bg-black/0 transition-colors duration-300 group-hover:bg-black/30"></div></div><div class="min-w-0 flex-1"><span style="background-color:#6cb4401a;border-color:#6cb440;color:#6cb440" class="inline-flex items-center rounded-full border border-transparent bg-surface px-2 py-0.5 font-mono text-xs text-ink-muted ">Spring Boot</span><h3 class="mt-1.5 text-base font-normal leading-snug text-ink transition-colors group-hover:text-accent">Understanding Spring Boot Project Structure</h3><p class="mt-3 text-xs text-ink-faint">9<!-- --> min read</p></div></a></div><nav aria-label="Pagination" class="mt-10 flex flex-wrap items-center justify-between gap-4 pt-8"><label class="flex items-center gap-2.5 font-mono text-xs text-ink-faint"><span class="relative inline-flex h-9 items-center rounded-xl border border-border bg-surface-strong pl-4 pr-9 text-sm font-medium text-ink"><select aria-label="Articles per page" class="h-full w-full appearance-none bg-transparent pr-1 outline-none"><option value="30" selected="">30</option><option value="40">40</option><option value="50">50</option><option value="100">100</option></select><svg width="12" height="12" viewBox="0 0 20 20" fill="none" aria-hidden="true" class="pointer-events-none absolute right-3 text-ink-muted"><path d="M5 8l5 5 5-5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"></path></svg></span>per page</label><div class="flex items-center gap-3"><span class="inline-flex h-9 items-center rounded-xl border border-border bg-surface-strong px-4 font-mono text-sm text-ink"><span class="font-medium">1</span><span class="mx-1.5 text-ink-faint">of</span><span>12</span><span class="ml-1.5 text-ink-faint">pages</span></span><button type="button" aria-label="Previous page" disabled="" class="inline-flex h-9 items-center justify-center rounded-xl border border-border px-4 text-sm font-medium text-ink-muted transition-colors hover:border-accent hover:text-accent disabled:pointer-events-none disabled:opacity-30">Previous</button><button type="button" aria-label="Next page" class="inline-flex h-9 items-center justify-center rounded-xl border border-border px-4 text-sm font-medium text-ink-muted transition-colors hover:border-accent hover:text-accent disabled:pointer-events-none disabled:opacity-30">Next</button></div></nav></div></div></div><!--$--><!--/$--></main><footer class="bg-surface/80"><div class="mx-auto flex max-w-7xl flex-col gap-4 px-4 py-10 text-sm text-ink-muted sm:flex-row sm:items-center sm:justify-between sm:px-6"><p>© <!-- -->2026<!-- --> StackTips. Built by<!-- --> <a href="https://github.com/nilandev" target="_blank" rel="noopener noreferrer" class="hover:text-ink">Nilanchala</a> <!-- -->with love</p><nav class="flex gap-5"><a class="hover:text-ink" href="/articles">Tutorials</a><a class="hover:text-ink" href="/courses">Courses</a><a class="hover:text-ink" href="/topics">Topics</a></nav></div></footer>
1<script src="/_next/static/chunks/1qqh6g_pdlocw.js" id="_R_" async=""></script>
1<script>(self.__next_f=self.__next_f||[]).push([0])</script>
1<script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[3020,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\"],\"SiteHeader\"]\n3:I[39756,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\"],\"default\"]\n4:I[37457,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\"],\"default\"]\n5:I[22381,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\",\"/_next/static/chunks/0d40cfc_crt89.js\"],\"NotFoundTracker\"]\n6:I[22016,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\",\"/_next/static/chunks/0d40cfc_crt89.js\"],\"\"]\n10:I[68027,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/31h00aiyhac91.css\",\"style\"]\n:HL[\"/_next/static/media/409c52c0b1658041-s.p.2bve6knowi8om.woff2\",\"font\",{\"crossOrigin\":\"\",\"type\":\"font/woff2\"}]\n:HL[\"/_next/static/media/47d6d6c1e6da10b8.p.40-jm68xkzcno.woff2\",\"font\",{\"crossOrigin\":\"\",\"type\":\"font/woff2\"}]\n:HL[\"/_next/static/media/70bc3e132a0a741e-s.p.3t6q91iet4nsy.woff2\",\"font\",{\"crossOrigin\":\"\",\"type\":\"font/woff2\"}]\n"])</script>
1<script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"articles\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"articles\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/31h00aiyhac91.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"async\":true,\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-1\",{\"src\":\"/_next/static/chunks/20l7v14ur27g4.js\",\"async\":true,\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-2\",{\"src\":\"/_next/static/chunks/2_aqbasgm93x0.js\",\"async\":true,\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-3\",{\"src\":\"/_next/static/chunks/1-8s9_t85wwr4.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"className\":\"google_sans_de2ab2d4-module__jhlsca__variable google_sans_7052cbd-module__Nlg93G__variable jetbrains_mono_8911b945-module__BziYTW__variable sriracha_9bad02da-module__Vayo6a__variable h-full antialiased\",\"children\":[[\"$\",\"head\",null,{\"children\":[[\"$\",\"meta\",null,{\"name\":\"theme-color\",\"content\":\"#fafafa\"}],[\"$\",\"meta\",null,{\"property\":\"og:logo\",\"content\":\"https://stacktips.com/brand/icon-dark.png\"}],[\"$\",\"script\",null,{\"type\":\"text/javascript\",\"suppressHydrationWarning\":true,\"dangerouslySetInnerHTML\":{\"__html\":\"(function(){try{var t=localStorage.getItem(\\\"theme\\\");if(t===\\\"dark\\\"||t===\\\"light\\\")document.documentElement.setAttribute(\\\"data-theme\\\",t);var resolved=t===\\\"dark\\\"||t===\\\"light\\\"?t:(window.matchMedia(\\\"(prefers-color-scheme: dark)\\\").matches?\\\"dark\\\":\\\"light\\\");var m=document.querySelector('meta[name=\\\"theme-color\\\"]');if(m)m.setAttribute(\\\"content\\\",resolved===\\\"dark\\\"?\\\"#000000\\\":\\\"#fafafa\\\")}catch(e){}})()\"}}]]}],[\"$\",\"body\",null,{\"className\":\"min-h-full flex flex-col bg-paper text-ink\",\"children\":[[\"$\",\"$L2\",null,{}],[\"$\",\"main\",null,{\"className\":\"flex-1\",\"children\":[\"$\",\"$L3\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L4\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[\"$\",\"div\",null,{\"className\":\"mx-auto flex max-w-3xl flex-col items-center px-4 py-24 text-center sm:py-32 sm:px-6\",\"children\":[[\"$\",\"p\",null,{\"className\":\"font-mono text-sm uppercase tracking-[0.14em] text-ink-faint\",\"children\":\"404\"}],[\"$\",\"h1\",null,{\"className\":\"mt-3 font-display text-balance text-4xl font-medium tracking-tighter text-ink sm:text-6xl\",\"children\":[\"NullPointerException\",[\"$\",\"span\",null,{\"className\":\"text-accent\",\"children\":\":\"}],\" page is null\"]}],[\"$\",\"p\",null,{\"className\":\"mt-5 max-w-[52ch] leading-relaxed text-ink-muted\",\"children\":\"We looked everywhere. This route never compiled — it may have moved, been renamed, or you free-typed a URL like it's 1999.\"}],[\"$\",\"div\",null,{\"className\":\"mt-10 w-full overflow-hidden rounded-xl border border-border bg-surface-strong text-left shadow-sm\",\"children\":[[\"$\",\"div\",null,{\"className\":\"flex items-center gap-1.5 border-b border-border px-4 py-3\",\"children\":[[\"$\",\"span\",null,{\"className\":\"size-3 rounded-full bg-red-400/80\",\"aria-hidden\":\"true\"}],[\"$\",\"span\",null,{\"className\":\"size-3 rounded-full bg-yellow-400/80\",\"aria-hidden\":\"true\"}],[\"$\",\"span\",null,{\"className\":\"size-3 rounded-full bg-terminal-green/80\",\"aria-hidden\":\"true\"}],[\"$\",\"span\",null,{\"className\":\"ml-2 font-mono text-xs text-ink-faint\",\"children\":\"stacktips — zsh\"}]]}],[\"$\",\"pre\",null,{\"className\":\"overflow-x-auto px-5 py-5 font-mono text-xs leading-relaxed text-ink-muted\",\"children\":[[\"$\",\"span\",null,{\"className\":\"text-terminal-green text-xs\",\"children\":\"$$\"}],\" curl -I https://stacktips.com\",[\"$\",\"$L5\",null,{}],\"\\n\",\"HTTP/1.1 404 Not Found\\n\\n\",\"Exception in thread \\\"main\\\" java.lang.PageNotFoundException\\n\",\"    at StackTips.Router.resolve(Router.java:404)\\n\",\"    at StackTips.App.render(App.java:1)\\n\",\"Caused by: this tutorial doesn't exist (yet).\\n\",[\"$\",\"span\",null,{\"className\":\"text-terminal-green\",\"children\":\"$$ \"}],[\"$\",\"span\",null,{\"className\":\"animate-pulse text-terminal-green\",\"children\":\"▌\"}]]}]]}],[\"$\",\"div\",null,{\"className\":\"mt-10 flex flex-wrap items-center justify-center gap-3\",\"children\":[[\"$\",\"$L6\",null,{\"href\":\"/\",\"className\":\"inline-flex items-center gap-2 rounded-full bg-accent px-5 py-2.5 text-sm font-medium text-accent-ink transition-opacity hover:opacity-90\",\"children\":[\"$L7\",\"Back to home\"]}],\"$L8\"]}]]}],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}],\"$L9\",\"$La\"]}],\"$Lb\"]}]]}],{\"children\":[\"$Lc\",{\"children\":[\"$Ld\",{}
1,null,false,null]},null,false,\"$@e\"]},null,false,null],\"$Lf\",false]],\"m\":\"$undefined\",\"G\":[\"$10\",[\"$L11\"]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"F3wKBLU2MhWdE3GHbCSHD\"}\n"])</script>
1<script>self.__next_f.push([1,"12:I[5014,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\",\"/_next/static/chunks/0d40cfc_crt89.js\"],\"default\"]\n13:I[77180,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\"],\"WebVitals\"]\n14:I[97287,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\"],\"Analytics\"]\n15:I[5021,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\",\"/_next/static/chunks/0a3lk9460xb-w.js\"],\"PaginatedArticleList\"]\n16d:I[97367,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\"],\"ViewportBoundary\"]\n16f:I[97367,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\"],\"MetadataBoundary\"]\n170:\"$Sreact.suspense\"\n7:[\"$\",\"$L12\",null,{\"ref\":\"$undefined\",\"iconNode\":[[\"path\",{\"d\":\"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8\",\"key\":\"5wwlr5\"}],[\"path\",{\"d\":\"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z\",\"key\":\"r6nss1\"}]],\"className\":\"lucide-house size-4\",\"aria-hidden\":\"true\"}]\n8:[\"$\",\"$L6\",null,{\"href\":\"/topics\",\"className\":\"inline-flex items-center gap-2 rounded-full bg-surface px-5 py-2.5 text-sm font-medium text-ink transition-colors hover:bg-surface-strong\",\"children\":[[\"$\",\"$L12\",null,{\"ref\":\"$undefined\",\"iconNode\":[[\"circle\",{\"cx\":\"12\",\"cy\":\"12\",\"r\":\"10\",\"key\":\"1mglay\"}],[\"path\",{\"d\":\"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z\",\"key\":\"9ktpf1\"}]],\"className\":\"lucide-compass size-4\",\"aria-hidden\":\"true\"}],\"Browse topics\"]}]\n9:[\"$\",\"footer\",null,{\"className\":\"bg-surface/80\",\"children\":[\"$\",\"div\",null,{\"className\":\"mx-auto flex max-w-7xl flex-col gap-4 px-4 py-10 text-sm text-ink-muted sm:flex-row sm:items-center sm:justify-between sm:px-6\",\"children\":[[\"$\",\"p\",null,{\"children\":[\"© \",2026,\" StackTips. Built by\",\" \",[\"$\",\"a\",null,{\"href\":\"https://github.com/nilandev\",\"target\":\"_blank\",\"rel\":\"noopener noreferrer\",\"className\":\"hover:text-ink\",\"children\":\"Nilanchala\"}],\" \",\"with love\"]}],[\"$\",\"nav\",null,{\"className\":\"flex gap-5\",\"children\":[[\"$\",\"$L6\",null,{\"href\":\"/articles\",\"className\":\"hover:text-ink\",\"children\":\"Tutorials\"}],[\"$\",\"$L6\",null,{\"href\":\"/courses\",\"className\":\"hover:text-ink\",\"children\":\"Courses\"}],[\"$\",\"$L6\",null,{\"href\":\"/topics\",\"className\":\"hover:text-ink\",\"children\":\"Topics\"}]]}]]}]}]\na:[\"$\",\"$L13\",null,{}]\nb:[\"$\",\"$L14\",null,{}]\nc:[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L3\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L4\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}]\n16:T312a,"])</script>
1<script>self.__next_f.push([1,"\nIn the last chapter, we saw how logging works in Spring Boot. Now let's put everything we've built so far to use and create our first REST API.\n\n## What Is a REST API in Spring Boot?\n\nA REST API lets other applications talk to your Spring Boot app over HTTP. A client sends a request to a URL, and your app sends back data, usually as JSON or XML. It's the standard way a frontend, a mobile app, or another service talks to a backend application like the one we're building.\n\nRemember the Whitelabel error page we hit back in [Chapter 3](/articles/setting-up-your-first-spring-boot-project) when we opened `http://localhost:8080`? That happened because there was no endpoint to handle the request. Let's fix that now.\n\n## `@RestController` and `@GetMapping` Annotations Explained\n\nBack in [Chapter 6](/articles/spring-boot-annotations), we previewed two annotations we'd need for this: `@RestController` and `@GetMapping`. Here's what they actually do.\n\n`@RestController` marks a class as a REST endpoint handler. It's a specialization of `@Controller` (itself a `@Component`), so Spring's component scanning picks it up automatically, just like any other bean. It also tells Spring to write every method's return value straight into the HTTP response body, instead of resolving it to an HTML view.\n\n`@GetMapping(\"/path\")` maps HTTP GET requests for that path to the method it's placed on.\n\n## Creating Your First REST Endpoint\n\nAdd this `HelloController` class to your project, right alongside the main class containing `@SpringBootApplication`:\n\n\n```java\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class HelloController {\n\n    @GetMapping(\"/hello\")\n    public String sayHello() {\n        return \"Hello, Spring Boot!\";\n    }\n}\n```\n\nRun the app (`./gradlew bootRun`) and open `http://localhost:8080/hello` in your browser. Instead of the Whitelabel Error Page, you'll see:\n\n```text\nHello, Spring Boot!\n```\n\nThat's your first working REST endpoint.\n\n### Returning a JSON Response from a Spring Boot Controller\n\nThis String response is sent back as `text/plain`, not JSON — which is fine for a quick test, but not what most real-world APIs return.\n\nTo return JSON, just return any Java object other than a `String` — a `Map`, a `List`, a record, a class with getters. Spring Boot uses the Jackson library added on classpath (via `spring-boot-starter-web`) to serialize these Java objects into JSON automatically.\n\nLet's expand `sayHello()` to return a small status payload instead of a plain greeting:\n\n```java\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport java.util.Map;\n\n@RestController\npublic class HelloController {\n\n    @GetMapping(\"/hello\")\n    public Map\u003cString, Object\u003e sayHello() {\n        return Map.of(\n                \"message\", \"Hello, Spring Boot!\",\n                \"status\", \"UP\",\n                \"timestamp\", System.currentTimeMillis()\n        );\n    }\n}\n```\n\nRun the app again and refresh `http://localhost:8080/hello`. You'll see real JSON this time:\n\n```json\n{\n  \"message\": \"Hello, Spring Boot!\",\n  \"status\": \"UP\",\n  \"timestamp\": 1755400000000\n}\n```\n\n## Testing REST API with cURL\n\nA browser works fine for `GET` requests, but it won't show you response headers. For that, we could either use a REST client like Postman or the `curl` command:\n\n```bash\ncurl -i http://localhost:8080/hello\n```\n\nThe `-i` flag prints the response headers along with the body — look for `Content-Type: application/json`, which is Spring Boot confirming it serialized your response as JSON:\n\n```shell\nHTTP/1.1 200 OK\nContent-Type: application/json\n...\n\n{\"message\":\"Hello, Spring Boot!\",\"status\":\"UP\",\"timestamp\":1
1755400000000}\n```\n\nNotice we didn't have to set anything to get a `200 OK` back — Spring Boot returns that by default whenever a controller method completes without throwing an exception. \n\nWe'll get into customizing status codes and handling errors properly starting in [Chapter 19, Centralized Error Handling](/articles/centralized-error-handling-in-spring-boot-with-controlleradvice).\n\n\n## Building a CRUD REST API with Spring Boot\nIn RESTful architecture, HTTP is not just a transport protocol, but it is language. Different actions are expressed using different HTTP Verbs (or HTTP methods). These verbs map directly to the classic CRUD (Create, Read, Update, Delete) database operations:\n\n\n| HTTP Verb | Operation | Spring Annotation | Description |\n| :--- | :--- | :--- | :--- |\n| `GET` | Read | `@GetMapping` | Read data without altering the server state. |\n| `POST` | Create | `@PostMapping` | Send new data to the server to create a resource. |\n| `PUT` | Update | `@PutMapping` | Replace or update an existing resource. |\n| `PATCH` | Partial Update | `@PatchMapping` | Apply partial modifications to an existing resource. |\n| `DELETE` | Delete | `@DeleteMapping` | Remove a resource from the server. |\n\nLet's build an interactive Weather API. We will use a mock service that holds an in-memory mutable state so you can actually create, read, update, and reset forecasts in real time without using any database yet.\n\n\n### Creating a DTO with a Java Record\n\nLet's create a DTO class to hold our weather information. Using Java record is perfect here: Jackson has built-in support for records, so it serializes each record component (e.g. `location()`, `temperatureCelsius()`) straight into a matching JSON property, with no getters, no-args constructor, or field annotations needed. A regular class would need to expose either public getters or public fields for Jackson to do the same.\n\n```java\npublic re
1cord WeatherForecast(String location, double temperatureCelsius, String condition) {\n\n}\n```\n\n\n### Building a Mock Service Layer\n\nNext, we'll build a service that maintains a mutable \"current\" forecast, plus a running history of every forecast that's ever been logged via `POST`. This lets our `POST`, `PUT`, and `DELETE` methods modify real data in memory:\n\n```java\nimport org.springframework.stereotype.Service;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n@Service\npublic class WeatherService {\n\n    private WeatherForecast currentForecast = new WeatherForecast(\"New York\", 22.5, \"Partly Cloudy\");\n    private final List\u003cWeatherForecast\u003e forecastHistory = new ArrayList\u003c\u003e();\n\n    public WeatherForecast getForecast() {\n        return this.currentForecast;\n    }\n\n    public WeatherForecast addForecast(WeatherForecast newForecast) {\n        this.forecastHistory.add(newForecast);\n        this.currentForecast = newForecast;\n        return this.currentForecast;\n    }
1\n\n    public WeatherForecast updateForecast(WeatherForecast newForecast) {\n        this.currentForecast = newForecast;\n        return this.currentForecast;\n    }\n\n    public List\u003cWeatherForecast\u003e getForecastHistory() {\n        return this.forecastHistory;\n    }\n\n    public void resetForecast() {\n        this.currentForecast = new WeatherForecast(\"New York\", 0.0, \"Unknown\");\n    }\n}\n```\n\nNotice `addForecast()` and `updateForecast()` both change the current forecast, but only `addForecast()` logs the change to `forecastHistory`. That's the real difference between the two: `POST` creates a new, independent record, while `PUT` just overwrites the current one in place.\n\n\n### Wiring CRUD Endpoints in the Controller\n\nNow, let's create a `WeatherController` to expose these operations. We'll map `GET`, `POST`, `PUT`, and `DELETE` requests to the `/weather` base path, plus a small `GET` on `/weather/history` to inspect the log:\n\n```java\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.List;\n\n@RestController\n@RequestMapping(\"/weather\")\npublic class WeatherController {\n\n    private final WeatherService weatherService;\n\n    public WeatherController(WeatherService weatherService) {\n        this.weatherService = weatherService;\n    }
1\n\n    @GetMapping\n    public WeatherForecast getWeather() {\n        return weatherService.getForecast();\n    }\n\n    @PostMapping\n    public WeatherForecast addWeather(@RequestBody WeatherForecast newForecast) {\n        return weatherService.addForecast(newForecast);\n    }\n\n    @PutMapping\n    public WeatherForecast updateWeather(@RequestBody WeatherForecast newForecast) {\n        return weatherService.updateForecast(newForecast);\n    }\n\n    @DeleteMapping\n    public String resetWeather() {\n        weatherService.resetForecast();\n        return \"Weather forecast has been reset to default values.\";\n    }\n\n    @GetMapping(\"/history\")\n    public List\u003cWeatherForecast\u003e getWeatherHistory() {\n        return weatherService.getForecastHistory();\n    }\n}\n```\n\nLet's call out four crucial details in this controller:\n\n- `@RequestMapping(\"/weather\")` sets the base URL path for this entire class.\n- Method-level annotations such as `@GetMapping`, `@PostMapping`, `@PutMapping`, and `@DeleteMapping`, used without an explicit path, map directly to that base path — making them handle `GET /weather`, `POST /weather`, `PUT /weather`, and `DELETE /weather` respectively.\n- `@GetMapping(\"/history\")` does take an explicit path, so it's appended to the class-level base path, giving us `GET /weather/history` — a second endpoint living alongside the others.\n- `@RequestBody` on `addWeather()` and `updateWeather()` tells Spring to parse the incoming JSON payload in the request body and deserialize it directly into our `WeatherForec
1ast` Java record.\n\n### Testing the CRUD REST API with curl\nFor testing these API's we can either use REST clients like Postman or cURL API clients.\n\n#### Step 1: Fetch the Current Forecast (GET)\n\nLet's see what the initial data looks like:\n\n```shell\ncurl -i http://localhost:8080/weather\n```\nResponse:\n\n```shell\nHTTP/1.1 200 OK\nContent-Type: application/json\n...\n\n{\"location\":\"New York\",\"temperatureCelsius\":22.5,\"condition\":\"Partly Cloudy\"}\n```\n\n#### Step 2: Log a New Forecast (POST)\nNow, let's send a POST request with a JSON payload to create a new forecast entry:\n\n```shell\ncurl -i -X POST \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"location\":\"Paris\",\"temperatureCelsius\":18.0,\"condition\":\"Cloudy\"}' \\\n  http://localhost:8080/weather\n```\n\nResponse:\n\n```shell\nHTTP/1.1 200 OK\nContent-Type: application/json\n...\n\n{\"location\":\"Paris\",\"temperatureCelsius\":18.0,\"condition\":\"Cloudy\"}\n```\n\nParis is now the current forecast, and it's also been logged to history — we'll confirm that in Step 5.\n\n#### Step 3: Update the Forecast (PUT)\nNow, let's send a PUT request to overwrite the current forecast in place:\n\n```shell\ncurl -i -X PUT \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"location\":\"London\",\"temperatureCelsius\":14.0,\"condition\":\"Rainy\"}' \\\n  http://localhost:8080/weather\n```\n\nResponse:\n\n```shell\nHTTP/1.1 200 OK\nContent-Type: application/json\n...\n\n{\"location\":\"London\",\"temperatureCelsius\":14.0,\"condition\":\"Rainy\"}\n```\n\n#### Step 4: Verify the State Change (GET)\nTo prove our stateful in-memory service successfully stored the updated data, run another standard GET request:\n\n```shell\ncurl -i http://localhost:8080/weather\n```\n\nResponse:\n\n```shell\nHTTP/1.1 200 OK\nContent-Type: application/json\n...\n\n{\"location\":\"London\",\"temperatureCelsius\":14.0,\"condition\":\"Rainy\"}\n```\n\nIt changed! Your API successfully updated its in-memory record.\n\n#### Step 5: Check the Forecast History (GET)\nNow let'
1s inspect the history log:\n\n```shell\ncurl -i http://localhost:8080/weather/history\n```\n\nResponse:\n\n```shell\nHTTP/1.1 200 OK\nContent-Type: application/json\n...\n\n[{\"location\":\"Paris\",\"temperatureCelsius\":18.0,\"condition\":\"Cloudy\"}]\n```\n\nOnly Paris shows up here — the `POST` from Step 2 got logged, but the `PUT` from Step 3 didn't. That's `POST` and `PUT` behaving exactly as they're meant to: one creates a new record, the other replaces an existing one in place.\n\n#### Step 6: Reset the Forecast (DELETE)\nFinally, let's trigger our reset action by sending a DELETE request:\n\n```shell\ncurl -i -X DELETE http://localhost:8080/weather\n```\n\nResponse:\n\n```shell\nHTTP/1.1 200 OK\nContent-Type: text/plain;charset=UTF-8\n...\n\nWeather forecast has been reset to default values.\n```\n\n## Summary\n\nIn this chapter, we built our first REST endpoint, saw the difference between a plain-text and JSON reponse. \n\nIn the next chapter, we'll fix that: [Handling Request Parameters, Path Variables, and Request Bodies](/articles/handling-request-parameters-path-variables-and-request-body-in-spring-boot) covers how to accept input from the client so your endpoints can actually respond to what's being asked.\n"])</script>
1<script>self.__next_f.push([1,"17:T135a,"])</script>
1<script>self.__next_f.push([1,"\nIn the previous chapter, we made sure Java, an IDE, and a build tool were in place. Now let's put them to use and bootstrap your first Spring Boot project.\n\nThere are a few ways to generate a new Spring Boot project:\n\n-   **Spring Initializr** — a web-based project generator at [start.spring.io](https://start.spring.io)\n-   **IDE-integrated generator** — IntelliJ IDEA, Eclipse (with Spring Tools), and VS Code (with the Spring Boot Extension Pack) all embed the same Spring Initializr under the hood\n-   **Spring CLI** — a command-line tool for generating projects, useful for scripting or quick prototypes\n\n```mermaid\ngraph LR\n    A[Choose a generator] --\u003e B[start.spring.io]\n    A --\u003e C[IDE-integrated wizard]\n    A --\u003e D[Spring CLI]\n    B --\u003e E[Download \u0026 unzip project]\n    C --\u003e E\n    D --\u003e E\n    E --\u003e F[Open project in your IDE]\n```\n\nAll three produce the exact same project — an IDE wizard is just a more convenient shortcut around Spring Initializr. We'll walk through both the web UI and the IntelliJ wizard below; pick whichever you're more comfortable with.\n\n## Option 1: Using Spring Initializr\n\nHead over to [start.spring.io](https://start.spring.io) and fill in the project details:\n\n-   **Project:** Gradle - Groovy (this course uses Gradle; choose Maven if you'd rather follow along with that instead — every concept still applies)\n-   **Language:** Java\n-   **Spring Boot:** the latest stable version shown\n-   **Project Metadata:**\n    -   Group: `com.stacktips`\n    -   Artifact: `hello-spring`\n    -   Name: `hello-spring`\n    -   Package name: `com.stacktips.hello_spring`\n    -   Packaging: Jar\n    -   Java: 17\n-   **Dependencies:** add **Spring Web** — this pulls in everything needed to build a web application or REST API, including an embedded Tomcat server\n\n![Generating a project using Spring Initializr](/media/media/attachments/2024/10/24/32-spring-initializer.jpg)\n\nOnce everything is filled in, click **Generate**. This downloads a `.zip` file containing your project — unzip it and open the folder in your IDE.\n\n## Option 2: Using the IntelliJ IDEA Project Wizard\n\nIf you're using IntelliJ IDEA, you don't need to leave the IDE at all. Go to **File → New → Project**, select **Spring Boot** from the project types on the left, and fill in the same metadata as above. IntelliJ generates the project directly using Spring Initializr behind the scenes and opens it for you automatically.\n\n![Creating a Spring Boot project from IntelliJ IDEA](/media/media/attachments/2024/10/24/33-create-spring-project-using-intellij-idea.jpg)\n\nThis is the quickest way to get started since there's no separate download-and-unzip step.\n\n## Running the Application\n\nOnce the project is open in your IDE, give it a minute to download the dependencies defined in `build.gradle` (or `pom.xml` if you chose Maven). You can run the application in any of the following ways:\n\n**1. From your IDE**\n\nOpen `HelloSpringApplication.java` and click the **Run** button next to the `main()` method (or use the green play icon in the toolbar).\n\n![Running a Spring Boot application from IntelliJ IDEA](/media/media/attachments/2024/10/24/34-running-spring-boot-from-intellij.jpg)\n\n**2. From the command line, using the Gradle wrapper**\n\nEvery project generated by Spring Initializr includes a Gradle (or Maven) wrapper, so you don't need Gradle or Maven installed separately.\n\n```bash\n# macOS / Linux\n./gradlew bootRun\n\n# Windows\ngradlew.bat bootRun\n```\n\nIf you generated a Maven project instead, the equivalent command is:\n\n```bash\n# macOS / Linux\n./mvnw spring-boot:run\n\n# Windows\nmvnw.cmd spring-boot:run\n```\n\n**3. By building and running the packaged jar**\n\n```bash\n# macOS / Linux\n./gradlew build\n\n# Windows\ngradlew.bat build\n```\n\n```bash\njava -jar build/libs/hello-spring-0.0.1-SNAPSHOT.jar\n```\n\nWe'll cover packaging and running Spring Boot applications in more detail in a later chapter.\n\n## Verifying It Worked\n\nWhichever method you used, you should see Spring Boot's startup banner in the console, ending with a line similar to:\n\n```\nTomcat started on port(s): 8080 (http) with context path ''\nStarted HelloSpringApplication in 1.234 seconds\n```\n\nNow open [http://localhost:8080](http://localhost:8080) in your browser. You'll see a **Whitelabel Error Page** with a 404 status — and that's expected. It means the embedded server is up and handling requests; we just haven't defined any endpoints yet. We'll fix that when we build our first REST API later in this course.\n\n## Summary\n\nIn this chapter, you bootstrapped your first Spring Boot project using both Spring Initializr and the IntelliJ IDEA wizard, and ran it using three different methods — from the IDE, via the Gradle wrapper, and as a packaged jar.\n\nIn the next chapter, we'll open up the project and break down exactly what each file and folder does in [Understanding Spring Boot Project Structure](/articles/understanding-spring-boot-project-structure).\n"])</script>
1<script>self.__next_f.push([1,"18:T1ffe,"])</script>
1<script>self.__next_f.push([1,"\nIn the last chapter, we listed out the annotations you'll use all the time in Spring Boot, including `@Value`. In this chapter, we'll actually use it and see how Spring Boot loads and manages configuration for your application.\n\n## Configuring with Properties Files\n\nSpring Boot offers a flexible approach to managing properties from various sources. By default, it loads the properties from the `application.properties` file. It also considers the OS environment variables, Java System properties and command-line arguments.\n\nThe resources are loaded in the following order of priority, from highest to lowest:\n\n1.  Command-line arguments\n2.  Java system properties\n3.  OS environment variables\n4.  `application.properties` located outside the packaged application\n5.  `application.properties` packaged within the application\n\nIn other words, if the same property is set in more than one place, the one higher up this list wins.\n\n```mermaid\ngraph TD\n    A[\"Command-line arguments\"] --\u003e B[\"Java system properties\"]\n    B --\u003e C[\"OS environment variables\"]\n    C --\u003e D[\"application.properties outside the jar\"]\n    D --\u003e E[\"application.properties inside the jar\"]\n```\n\nIn the following example, we will create a weather service to load properties from the `application.properties` file.\n\n1.  Add the following properties inside `application.properties` file.\n\n```properties\nweather.api.key=default-api-key\nweather.default.city=New York\nweather.units=imperial\n```\n\n2.  Let us create a `WeatherService` class and load the properties from `application.properties` file\n\n```java\n@Service\npublic class WeatherService {\n\n    @Value(\"${weather.api.key}\")\n    private String apiKey;\n\n    @Value(\"${weather.default.city}\")\n    private String defaultCity;\n\n    @Value(\"${weather.units}\")\n    private String units;
1\n\n    public String getWeatherForecast() {\n        return String.format(\"Weather forecast for %s: Sunny, 25°%s. API Key: %s\",\n                defaultCity, units.equals(\"metric\") ? \"C\":\"F\", apiKey);\n    }\n}\n```\n\nThe `@Value` annotation will instruct Spring to detect and load the value of that property.\n\nIn this example, it will detect the property `weather.api.key` inside the `application.properties` file and load the value to the variable `apiKey`.\n\nWe can define a default value for the `@Value` annotation by adding a colon. Eg. `@Value(\"${weather.api.key:defaultKey}\")`. In this case, it will use `defaultKey` as the value when there's no property defined with the key `weather.api.key`.\n\nIf there's no property defined and no default value given, it will throw the following exception:\n\n```text\nCaused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'weatherService': Injection of autowired dependencies failed\n    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:515) ~[spring-beans-6.1.13.jar:6.1.13]\n    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1439) ~[spring-beans-6.1.13.jar:6.1.13]\n    ... omitted\nCaused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'weather.api.key' in value \"${weather.api.key}\"\n```\n\nTo see the properties actually get loaded, add a `CommandLineRunner` bean that calls `getWeatherForec
1ast()` on startup:\n\n```java\n@Component\npublic class AppRunner implements CommandLineRunner {\n\n    private final WeatherService weatherService;\n\n    public AppRunner(WeatherService weatherService) {\n        this.weatherService = weatherService;\n    }\n\n    @Override\n    public void run(String... args) {\n        System.out.println(weatherService.getWeatherForecast());\n    }\n}\n```\n\nRun the app and you'll see this printed to the console:\n\n```text\nWeather forecast for New York: Sunny, 25°F. API Key: default-api-key\n```\n\n## Using `@ConfigurationProperties` Instead of `@Value`\n\n`@Value` works fine for one or two properties, but it gets repetitive once you have a whole group of related ones, like our three `weather.*` properties. For that, `@ConfigurationProperties` is the better to bind a whole prefix straight into a class:\n\n```java\n@Component\n@ConfigurationProperties(prefix = \"weather\")\npublic class WeatherProperties {\n\n    private String apiKey;\n    private String defaultCity;\n    private String units;\n\n    // getters and setters\n}\n```\n\nSpring Boot maps `weather.api.key` to `apiKey`, `weather.default.city` to `defaultCity`, and so on, matching the dotted property name to the camelCase field name. You can then inject `WeatherProperties` anywhere, the same way you'd inject any other bean, instead of repeating `@Value` on every field.\n\n## Configuring with YAML\n\nSpring boot also natively supports YAML files for managing configuration properties. YAML files use the same principle as `.properties` files.\n\nThe application.properties file content can be written using YAML as:\n\n**application.yaml**\n\n```yaml\nweather:\n  api:\n    key: default-api-key\n  default:\n    city: New York\n  units: imperial\n```\n\n## Loading an External Configuration File\n\nSpring Boot also picks up an `application.properties` file placed outside your project, not just the one packaged inside it. The easiest way to see this is to package the app as an executable jar and place an `application.properties` file next to it — Spring Boot will pick it up automatically without you having to point to it.\n\nBuild and run the jar:\n\n```bash\njava -jar hello-spring-0.0.1-SNAPSHOT.jar\n```\n\nIf an `application.properties` file exists in the same folder as the jar, Spring Boot loads it and merges it with the one already packaged inside the jar, taking priority over it as we saw in the priority list above.\n\n## Environment-Specific Configuration with Profiles\n\nSpring boot also allows you to isolate the environment-specific configurations using profiles. For example, if you want to use different configurations for dev, QA and production servers, you can create 3 different files (eg. `application-dev.properties`, `application-qa.properties` and `application-prod.properties`) to have different configurations for each environment.\n\nThe profile to activate is set using the `spring.profiles.active` property. You can pass it as a command-line argument:\n\n```bash\njava -jar hello-spring-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev\n```\n\nor as an environment variable:\n\n```bash\nexport SPRING_PROFILES_ACTIVE=dev\n```\n\nThe profile-specific `application-{profile}.properties` file takes precedence over the non-profile-specific one, but everything still follows the same overall order — a profile file doesn't outrank an environment variable or a command-line argument, only the plain `application.properties` file it's paired with.\n\nWhen profile-specific properties are defined, the resources are loaded in the following order of priority, from highest to lowest:\n\n1.  Command-line arguments\n2.  Java system properties\n3.  OS environment variables\n4.  `application-{profile}.properties` outside the packaged application\n5.  `application.properties` located outside the packaged application\n6.  `application-{profile}.properties` packaged inside the application\n7.  `application.properties` packaged within the application\n\n## Overriding Configuration from the Command Line\n\nTo override configuration using the command-line arguments, you can simply add `--key=value` argument to your java -jar command.\n\n```bash\njava -jar hello-spring-0.0.1-SNAPSHOT.jar --weather.api.key=my-key\n```\n\nCommand-line arguments always win — they sit at the top of every priority list we've looked at in this chapter, so they override everything else.\n\n## Summary\n\nIn this chapter, we saw how Spring Boot loads configuration from properties files, YAML, environment variables, and command-line arguments, and in what order it picks a winner when the same property is set in more than one place. We also looked at how profiles let you swap configuration per environment.\n\nIn the next chapter, we'll look at [Logging in Spring Boot](/articles/logging-in-spring-boot), including how to control log levels per profile using what we just learned here.\n"])</script>
1<script>self.__next_f.push([1,"19:T1ea6,"])</script>
1<script>self.__next_f.push([1,"\nBefore we dive into developing Spring Boot applications, please ensure you have the following prerequisites in place:\n\n-   **Java**: Version 17 or above\n-   **IDE** (Integrated Development Environment)\n-   **Build Tool**: Maven or Gradle\n\nSpring Boot 3.x requires Java 17 as a minimum baseline and supports newer LTS releases as they're published. Always check the [Spring Boot releases page](https://spring.io/projects/spring-boot#learn) or [start.spring.io](https://start.spring.io) for what's current when you start a new project.\n\nCheck if you have Java installed using the following command.\n\n```bash\njava --version\n```\n\nIf Java is not installed, you can follow the installation process from my blog post: [How to Install Java for MacOS and Windows?](https://stacktips.com/articles/how-to-install-java-for-macos-and-windows)\n\nIf you're installing Java for the first time, pick a free OpenJDK distribution such as [Eclipse Temurin](https://adoptium.net/) or Amazon Corretto — either works fine for Spring Boot development. Make sure you install the **JDK** (Java Development Kit), not just the JRE, since the JDK includes the compiler and tools needed to build applications.\n\n### IDE (Integrated Development Environment)\n\nAn Integrated Development Environment (IDE) is an all-in-one software tool for writing code. Think of it as a supercharged text editor built for developers. It helps you to write code faster, debug and fix bugs easily, keep files organized and keep all your commands in one place. \n\nFor Spring Boot application development, we have several IDE options available:\n\n-   **VSCode** - Free but requires [Extension Pack for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack) and the [Spring Boot Extension Pack](https://marketplace.visualstudio.com/items?itemName=vmware.vscode-boot-dev-pack)\n-   **Eclipse** - Free but requires [Spring Tools](https://marketplace.eclipse.org/content/spring-tools-4) plugin\n-   **IntelliJ IDEA** - Support both Free Community Edition and Licensed Ultimate Edition. It includes built-in Spring Boot support so no additional plugin installation required.\n\nI prefer IntelliJ IDEA, as it stands out as one of the most advanced and widely used IDEs for Java developers. If you haven't installed it yet, you can download the Community Edition of IntelliJ [here](https://www.jetbrains.com/idea/download/?section=mac). Throughout this course, screenshots and instructions will reference IntelliJ IDEA, but everything shown works the same way in VSCode or Eclipse.\n\n## Choosing the Right Build Tools: Maven vs. Gradle\n\nBuild tools play a crucial role in software development. Build tools are used to automate the process of compiling, testing, packaging, and deploying your application. It can save a lot of time, especially when working with a large, distributed team.\n\nUsing build tools we can simplify the process of managing project dependencies. It helps to automate the process of including external libraries in your project and resolving the dependencies automatically.  \nPrimarily there are two popular build tool choices for writing Java applications; Maven and Gradle.\n\n### Maven\n\nMaven is a popular build automation tool used primarily for Java projects. Maven is almost 20 years old and was first introduced in 2004.\n\nIt uses an XML file called a pom.xml (Project Object Model) to define the project's configuration. The `pom.xml` file serves as the central configuration file for managing dependencies, plugins and build configurations for the Java project. It contains details about the project, including its dependencies, plugins, build lifecycle, and other relevant project metadata.\n\n**pom.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cproject xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\"\u003e\n  \u003cmodelVersion\u003e4.0.0\u003c/modelVersion\u003e\n  \u003cparent\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-parent\u003c/artifactId\u003e\n    \u003cversion\u003e3.3.4\u003c/version\u003e\n    \u003crelativePath/\u003e \u003c!-- lookup parent from repository --\u003e\n  \u003c/parent\u003e\n  \u003cgroupId\u003ecom.stacktips\u003c/groupId\u003e\n  \u003cartifactId\u003ehello-spring\u003c/artifactId\u003e\n  \u003cversion\u003e0.0.1-SNAPSHOT\u003c/version\u003e\n  \u003cname\u003ehello-spring\u003c/name\u003e\n  \u003cdescription\u003eDemo project for Spring Boot\u003c/description\u003e\n  \u003cproperties\u003e\n    \u003cjava.version\u003e17\u003c/java.version\u003e\n  \u003c/properties\u003e\n  \u003cdependencies\u003e\n    \u003cdependency\u003e\n      \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n      \u003cartifactId\u003espring-boot-starter-web\u003c/artifactId\u003e\n    \u003c/dependency\u003e\n\n    \u003cdependency\u003e\n      \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n      \u003cartifactId\u003espring-boot-starter-test\u003c/artifactId\u003e\n      \u003cscope\u003etest\u003c/scope\u003e\n    \u003c/dependency\u003e\n  \u003c/dependencies\u003e\n\n  \u003cbuild\u003e\n    \u003cplugins\u003e\n      \u003cplugin\u003e\n        \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n        \u003cartifactId\u003espring-boot-maven-plugin\u003c/artifactId\u003e\n      \u003c/plugin\u003e\n    \u003c/plugins\u003e\n  \u003c/build\u003e\n\n\u003c/project\u003e\n```\n\n### Gradle\n\nGradle is yet another build automation tool, it was first introduced in 2007. Gradle uses either **Groovy** or **Kotlin DSL** (Domain-Specific Language) for defining build scripts. Gradle maintains the dependency configurations in build.gradle file.\n\nThe `build.gradle` file is typically stored in the project's root directory. An example of a Gradle build file for a Spring Boot application follows.\n\n**build.gradle**\n\n```groovy\nplugins {\n  id 'java'\n  id 'org.springframework.boot' version '3.3.4'\n  id 'io.spring.dependency-management' version '1.1.6'\n}\n\ngroup = 'com.stacktips'\nversion = '0.0.1-SNAPSHOT'\n\njava {\n  toolchain {\n    languageVersion = JavaLanguageVersion.of(17)\n  }\n}\n\nrepositories {\n  mavenCentral()\n}\n\ndependencies {\n  implementation 'org.springframework.boot:spring-boot-starter-web'\n  testImplementation 'org.springframework.boot:spring-boot-starter-test'\n  testRuntimeOnly 'org.junit.platform:junit-platform-launcher'\n}\n\ntasks.named('test') {\n  useJUnitPlatform()\n}\n```\n\nThough Gradle is relatively new, it has gained popularity due to its ability to handle complex build automation and dependency management capability.\n\n### Choosing Between Maven and Gradle\n\nWhile Maven is a well-established standard in the Java community, Gradle has emerged as a modern build system that has gained significant popularity in recent years. Both Gradle and Maven are powerful tools, making them suitable for larger and more complex projects.\n\nThe choice between Maven and Gradle for Spring Boot development depends on your personal preferences and the specific needs of your project.\n\n-   Maven uses an XML file (pom.xml) for configuration, which can become verbose and complex for larger projects.\n-   Maven tends to have slower build times due to its less efficie
1nt handling of incremental builds and parallel execution. Read more [here](https://gradle.org/maven-vs-gradle/#:~:text=Improving%20build%20time%20is%20one,for%20work%20avoidance%20and%20incrementality)\n-   Choose Gradle if you prefer modern, expressive DSL for configuration (Groovy or Kotlin).\n\n![Comparison of Maven and Gradle build tools](/media/media/attachments/2024/10/24/23-maven-vs-gradle.jpg)\n\n**Which one should you use in this course?** \nEither works, but this course uses **Gradle** for its project examples — you'll see a `build.gradle` file in the project structure walkthrough in the next couple of chapters. If you'd rather follow along with Maven, that's fine too: every concept we cover works identically regardless of build tool, and Spring Initializr lets you generate the same project with either one.\n\n---\n\nNow that your Java version, IDE, and build tool are sorted, you're ready to create your first Spring Boot project. In the next lesson, we'll use Spring Initializr to generate a project and open it in your IDE.\n"])</script>
1<script>self.__next_f.push([1,"1a:T235b,"])</script>
1<script>self.__next_f.push([1,"\n### 1. What are the key features introduced in Java 17?\n\nJava 17 introduced several important features including:\n\n-   Sealed Classes- Restricts which classes can inherit from a sealed class\n-   Pattern Matching for switch: Allows more expressive and concise switch statements and reduces boilerplate code in type-checking scenarios\n-   Records: Provides a compact syntax for creating immutable data classes\n-   Text Blocks: Allows multi-line string literals without escape characters - Improved Random Number Generators: Provides a new interface and implementations for random number generation\n\n### 2. Explain the concept of text blocks in Java. How do they improve code readability?\n\nText blocks in Java improve the way multiline strings are handled in code. Traditionally very difficult to read strings that span across multiple lines and require preserving formatting.\n\nJava 17 introduced triple quotes (`\"\"\"`). Text inside triple quotes is called text blocks. The compiler automatically strips incidental indentation and preserves formatting.\n\n```java\nString query =  \"SELECT e.employee_id, e.first_name, e.last_name, \\n\" +\n                \"       d.department_name, j.job_title, \\n\" +\n                \"       e.salary, e.hire_date \\n\" +\n                \"FROM employees e \\n\" +\n                \"JOIN departments d ON e.department_id = d.department_id \\n\" +\n                \"JOIN jobs j ON e.job_id = j.job_id \\n\" +\n                \"WHERE e.salary \u003e 50000 \\n\" +\n                \"  AND e.hire_date \u003e '2020-01-01' \\n\" +\n                \"  AND d.department_name IN ('Sales', 'Marketing', 'IT') \\n\" +\n                \"ORDER BY e.salary DESC, e.last_name ASC\";\n\n// With text blocks\nString query = \"\"\"\n        SELECT e.employee_id, e.first_name, e.last_name,\n               d.department_name, j.job_title,\n               e.salary, e.hire_date\n        FROM employees e\n        JOIN departments d ON e.department_id = d.department_id\n        JOIN jobs j ON e.job_id = j.job_id\n        WHERE e.salary \u003e 50000\n          AND e.hire_date \u003e '2020-01-01'\n          AND d.department_name IN ('Sales', 'Marketing', 'IT')\n        ORDER BY e.salary DESC, e.last_name ASC\n        \"\"\";\n```\n\n### 3. What are the Records in Java?\n\nRecords is a new language feature introduced in Java 14 and finalised in Java 16. A record 
1is a special type of class in Java that allows us to define classes that act as transparent carriers for immutable data. Records can be used to replace traditional POJOs, which are often verbose and require a lot of boilerplate code.\n\nThis is how we can define the records\n\n```java\npublic record Vehicle(String make, String model, int year) {}\n```\n\nThe fields of a record are implicitly final, which means that once a record instance is created, the data it contains cannot be changed.\n\nRecords provide several built-in methods for common operations such as constructors, getters, `equals()`, `hashCode()`, and `toString()`. Like a regular class, methods inside the record can be extended to provide a custom implementation.\n\nRecords allow you to define a **Compact constructor** which omits the parameter list, assuming the same parameters as the record components. Within this constructor, you can include validation or normalization logic for the fields.\n\n```java\npublic record Vehicle(String make, String model, int year) {\n\n    // Compact constructor\n    public Vehicle {\n        if (year \u003c 1886) { // The first car was made in 1886\n            throw new IllegalArgumentException(\"Invalid year\");\n        }\n        make = make.trim();\n        model = model.trim();\n    }\n}\n```\n\nRecords are ideal for creating simple data-carrier classes, such as DTOs (Data Transfer Objects), value objects in domain-driven design, tuples, and more. Records are serializable by default, provided that all their components are serializable.\n\n### 4: Explain the concept of sealed classes in Java 17.\n\nSealed classes are a new language feature introduced in Java 17 as part of JEP 409. They provide a way to restrict the subclasses that can extend a class or implement an interface. This feature is useful to create more robust and maintainable code and to define a closed hierarchy of types.\n\nSealed Classes allow you to specify a limited set of subclasses that can extend a given class or implement an interface.\n\nThis is how we can declare a sealed class in Java:\n\n```java\npublic sealed abstract class Vehicle permits Car, Truck, Motorcycle {\n    private final String make;\n    private final String model;\n\n    public Vehicle(String make, String model) {\n        this.make = make;\n        this.model = model;\n    }\n\n    public abstract void displayVehicleInfo();\n}\n\npublic final class Car extends Vehicle {\n    private final int seatingCapacity;\n\n    public Car(String make, String model, int seatingCapacity) {\n        super(make, model);\n        this.seatingCapacity = seatingCapacity;\n    }\n\n    @Override\n    public void displayVehicleInfo() {\n        System.out.println(\"Car: \" + getMake() + \" \" + getModel() + \", Seating Capacity: \" + seatingCapacity);\n    }\n}\n```\n\nThe `permits` clause is used to specify the allowed subclasses for type `Shape`.\n\nSince the compiler knows all the possible subtypes of a sealed class, it will prevent any other class except `Circle`, `Square` or `Rectangle` from extending the `Shape` class.\n\n### 5. How Sealed classes are different from final classes?\n\nSealed classes and final classes serve different purposes in Java, although both are used to restrict inheritance.\n\n-   Final Classes in Java cannot be inherited at all. It can be used when a class should never be extended.\n-   Sealed Classes can be inherited, but only by a predefined set of classes. It is used when you want to allow inheritance, but only for specific classes.\n\n### 6: How does the pattern matching for `instanceof` work in Java 17?\n\nPattern Matching for `instanceof` in Java 17 enhances the `instanceof` operator and eliminates the need for type casting and checking.\n\n**Traditional approach:**\n\n```java\nif (obj instanceof Car) {\n    Car str = (Car) obj;\n    // Use car object here\n}\n```\n\n**With pattern matching for instanceof:**\n\n```java\nif (obj instanceof Car car) {\n    // Use car object here\n}\n```\n\nAs you can notice, it makes the code more concise but also enhances readability and reduces the possibility of errors, such as incorrect casting.\n\n### 7: How does the Pattern matching for the switch work?\n\nPattern Matching for the switch is introduced as a preview feature in Java 17. This feature extends the switch expression and switch statement to allow pattern matching in case labels. Pattern Matching for switch aims to make code more readable and safe, especially when dealing with type testing and casting.\n\nPlease note, the Pattern Matching for switch is still in preview and not yet a finalized.\n\n```java\nswitch (obj) {\n    case String s -\u003e System.out.println(\"It's a string: \" + s);\n    case Integer i -\u003e System.out.println(\"It's an integer: \" + i);\n    case null -\u003e System.out.println(\"It's null\");\n    default -\u003e System.out.println(\"It's something else\");\n}\n```\n\n### 8. Is it possible to use records with inheritance?\n\nA record declaration does not have an extends clause, so it is not possible to explicitly declare a direct superclass type, even a Record. However, a record can implement interfaces, so you can use them polymorphically.\n\nRefer to the Java 17 [JLS 8.10](https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html#jls-8.10) notes for more information.\n\n### 9. How does the new Random Number Generators API in Java 17 improve upon the previous implementation?\n\nThe new Random Number Generators API in Java 17 introduced a new `RandomGenerator` interface as the top-level interface for random number generators. It provides specialized interfaces like `SplittableRandomGenerator`, `JumpableRandomGenerator`, and `LeapableRandomGenerator` for different types of generators.\n\nIt includes algorithms like LXM, Xoroshiro128PlusPlus, and Xoshiro256PlusPlus, which are more modern and efficie
1nt than the older Linear Congruential Generator (LCG) used in the legacy `Random` class.\n\nThe new API interface offers better control over the sequence of random numbers generated and provides methods to \"jump\" or \"leap\" ahead in the sequence without generating intermediate values.\n\n```java\nimport java.util.random.RandomGenerator;\nimport java.util.random.RandomGeneratorFactory;\n\npublic class RandomExample {\n    public static void main(String[] args) {\n        RandomGenerator rng = RandomGeneratorFactory.of(\"Xoshiro256PlusPlus\")\n             .create();\n        int randomInt = rng.nextInt();\n        rng.doubles().limit(5).forEach(System.out::println);\n\n        // Create a splittable generator for parallel processing\n        RandomGenerator splitRng = RandomGeneratorFactory.of(\"L64X128MixRandom\").create();\n        RandomGenerator split1 = splitRng.split();\n        RandomGenerator split2 = splitRng.split();\n\n        System.out.println(split1.nextInt());\n        System.out.println(split2.nextInt());\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"1b:T56fb,"])</script>
1<script>self.__next_f.push([1,"\nA curated set of interview questions and answers on spring, spring boot, JPA and Hibernate.\n\n## Spring, Spring Boot\n\n* * *\n\n### 1. Explain Dependency Injection in the context of Spring.\n\nDI is a software design pattern used in object-oriented programming, where the dependencies of a class are provided by an external entity rather than being created within the class itself.\n\nIn other words, instead of a class creating and managing its dependencies, those dependencies are created and managed outside but, are \"injected\" into your class whenever you need it. The main idea behind Dependency Injection is to decouple the bean instantiation process from your actual business logic implementation.\n\nDependency Injection (DI) is one of the core concepts of the Spring Framework. It is achieved through the Spring Framework's Inversion of Control (IoC) container. This allows the loose coupling of components and object creation and disposal responsibility is handed over to the spring container.\n\nAny object in the Spring framework that is initialized through the Spring container is called Spring Bean.\n\nDependency Injection works in a stepped approach;\n\n-   Bean identification/registration\n-   Bean injection\n\nBean identification refers to the way beans are identified within the Spring IoC container. Bean identification can happen with `@Bean` annotation on the `@Configuration` class or using any of the 3 stereotypes (`@Service`, `@Repository` or `@Componenet` annotation).\n\nBean Injection is the process by which one object (the dependency) is passed to another object that needs it (the dependent) rather than the dependent object needing to create the dependency itself. Bean injection can be done using @Autowired field injection, setter method injection or constructor injection.\n\nLearn more about [dependency injection](https://stacktips.com/courses/spring-boot-for-beginners/dependency-injection-in-spring-boot) here.\n\n### 2. Explain `@RestController` annotation in Springboot. How `@RestController` is different from `@Controller` annotation?\n\nThe `@RestController` annotation is a combination of `@Controller` and `@ResponseBody`, used for creating a restful controller. It converts the response to JSON or XML. It ensures that data returned by each method will be written straight into the response body instead of returning a template.\n\nThe `@Controller` Map of the model object to view or template and make it human-readable but `@RestController` simply returns the object and object data is directly written in HTTP response as JSON or XML.\n\n### 3. What is the difference between @Component, @Service and @Repository annotations?\n\n**@Component** It is a generic stereotype for any Spring-managed component or bean. It tells 
1Spring to look for “Components” when the application starts.\n\n**@Repository** It is a stereotype used for the persistence layer beans.\n\n**@Service** This stereotype is used to indicate that they’re holding the business logic. ![|600](/media/articles/1/Blank-diagram.png)\n\n### 4. Explain Transitive Dependency resolution in Spring boot with an example.\n\nAs your application grows, the number of dependencies will grow and managing those dependencies manually is very cumbersome and error-prone. That’s where the Spring boot starter packages come to the rescue. Spring Boot provides several Spring Boot starter packages to address this problem.\n\nThere are two types of dependencies:\n\n-   **Direct:** These are dependencies defined in your `pom.xml` or `build.gradle` file under the `dependencies` section.\n-   **Transitive:** These are dependencies that are dependencies of your direct dependencies.\n\nFor example, if we add the `spring-boot-starter-web` as a dependency to your `pom.xml` file then will download `spring-boot-starter-tomcat` as the direct dependency and with that it will also download the other transitive dependencies like `tomcat-embedded-core` and `tomcat-embedded-el` and `tomcat-embedded-websocket`.\n\n### 5. How to handle exceptions in RestController and return appropriate error responses?\n\nThe `@ControllerAdvice` annotation can be used to handle exceptions thrown from any controllers.\n\n```java\n@ControllerAdvice\nclass GlobalControllerExceptionHandler {\n\n    @ResponseStatus(HttpStatus.CONFLICT)\n    @ExceptionHandler(CustomException.class)\n    public void handleCustomException() {\n       // handle the error and respond\n    }\n\n}\n```\n\n### 6. What are the different options available to make external HTTP API calls from the Spring Boot Application?\n\nSpring boot provides multiple options to make external HTTP calls:\n\n-   [RestTemplate](https://stacktips.com/articles/rest-clients-in-spring#1-resttemplate):\n    -   It is a synchronous HTTP client. The `RestTemplate` is marked for deprecation in Spring 6 and it is recommended to use `RestClient` for applications using Spring 6 or above.\n    -   Reference\n-   [Feign client](https://stacktips.com/articles/rest-clients-in-spring#2-feign-client):\n    -   Feign is a declarative REST client designed to simplify the process of writing web service clients by handling boilerplate tasks such as client creation and response handling. To use Feign we simply need to define an interface using standard JAX-RS annotations, and the framework manages the rest.\n-   [WebClient](https://stacktips.com/articles/rest-clients-in-spring#3-webclient)\n    -   The `WebClient` is an alternative to `RestTemplate`. It was introduced in Spring 5 as part of the **WebFlux** stack. It provides both synchronous and asynchronous APIs to make the REST calls from the Spring application.\n    -   To use `WebClient` in a Spring Boot application, we need to add the `spring-boot-starter-webflux` dependency.\n-   [RestClient](https://stacktips.com/articles/rest-clients-in-spring#4-restclient) (New in 3.2.x)\n    -   The `RestClient` is a newer client in Spring 6, designed to overcome some limitations of `RestTemplate`. It supports both synchronous and asynchronous operations.\n    -   It works similarly to the `WebClient` API, except we don’t have to add the WebFlux dependency.\n-   [HTTP Interface](https://stacktips.com/articles/rest-clients-in-spring#5-http-interface)\n    -   Spring 6 also adds the ability to create a declarative HTTP interface (similar to Feign) using the existing HTTP clients such as `RestTemplate`, `WebClient` and `RestClient`.\n    -   It creates a proxy to perform requests and attach it to the preferred HTTP client configured. For example, the above `ProductApiClient` can be written using a declarative HTTP interface as follows:\n\n### 7. What are the limitations of RestTemplate? and how does it compare with WebClient?\n\n[WebClient](https://stacktips.com/articles/what-is-webclient-how-to-use-webclient-in-java-springboot) is a non-blocking, reactive HTTP client introduced in Spring 5.0, which is the reactive counterpart to the traditional [RestTemplate](https://stacktips.com/articles/calling-rest-services-using-resttemplate) in Spring Boot. It provides a simplified and intuitive API for making HTTP requests. It is designed to handle both synchronous and asynchronous operations.\n\n### 8. What are the different scheduling configurations available for performing periodic tasks?\n\nSpring scheduler is used to schedule the task. It is a scheduler that runs in the background and executes the task at the specified time. We can schedule a task by enabling `@EnableScheduling` annotation and then using `@Scheduled` annotation.\n\nThe `@Scheduled` annotation supports cron, `fixedDelay`, `fixedRate` and `cron` configuration options.\n\n### 9. I want to write a validation to ensure all c
1onfigurations are loaded correctly when my application starts. Which is the best place to write that logic?\n\nSpring boot offers multiple options, for executing your code during the application startup. There are 3 out-of-the-box practices recommended by the Spring developers.\n\n1.  Using `@PostConstruct` annotation\n2.  Using ApplicationRunner or Command Line Runner Interface\n3.  Option-3: Using Spring Boot Events\n\nLearn with the [example](https://stacktips.com/articles/how-to-execute-code-on-spring-boot-application-startup) here.\n\n### 10. What are the differences between JAR and WAR bundles?\n\nJAR (Java Archive) and WAR (Web Archive) are formats used in the Java ecosystem for packaging and distributing applications. But they have a completely different purpose.\n\n**JAR (Java Archive):** - Jar files are used to package and distribute standalone Java applications. They contain a set of classes, resources, and other files that are required to run the application. - JAR files are typically self-contained, meaning that they do not require any additional dependencies to be installed on the system where they are run.\n\n**WAR (Web Archive):** - WAR files are a specific type of JAR file that is used to package and distribute web applications. - They contain all of the files that are required to run the web application, including the Java classes, web pages, static resources, and deployment descriptor files. - WAR files are typically deployed to a web server, where they are run in a servlet container.\n\nLearn more about [Jar vs War](https://stacktips.com/courses/spring-boot-for-beginners/creating-first-spring-boot-project#war-vs-jar)\n\n### 11. How do you configure externalized properties in a Spring Boot application?\n\nTo configure externalized properties in a Spring Boot application, you can use `application.properties` or `application.yml` files. These files can be placed in the classpath or externalized to a specific location.\n\nYou can access these properties programmatically using the `@Value` annotation or by injecting an instance of the class.\n\n```java\n@Component\npublic class MyBean {\n\n    @Value(\"${name}\")\n    private String name;\n    // ...\n}\n```\n\nWe can also bind the properties using the Spring `DataBinder` utility using the `@ConfigurationProperties` annotation on a class.\n\n```java\n@ConfigurationProperties(prefix=\"my\")\npublic class Config {\n\n    private List\u003cString\u003e servers = new ArrayList\u003cString\u003e();\n\n    public List\u003cString\u003e getServers() {\n        return this.servers;\n    }\n}\n```\n\n### 12. What is the best way to check if authentication headers are added to all incoming HTTP requests?\n\nTo validate the headers in my incoming requests we have two options: Servlet filters and Spring interceptors.\n\nSpring Interceptors are used to intercept client requests before they are handled by the controller. They can also be used to intercept the response before the response is sent back to the client. [Interceptors](https://stacktips.com/articles/how-to-use-interceptor-in-spring-boot) are part of the Spring Web MVC framework and provide a way to add pre/post-processing logic to your application's request-response lifecycle.\n\nIf you have servlet filters defined, then the request first passes through the servlet filters before it reaches to the `DispatcherServlet`. If you have multiple filters within your application, it invokes the filters based on the order defined.\n\n### 13. How Filters are different from Interceptors?\n\nFilters are similar to Interceptors, you can also use Servlet filters to intercept the request/response in Spring Boot. But Filters are part of the Servlet API and operate at a lower level.\n\nCheck out [here for a detailed article](https://stacktips.com/articles/how-to-use-interceptor-in-spring-boot#filters-vs-interceptors).\n\n### 14. What are the Limitations of Spring Scheduler?\n\n-   **No support for dynamic Scheduling:** The `@Scheduled` annotations are typically configured at application startup and do not support runtime changes without redeploying the application.\n-   **No support for Job Persistence**: It does not offer built-in supp
1ort for Job persistence, as a result, job recovery in the event of an application restart is not possible.\n-   **No clustering, load balancing:** It does not support clustering and load balancing, The tasks are typically run on a single node.\n-   **Limited control:** It does not allow fine-grained control over managing the tasks. For example, we cannot pause, resume, and unscheduled jobs individually.\n\nSpring Scheduler is sufficient for many simple scheduling tasks, but if you have complex scheduling requirements, job management, and monitoring, then you would need another framework like Quartz.\n\nLimitations of [Spring Scheduler](https://stacktips.com/articles/task-execution-and-scheduling-in-spring-boot#limitations-of-spring-scheduler):\n\n### 15. How to handle database migrations with MySQL and JPA?\n\nPrimarly we have two choices to manage database migrations in the spring boot application. - [Flyway](https://stacktips.com/articles/using-flyway-for-database-migration-in-spring-boot#integrating-flyway-in-spring-boot) - Liquibase\n\nBoth tools work pretty much the same. You need to add the Flyway or Liquibase dependency to your project. All the database changes are managed in the changelog file. If the DB migration is enabled, it executes the migration files during the application startup and executes the SQL queries if there are any changes to the checksum.\n\n### 16. What is Cross-Origin Resource Sharing (CORS)? How do we enable CORS in a Spring Boot RESTful API?\n\nCross-Origin Resource Sharing (CORS) is a security mechanism implemented by web browsers to control access to resources (like APIs) from a different domain than the one serving the web page. It's an important concept in web development, especially for RESTful APIs.\n\nCORS allows servers to specify which origins (domains) are allowed to make requests to them. This is crucial for security, as it prevents malicious websites from making unauthorized requests to your API.\n\nThere are several ways to enable CORS in a Spring Boot application.\n\n**Using global CORS configuration:**\n\n```java\n@Configuration\npublic class CorsConfig {\n\n    @Bean\n    public WebMvcConfigurer corsConfigurer() {\n        return new WebMvcConfigurer() {\n            @Override\n            public void addCorsMappings(CorsRegistry registry) {\n                registry.addMapping(\"/**\")\n                        .allowedOrigins(\"https://stacktips.com\")\n                        .allowedMethods(\"GET\", \"POST\", \"PUT\", \"DELETE\")\n                        .allowedHeaders(\"*\")\n                        .allowCredentials(true);\n            }\n        };\n    }\n}\n```\n\n**Configuring CORS in Controller-level**\n\n```java\n@RestController\n@CrossOrigin(origins = \"https://stacktps.com\")\npublic class HelloController {\n\n    @GetMapping(\"/hello\")\n    public String getData() {\n        return \"Hello World!\";\n    }\n}\n```\n\n**Method-level CORS:**\n\n```java\n@RestController\npublic class HelloController {\n\n    @CrossOrigin(origins = \"https://stacktps.com\")\n    @GetMapping(\"/hello\")\n    public String getData() {\n        return \"Hello World!\";\n    }\n}\n```\n\nOther CORS Configuration Options: - `allowedOrigins`: Specifies which origins are allowed to make requests. - `allowedMethods`: Specifies which HTTP methods are allowed (GET, POST, etc.). - `allowedHeaders`: Specifies which headers are allowed in the request. - `exposedHeaders`: Specifies which headers should be exposed to the client. - `allowCredentials`: Indicates whether the browser should include credentials (like cookies) with the request. - `maxAge`: Specifies how long the browser should cache the CORS configuration.\n\n### 18. Explain the purpose of the `@Autowired` annotation in Spring Boot.\n\nThe `@Autowired` annotation in Spring Boot is used for field injection. When fields are marked with `@Autowired` annotation, spring automatically injects that bean.\n\n```java\n@Service\nclass UserService{\n\n    @Autowired\n    private UserRepository repository;\n\n    //Other methods\n}\n```\n\n### 19. What is REST, and how does it differ from SOAP\n\n**REST (Representational State Transfer)** - REST is suitable for CRUD operations and simple APIs. Best for stateless, resource-based interactions. REST relies on 
1stateless communication and standard HTTP methods. - Resources are identified by URLs, and representations of resources are typically transferred in JSON or XML format.\n\n**SOAP (Simple Object Access Protocol)** - It is suitable for enterprise-level services requiring strict standards, security, and transactions. - Uses WSDL (Web Services Description Language) - It has built-in support for stateful operations and transactions, which can be beneficial for certain types of applications.\n\n| Feature/Protocol | REST | SOAP |\n| --- | --- | --- |\n| Architecture | Resource-based | Protocol-based |\n| Data Format | JSON, XML | XML |\n| Transport | HTTP | HTTP, SMTP, etc. |\n| Communication | Stateless | Can be stateful |\n| Flexibility | High | Low |\n| Ease of Use | High | Medium |\n| Error Handling | HTTP status codes | Detailed (SOAP faults) |\n\n### 20. What is HATEOAS in the context of RESTful APIs?\n\nThe HATEOAS is stands for Hypermedia as the engine of Application State, is one of the key principles of RESTful architecture. It enhances the discoverability of RESTful APIs using hypermedia.\n\nInstead of having predefined endpoints, a HATEOAS-compliant API provides links dynamically with the responses, allowing the client to navigate the API dynamically.\n\nA HATEOAS-compliant API response looks something similar to:\n\n```json\n{\n  \"id\": 1,\n  \"name\": \"John Doe\",\n  \"email\": \"[email protected]\",\n  \"_links\": {\n    \"self\": {\n      \"href\": \"http://api.example.com/users/1\"\n    },\n    \"friends\": {\n      \"href\": \"http://api.example.com/users/1/friends\"\n    },\n    \"update\": {\n      \"href\": \"http://api.example.com/users/1\",\n      \"method\": \"PUT\"\n    },\n    \"delete\": {\n      \"href\": \"http://api.example.com/users/1\",\n      \"method\": \"DELETE\"\n    }\n  }\n}\n```\n\n## JPA, JDBC, Hibernate\n\n* * *\n\n### 21. Explain the difference between JDBC and Hibernate.\n\nJDBC (Java Database Connectivity) and Hibernate are both used for interacting with databases in Java applications.\n\nWhile JDBC provides low-level API to interact with databases using SQL queries directly, Hibernate is an ORM (Object-Relational Mapping) framework that provides a higher level of abstraction over JDBC.\n\nWith JDBC, you need to manually handle the database connection, prepare SQL statements, execute them, manage the result sets, and manage transactions.\n\nHibernate automatically maps Java objects to database tables, allowing you to work with data in an object-oriented way without writing SQL queries for most database operations. It also comes with built-in support for transaction management and handles one-to-one, one-to-many, many-to-one, and many-to-many relationships.\n\n### 22. Discuss the advantages and disadvantages of using an ORM (Object-Relational Mapping) framework like Hibernate.\n\n**Advantages** - Hibernate automatically generates SQL queries based on object manipulations. You don't need to work with writing SQL queries. - Many common tasks like opening and closing DB connections, managing transactions, and handling result sets are handled by the ORM. This means you have to write less code as compared to using JDBC. - Hibernate abstracts the underlying database by generating SQL according to the dialect of the chosen database. It supports a wide range of databases (including MySQL, PostgreSQL, and Oracle) making it easier to switch to a different database. - It integrates well with Spring's transaction management workflow and supports ACID properties ensuring data consistency.\n\n**Disadvantages** - Queries generated from Hibernate may not always be optimized. - While lazy loading improves performance, it can lead to the \"N+1 problem,\" where multiple small queries are executed instead of a single efficient query, impacting performance in certain scenarios.\n\n### 23. Can we write a native SQL query in JPA?\n\nYou can write a native SQL query using the `@Query` annotation. Eg.\n\n```java\n@Query(\"SELECT u FROM User u WHERE u.status = 1\")\nCollection\u003cUser\u003e findAllActiveUsers();\n\n@Query(\"SELECT u FROM User u WHERE u.status = 1 AND u.name = ?1\")\nCollection\u003cUser\u003e fetchUsersWithNameAndStatus(string name, String status);\n```\n\n### 24. Explain the difference between JPQL, SQL, and Criteria API in the context of Spring Data JPA and when you would use each.\n\n**JPQL** Java Persistence Query Language is an object-oriented query language used to perform queries on JPA entities. It's independent of the underlying database and SQL dialect.\n\n**SQL** Structured Query L
1anguage is a language used to communicate with relational databases. Native SQL queries can be executed in Spring Data JPA using the `@Query` annotation with the `nativeQuery` flag set to true.\n\n**Criteria API** It is a type-safe, programmatic way to create JPA queries. It's more verbose than JPQL but provides better compile-time checks.\n\nUse JPQL for simple to moderately complex queries, SQL for database-specific queries or optimizations, and Criteria API for complex and type-safe queries.\n\n### 25. What is the role of the @Transactional annotation in Spring Data JPA, and how does it affect database transactions?\n\nThe `@Transactional` is used to define the boundaries of a transaction in Spring Data JPA. When a method annotated with `@Transactional` is called, a new transaction is started. The transaction is committed when the method completes successfully and rolled back if an exception occurs. It ensures the consistency and integrity of the data.\n\n### 26. What is the N+1 query problem? How do you handle lazy-loading and N+1 query problems in Spring Data JPA?\n\nThe N+1 query problem happens when the data access framework executes N additional SQL statements to fetch the same data that could have been retrieved when executing the primary SQL query.\n\nThe larger the value of N, the more queries will be executed, and the larger the performance impact. And, unlike the slow query log that can help you find slow-running queries, the N+1 issue won’t be spotted because each additional query runs sufficiently fast to not trigger the slow query log.\n\nThe problem is executing a large number of additional queries that, overall, take sufficient time to slow down response time. Lazy-loading can be addressed by:\n\n1.  Using `FetchType.EAGER` to load related entities immediately.\n2.  Using `JOIN FETCH` in JPQL or EntityGraph to all required relationships in a single query.\n"])</script>
1<script>self.__next_f.push([1,"1c:T564a,"])</script>
1<script>self.__next_f.push([1,"\n### 1. What is the difference between the comparison done by the `equals()` method and the `==` operator?\n\nIn Java, the `equals()` method is used for comparing the contents of two string objects. It returns **true** if the two have the same value while the `==` operator compares the references of two string objects.\n\nIn the following example, `equals()` returns true as the two string objects have the same values. However == operator returns false as both string objects are referencing different objects:\n\n```java\npublic class EqualsTest {\n\n    public static void main(String args[]) {\n        String str1 = new String(\"Hello World\");\n        String str2 = new String(\"Hello World\");\n\n        //Reference comparison\n        System.out.println(s1 == s2);\n\n        //Content comparison\n        System.out.println(s1.equals(s2));\n\n        // integer-type\n        System.out.println(10 == 10);\n\n        // char-type\n        System.out.println('a' == 'a');\n    }\n\n}\n```\n\nOutput\n\n```text\nfalse\ntrue\ntrue\ntrue\n```\n\n### 2. What is the output of the following program?\n\n```java\npublic class Test {\n\n    public void print(int a, long b) {\n        System.out.println(\"Method 1\");\n    }\n\n    public void print(long a, int b) {\n        System.out.println(\"Method 2\");\n    }\n\n    public static void main(String[] args) {\n        Test obj = new Test();\n        obj.print(5, 10);\n    }\n\n}\n```\n\nThe above program will output:\n\n```text\nMethod 1\n```\n\nThis is because Java will automatically promote smaller numeric types to larger numeric types as needed. In this case, the integer literal `5` can be automatically promoted to either an `int` or a `long`, and the integer literal `10` can also be promoted to either an `int` or a `long`.\n\n### 3. How to Create an Infinite Loop in Java?\n\nInfinite loops are those loops that run infinitely without any breaking conditions. Some examples of consciously declaring an infinite loop are:\n\nUsing For Loop:\n\n```java\nfor (;;)\n{\n   // Business logic\n   // Any break logic\n}\n```\n\nUsing while loop:\n\n```java\nwhile(true){\n   // Business logic\n   // Any break logic\n}\n```\n\nUsing do-while loop:\n\n```java\ndo{\n   // Business logic\n   // Any break logic\n} while(true);\n```\n\n### 4. Explain the Diamond Problem. How does Java overcome this problem?\n\nThe Diamond Problem is a situation where a class inherits from two classes that have a common ancestor. This creates ambiguity in the path through which a method or a member variable is inherited because there are 2 possible paths to follow up the inheritance hierarchy to the common ancestor.\n\nJava does not support multiple inheritance for classes, meaning a class cannot extend more than one class. However, it supports multiple inheritance of types through the interface mechanism.\n\n### 5. What is a `default` method in the interface? Is it possible to have a method definition in the Java interface?\n\nTherefore, to overcome this issue, Java 8 has introduced the concept of default methods (Also known as Extension Methods) which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.\n\nYou can do this by using the `default` keyword.\n\n```java\ninterface Vehicle {\n    String speedUp();\n    String slowDown();\n\n    default String alarmOn() {\n        return \"Turning the alarm on.\";\n    }\n\n    default String alarmOff() {\n        return \"Turning the alarm off.\";\n    }\n}\n```\n\nRead more about [default methods for interface](https://stacktips.com/articles/default-methods-for-interfaces-in-java8) here.\n\n### 6. Explain how Java deals with the diamond problem due to the `default` method in the interface.\n\nWith the introduction of Default methods in interfaces in Java 8, the potential for a diamond problem arose. Default methods allow an interface to provide a default implementation for methods, which means a class can inherit concrete methods from multiple interfaces.\n\nThere are two ways to address this issue in Java:\n\n1.  **Explicit Implementation:** If a class implements multiple interfaces that define the same default method, the class must explicitly provide an implementation for that method to resolve the conflict.\n2.  **Inheritance Rule:** If a class inherits a method from a superclass, it takes precedence over any default methods provided by interfaces.\n\n```java\ninterface Interface1 {\n    default void hello() {\n        System.out.println(\"Hello from Interface1\");\n    }\n}\n\ninterface Interface2 {\n    default void hello() {\n        System.out.println(\"Hello from Interface2\");\n    }\n}\n\npublic class Child implements Interface1, Interface2 {\n    @Override\n    public void hello() {\n        System.out.println(\"inside Child class hello method\");\n\n        // Calling Interface1's default method\n        Interface1.super.hello();\n    }\n\n    public static void main(String[] args) {\n        Child obj = new Child();\n\n        // This will call the Child class hello method\n        obj.hello();\n    }\n}\n```\n\n### 7. What is Functional Interfaces?\n\nA functional interface must contain exactly one abstract method declaration. Each lambda expression of that type will be matched to this abstract method.\n\nSince default methods are not abstract you're free to add default methods to your functional interface. We can use arbitrary interfaces as lambda expressions as long as the interface only contains one abstract method.\n\nTo ensure your interface meets the requirements, you can optionally add the `@FunctionalInterface` annotation. The compiler is aware of this annotation and throws a compiler error as you try to add a second abstract method declaration to the interface.\n\n```java\n@FunctionalInterface\ninterface Converter\u003cF, T\u003e {\n    T convert(F from);\n}\n```\n\nThis can be used as\n\n```java\nConverter\u003cString, Integer\u003e converter = (from) -\u003e Integer.valueOf(from);\nInteger converted = converter.convert(\"123\");\nSystem.out.println(converted);\n```\n\n### 8. Can Abstract Class in Java have Constructors?\n\nYes, abstract classes in Java can have constructors.\n\nWhile it may seem counterintuitive at first, since abstract classes cannot be instantiated directly, these constructors can be used to initialize the fields and can be called during the instantiation of its concrete subclass.\n\nHere's how abstract class constructors are used:\n\n```java\nabstract class MyAbstractClass {\n\n    public int a;\n    public int b;\n\n    public MyAbstractClass(int a, int b) {\n        this.a = a;\n        this.b = b;\n    }\n\n    public void print() {\n        System.out.println(\"a = \" + a);\n        System.out.println(\"b = \" + b);\n    }\n}\n\npublic class AbstractDemo extends MyAbstractClass {\n\n    public AbstractDemo(int x, int y) {\n        super(x, y);\n\n    }\n\n    public static void main(String[] args) {\n        AbstractDemo obj = new AbstractDemo(5, 10);\n        obj.print();\n    }\n\n}\n```\n\nWhen a concrete subclass of an abstract class is instantiated, the constructor of the abstract class is called first, either implicitly or through the use of `super()` by passing arguments.\n\nThis process is known as constructor chaining and ensures that the initialization behaviour defined in the abstract class's constructor is executed.\n\n### 9. Why is the Main Method Static in Java?\n\nThe main method is always static because static members are those methods that belong to the classes, not to an individual object. So if the main method will not be static then for every object, it will be available to all objects which is not acceptable to JVM. JVM calls the main method based on the class name itself. Not by creating the object.\n\nThere must be only 1 main method in the Java program as the execution starts from the main method.\n\n### 10. Explain Java Streams?\n\nA `java.util.Stream` represents a sequence of elements on which one or more operations can be performed. Stream operations are either intermediate or terminal.\n\nWhile terminal operations return a result of a certain type, intermediate operations return the stream itself so you can chain multiple method calls in a row.\n\nStreams are created on a source, e.g. a `java.util.Collection` like lists or sets (maps are not supported). Stream operations can either be executed sequentially or parallelly. Streams can be created either by calling `Collection.stream()` or `Collection.parallelStream()` method.\n\nThe following sections explain the most common stream operations.\n\n```java\nList\u003cString\u003e listItems = new ArrayList\u003c\u003e();\nlistItems.add(\"item1\");\nlistItems.add(\"item3\");\nlistItems.add(\"item2\");\n\nlistItems\n    .stream()\n    .filter((s) -\u003e s.startsWith(\"item3\"))\n    .forEach(System.out::println);\n```\n\n### 11. How would you differentiate between a `String`, `StringBuffer`, and a `StringBuilder`?\
1n\nA `String` is **immutable**, whereas both the `StringBuilder` and `StringBuffer` are **mutable**. In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, memory is allocated heap memory storage area.\n\nIt is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. (For example, appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)\n\n```java\n// String\nString first = \"InterviewBit\";\nString second = new String(\"InterviewBit\");\n\n// StringBuffer\nStringBuffer third = new StringBuffer(\"InterviewBit\");\n\n// StringBuilder\nStringBuilder fourth = new StringBuilder(\"InterviewBit\");\n```\n\n### 12. Explain the output of the following program related to the `equals()` method of StringBuilder.\n\n```java\npublic class Demo {\n\n    public static void main(String[] args) {\n\n        StringBuilder sb1 = new StringBuilder(\"hello\");\n        StringBuilder sb2 = new StringBuilder(\"hello\");\n\n        if(sb1.equals(sb2)) {\n            System.out.println(\"Equal\");\n        } else {\n            System.out.println(\"Not Equal\");\n        }\n\n    }\n}\n```\n\nThe output of the given Java program will be `Not Equal`.\n\nThis is because the `equals()` method in the `StringBuilder` class does not override the `equals()` method from the `Object` class. In the `Object` class, the `equals()` method checks for reference equality, meaning it returns `true` if and only if both references point to the same object in memory.\n\nSince `sb1` and `sb2` are references to two different `StringBuilder` objects even though they contain the same sequence of characters, the `equals()` method inherited from the `Object` class will return `false`.\n\n### 13. What is method overriding? What restrictions are in place on method overriding?\n\nWhen a class defines a method using the same name, same return type, and same argument list as that of a method in its superclass, it is said to be overridden.\n\nWhen the method is invoked for an object, it is the overridden method that is called and not the method definition from the superclass.\n\nFollowing are some of the restrictions placed on method overriding: - Overridden methods must have the same name, argument list, and return type. - The overriding method may not limit the access of the method it overrides. Methods may be overridden to be more public, not more private. - The overriding method may not throw any exceptions that may not be thrown by the overridden method.\n\n### 14. What is the Difference Between an Inner Class and a Sub-Class?\n\nAn Inner class is a class that is nested within another class. An Inner class has access rights to the class which is nesting it and it can access all variables and methods defined in the outer class.\n\nA sub-class is a class that inherits from another class called a superclass. Sub-class can access all public and protected methods and fields of its superclass.\n\n### 15. What are the various access specifiers used for class definition in Java?\n\nAccess specifiers are the keywords used before a class name that defines the access scope. The types of access specifiers for classes are:\n\n-   **Public:** Class, Method, and Field are accessible from anywhere.\n-   **Protected:** Method, Field can be accessed from the same class to which they belong or from the sub-classes, and the class of the same package, but not from outside.\n-   **Default:** Method, Field, and class can be accessed only from the same package and not from outside of its native package.\n-   **Private:** Method, Field can be accessed from the same class to which they belong.\n\n### 16. Explain encapsulation in OOPS\n\nEncapsulation is a concept in Object Oriented Programming (OOP) for combining properties and methods in a single unit.\n\nEncapsulation helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independently of other objects. Encapsulation also serves the data hiding purpose.\n\n### 17. What is a Singleton class? Give a Practical example of when should you use Singleton class.\n\nSingleton design pattern belongs to the creational family of patterns that governs the instantiation process. This pattern ensures at most one instance of a class is ever created through the application lifecycle.\n\nFollowing are some of the examples where Singleton classes are best suited:\n\n-   **Project Configuration**: A class that reads your project configuration can be made Singleton. By making this singleton, you are allowing global access for all classes in your application. If the project configs are stored in a file, it just reads once and holds on the application cache. You don’t have to read the file multiple times.\n-   **Application Log:** The logger will be used everywhere in your application. It must be initialized once and used everywhere.\n-   **Analytics and Reporting:** If you are using some kind of data analysis tool like Google Analytics, you will notice that they are designed to be a singleton. It initializes once and is used everywhere for each user action.\n\nFor the step-by-step guide to implement singleton class visit [Singleton Design Pattern](https://stacktips.com/articles/singleton-design-pattern-in-java).\n\n### 18. What is the difference between continue and break statement?\n\nThe `break` and `continue` are two important keywords used in the loops. When a break keyword is used in a loop, the loop is broken instantly while when the continue keyword is used, the current iteration is broken and the loop continues with the next iteration.\n\n
1In the below example, the Loop is broken when the counter reaches 4.\n\n```java\nfor (counter = 0; counter\u003c 10; counter++)\n    system.out.println(counter);\n\n    if (counter == 4) {\n        break;\n    }\n}\n```\n\nIn the below example when the counter reaches 4, the loop jumps to the next iteration and any statements after the continue keyword are skipped for the current iteration.\n\n```java\nfor (counter = 0; counter \u003c 10; counter++)\n    system.out.println(counter);\n    if (counter == 4) {\n        continue;\n    }\n}\n```\n\n### 19. What is the difference between double and float variables in Java?\n\nIn Java, float takes 4 bytes in memory while Double takes 8 bytes in memory. Float is a single-precision floating-point decimal number while Double is a double-precision decimal number.\n\n### 20. What is the Final Keyword in Java?\n\nA variable declared with the final keyword is a constant in Java. Value can be assigned only once and after the assignment, the value of a constant can’t be changed.\n\nFor example, a constant with the name `MAX_LIMIT` is declared and assigned value:\n\n```java\nprivate final int MAX_LIMIT=100\n```\n\nWhen a method is declared as final, it can NOT be overridden by the subclasses. This method is faster than any other method because they are resolved at the complied time.\n\nWhen a class is declared as final, it cannot be inherited. Example String, Integer, and other wrapper classes.\n\n### 21. Can we declare a class as Abstract without having any abstract method?\n\nYes, we can create an abstract class by using the abstract keywords before the class names even if it doesn’t have any abstract method. However, if a class has even one abstract method, it must be declared as abstract otherwise it will give an error.\n\n### 22. What is the difference between an abstract class and an interface in Java?\n\nThe primary difference between an abstract class and an interface is that an interface can only possess a declaration of public static methods with no concrete implementation while an abstract class can have members with any access specifiers (public, private, etc) with or without a concrete implementation.\n\nAnother key difference in the use of abstract classes and interfaces is that a class that implements an interface must implement all the methods of the interface while a class that inherits from an abstract class doesn’t require the implementation of all the methods of its super class.\n\nA class can implement multiple interfaces but it can extend only one abstract class.\n\n### 23. Can we declare the main method of our class as private?\n\nIn Java, the main method must be public static to run any application correctly. If the main method is declared as private, the developer won’t get any compilation error however, it will not get executed and will give a runtime error.\n\n### 24. How we can execute any code even before the main method?\n\nIf we want to execute any statements before even the creation of objects at the load time of the class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before the creation of objects in the main method.\n\n### 25. What is a Serializable interface?\n\nSerializable is a marker interface. When an object has to be transferred over a network ( typically through RMI or EJB) or persists the state of an object to a file, the object Class needs to implement a Serializable interface.\n\nImplementing this interface will allow the object converted into a byte stream and transferred over a network.\n\n### 26. What is the use of `serialVersionUID`?\n\nDuring object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names, types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type every time an object is serialized the Java serialization mechanism automatically computes a hash value.\n\nObjectStreamClass’s computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value. The seri
1alVersionUID is also called suid.\n\nSo when the serialized object is retrieved, the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the objects. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.\n\nChanges to a serializable class can be compatible or incompatible.\n\n### 27. Explain the difference between JDK, JRE, and JVM.\n\nJVM (Java Virtual Machine): - The runtime engine that executes Java bytecode. It is platform-dependent, meaning different OS/hardware needs different JVM - It also provides memory management and security JRE (Java Runtime Environment): - JRE Contains the JVM and includes core libraries and other components to run Java applications - It is required for running compiled Java programs JDK (Java Development Kit): - JDK contains the JRE. It includes development tools like compiler, debugger, and documentation - You need JDK for developing Java applications\n\n### 28. How does garbage collection work in Java?\n\nGarbage collection in Java is an automatic memory management process that frees up memory occupied by objects that are no longer in use. It identifies which objects in memory are no longer reachable and periodically removes the unreachable objects from memory.\n\nGarbage collection (GC) helps to prevent memory leaks and manage the limited memory available in Java applications. The typical GC process uses a **Mark-and-Sweep** algorithm.\n\n### 29. Explain the differences between checked and unchecked exceptions\n\n| Checked Exceptions | Unchecked exceptions |\n| --- | --- |\n| Checked Exceptions are exceptions that the JAVA compiler requires us to handle. We have to use the try, cache block to handle the exception or throw the exception up the call stack. | The Java compiler ignores the unchecked exceptions and we are not forced by the compiler to handle it. Unchecked exceptions are those exceptions that extend RuntimeException |\n| For example, IOException, SQLException, etc are examples of checked exceptions. | For example, NullPointerException, IllegalArgumentException, etc are examples of unchecked exceptions. |\n| All modern Java IDEs (Integrated Development Environments) will show these errors during the compilation time. | Though the Java compiler does not force us, we can still choose to handle this exception to maintain the normal flow of the program. |\n\nRead more about [exception handling in Java](https://stacktips.com/courses/getting-started-with-java/java-exceptions) here.\n\n### 30. What is the purpose of the `transient` keyword in Java?\n\nSerialization is the process of converting an object into a byte stream so it can be saved to a file or transferred over a network. Deserialization is the reverse process, where the byte stream is converted back into an object.\n\nThe `transient` keyword in Java is used to mark fields in a class that should **not be serialized** when the class is converted into a byte stream during serialization. When an object is serialized to write to a file or sent over a network, fields marked as `transient` are excluded from the serialization process.\n\nCheckout working example [here](https://github.com/StackTipsLab/core-java-tutorials/tree/main/src/com/stacktips/transient_field)\n"])</script>
1<script>self.__next_f.push([1,"1d:T3c3c,"])</script>
1<script>self.__next_f.push([1,"\nIn this article, we will delve into some key optimization techniques and considerations to improve the overall application performance when dealing with MongoDB from Spring Boot.\n\nLet's dive in!\n\n## 1. Indexing MongoDB Collections\n\nIf your collection is not indexed, your queries will scan through the entire collection. Querying data with an index is much faster than scanning the entire collection.\n\nBy default, MongoDB includes an `_id` property in every document inside the collection and it is indexed. If you're using a custom ID field, then you need to ensure it is efficiently indexable.\n\nThere are several types of indexes supported in MongoDB. You can create a simple index on a field inside the collection or define more complex ones, such as compound indexes, partial indexes, and TTL indexes.\n\nYou can choose the type of index to use based on your query patterns.\n\n### Creating an Index\n\nThe Spring Data MongoDB (`spring-data-mongodb`) dependency provides several convenient options for creating an index.\n\nThe easiest way to create an index is to use the `@Indexed` annotation. All you need to do is to use the `@Indexed` annotation on the field within your model class. You can also set the `expireAfterSeconds` attribute on the `@Indexed` annotation to create a TTL index.\n\nIn the following `Product` model, the `productId` field is indexed with a TTL value:\n\n```java\n@Document(collection = \"products\")\npublic class Product {\n    @Indexed(name = \"productId_index\", expireAfterSeconds=3600)\n    String productId;\n    String name;\n    String category;\n    String brand;\n    BigDecimal offerPrice;\n    BigDecimal price;\n}\n```\n\n### Compound Indexes\n\nIndexes are great, but what if your query searches based on multiple fields inside a collection? That is when you should use compound indexes.\n\nA compound index can be created using the `@CompoundIndex` annotation by passing the index definition in JSON format. This annotation is applied at the class level and is repeatable.\n\nNote that a compound index can have a maximum of 32 fields.\n\nThe following example creates a compound index named `product_brand_index` using the `productId` and `brand` fields.\n\n```java\n@CompoundIndex(name = \"product_brand_index\",\n               def = \"{'productId': 1, 'brand': 1}\")\npublic class Product {\n    @Indexed\n    String productId;\n    String name;\n    String category;\n    String brand;\n    BigDecimal offerPrice;\n    BigDecimal price;\n}\n```\n\n### Partial Index\n\nPartial indexes are like regular indexes, but they only include documents in a collection that meet specific filter criteria. Because they only index a subset of data in a collection, they are more efficient compared to basic and compound indexes.\n\nSpring Data MongoDB does not support creating partial indexes via annotations, but it is possible programmatically.\n\n_Note_\n\nIt is recommended to start index creation on Spring application startup, specifically after the application context is refreshed. You can use Spring lifecycle events to guarantee that the context is fully initialized before you create indexes.\n\nThe following example creates a partial index named `apple_products_index` inside the `products` collection only for documents that contain `brand=apple`.\n\n```java\n@Component\nclass AppEventListener {\n\n    @Autowired\n    private MongoTemplate mongoTemplate;\n\n    @EventListener(ContextRefreshedEvent.class)\n    public void initIndicesAfterStartup() {\n        Index myIndex = new Index()\n                .background()\n                .unique()\n                .named(\"apple_products_index\")\n                .on(\"productId\", Sort.Direction.ASC)\n                .on(\"price\", Sort.Direction.DESC)\n                .partial(PartialIndexFilter.of(Criteria.where(\"brand\")\n                        .is(\"apple\")));\n\n        DefaultIndexOperations indexOperations = new DefaultIndexOperations(mongoTemplate,\n                \"products\", Product.class);\n        indexOperations.ensureIndex(myIndex);\n    }\n};\n```\n\n### FAQs\n\n**How many indexes can we create?** As indexes largely live in memory, ensure that your indexes fit entirely in RAM. If you're going overboard, MongoDB will attempt to read the index from disk, which has an adverse effect and slows down your queries.\n\nA single MongoDB collection can have a maximum of 64 indexes.\n\n## 2. Manage the Connection Pool\n\nIncorrectly configured connection pools can either lead to a shortage of database connections under load or waste resources. Increasing the client connection pool size based on availability can improve performance when you have high concurrent usage on your database.\n\nBy default, Spring Data MongoDB sets the max pool size to 100. But this can be changed by setting the `maxPoolSize=500` parameter in your connection URI.\n\n```yaml\nspring:\n  data:\n    mongodb:\n      uri: mongodb://user:password@localhost:27017/product_db?ssl=true\u0026maxPoolSize=500\u0026replicaSet=rs0\u0026authSource=admin\n```\n\nI highly recommend reading this excellent post by [Brian Shen](https://medium.com/@houwei.shen/how-poolsize-can-impact-mongodb-backed-apps-cee83d481b1f), where he explains how pool size can impact the performance of MongoDB-backed applications.\n\n## 3. Query Large Datasets\n\nRetrieving a large number of documents in a single operation can significantly increase the load on the MongoDB server. Instead, you can use paginated queries to fetch the data in chunks.\n\nFor example, the following code snippet uses a paginated query instead of fetching all the data at once.\n\n```java\nPageable pageable = PageRequest.of(page, size);\nQuery query = new Query().with(pageable);\nList\u003cProduct\u003e products= mongoTemplate.find(query, Product.class);\n```\n\n## 4. Inefficient Schema Design\n\nUnlike relational databases, MongoDB is schema-less and you are not required to design your schema upfront.\n\nAlthough it is not mandatory, having a database schema upfront helps to ensure that the data stored in the database follows a 
1specific structure. A well-designed schema can significantly enhance performance and data consistency.\n\nWhile designing your database schema, consider your data access patterns and aspects like sharding and indexing to ensure the database performs well as it scales.\n\nFor example, embedding documents can reduce the number of database roundtrips, but it can add overhead if your document size is huge.\n\nConsider reading some of the established schema design patterns [here](https://www.mongodb.com/docs/atlas/performance-advisor/schema-suggestions/).\n\n## 5. Use Appropriate Write Concerns and Read Preferences\n\nIf you're using distributed database systems, then consistency, availability, and durability of data are very important. This is where **Write Concerns** and **Read Preferences** come into play.\n\n### Write Concerns\n\nWrite Concerns deal with the level of acknowledgment requested from MongoDB when performing write operations.\n\nBy default, MongoDB acknowledges all write operations. This means it ensures the data is written to replica sets before the operation is considered successful. This can be overridden using the `setDefaultRWConcern` administrative command globally during cluster setup.\n\nThe default write concern used in the Java Mongo driver is to **acknowledge** all write operations. However, you can override this behavior from your application using the `setWriteConcern()` method on `MongoTemplate`.\n\n```java\nMongoTemplate template = new MongoTemplate(factory, converter);\ntemplate.setWriteConcern(WriteConcern.ACKNOWLEDGED);\n```\n\nThe above configuration alters the behavior globally across all repositories.\n\nAlternatively, you can configure it on a per-operation basis using a `WriteConcernResolver` bean.\n\n```java\n@Sl4j\n@Configuration\npublic class MongoConfiguration {\n\n    @Bean\n    public WriteConcernResolver writeConcernResolver() {\n        return action -\u003e {\n            String entityName = action.getEntityType().getSimpleName();\n            if (entityName.contains(\"Product\")) {\n                return WriteConcern.ACKNOWLEDGED;\n            } else if (entityName.contains(\"Metadata\")) {\n                return WriteConcern.JOURNALED;\n            }\n            return action.getDefaultWriteConcern();\n\n        };\n    }\n\n}\n```\n\n**References:**\n\n-   [https://mongodb.github.io/mongo-java-driver/4.2/apidocs/mongodb-driver-core/com/mongodb/WriteConcern.html](https://mongodb.github.io/mongo-java-driver/4.2/apidocs/mongodb-driver-core/com/mongodb/WriteConcern.html)\n-   [https://www.mongodb.com/docs/manual/reference/mongodb-defaults/](https://www.mongodb.com/docs/manual/reference/mongodb-defaults/)\n\n### Read Preferences\n\nThe Read Preferences configuration is used to determine how MongoDB directs read operations to the members of a replica set. It allows clients to control whether they prefer to read from the primary node or a secondary node based on latency.\n\nIt helps to balance the load and optimize read performance across a distributed database system.\n\nThe **Read Preferences** can be configured globally using a `MongoClientSettingsBuilderCustomizer` bean.\n\n```java\n@Bean\npublic MongoClientSettingsBuilderCustomizer monoClientCustomizer() {\n    return builder -\u003e builder.readPreference(ReadPreference.nearest());\n}\n```\n\nWe can also set the read preference per operation using:\n\n```java\nmongoTemplate.getCollection(\"product_collection\")\n        .withReadPreference(ReadPreference.nearest())\n        .find();\n```\n\n**References:**\n\n-   [https://www.javadoc.io/doc/org.mongodb/mongo-java-driver/latest/com/mongodb/ReadPreference.html](https://www.javadoc.io/doc/org.mongodb/mongo-java-driver/latest/com/mongodb/ReadPreference.html)\n\n## 6. Optimize Large Payloads Using Projections\n\nIf your database contains collections with large documents, retrieving large documents without projection can lead to high network latency and increased load on the MongoDB server.\n\nIt is a good practice to use projections and limit the result by pulling only the required fields. This can reduce the amount of data transferred over the network.\n\nIn Spring Data MongoDB, you can use the `fields()` method to include and exclude fields in your response. For example, the following query pulls only `productId` and `name` from the `Product` collection.\n\n```java\nQuery query = new Query();\nquery.fields().include(\"productId\").include(\"name\");\nreturn mongoTemplate.find(query, Product.class);\n```\n\n## 7. Leverage Application-Level Caching\n\nCaching helps to speed up data access and improve overall application performance by reducing the need for frequent access to the database. A caching strategy can be implemented at different levels to meet your performance goals:\n\n-   Caching on the client side (browser)\n-   Caching at the web server layer\n-   Caching application-level data\n-   CDN caching\n-   Database caching\n\nImplement application-level caching to avoid unnecessary database reads. Read the [official documentation](https://docs.spring.io/spring-boot/reference/io/caching.html) to implement caching within your Spring Boot application.\n\n## 8. Use Aggregations\n\nFor complex data processing, MongoDB's aggregation framework is more efficient than running multiple queries and processing data on the application side.\n\nAggregations can be used for processing and transforming documents within a collection. They use a pipeline approach, where documents pass through a series of stages that perform operations such as filtering, grouping, and transforming data.\n\nSpring Data MongoDB provides support for the aggregation framework through the `Aggregation` class.\n\nLet's say you have a list of products, prices, and sales data stored in different c
1ollections and you want to generate a report that calculates the total sales made last month for each product. This can be written using aggregations as follows:\n\n```java\npublic List\u003cTotalSales\u003e calculateLastMonthSales() {\n    MatchOperation matchStage = Aggregation.match(Criteria.where(\"date\")\n            .gte(getLastMonthStartDate())\n            .lte(new Date()));\n\n    LookupOperation lookupProduct = Aggregation.lookup(\n            \"Product\", \"productId\", \"_id\", \"product\");\n    LookupOperation lookupPrice = Aggregation.lookup(\n            \"Price\", \"productId\", \"_id\", \"price\");\n    UnwindOperation unwindProduct = Aggregation.unwind(\"product\");\n    UnwindOperation unwindPrice = Aggregation.unwind(\"price\");\n\n    GroupOperation groupStage = Aggregation.group(\"product.name\")\n            .sum(ArithmeticOperators.Multiply.valueOf(\"quantity\")\n                    .multiplyBy(\"price.price\"))\n            .as(\"totalSales\");\n\n    ProjectionOperation projectStage = Aggregation.project()\n            .andExpression(\"_id\").as(\"productName\")\n            .andExpression(\"totalSales\").as(\"totalSales\")\n            .andExclude(\"_id\");\n\n    Aggregation aggregation = Aggregation.newAggregation(matchStage,\n            lookupProduct,\n            unwindProduct,\n            lookupPrice,\n            unwindPrice,\n            groupStage,\n            projectStage);\n    AggregationResults\u003cTotalSales\u003e results = mongoTemplate.aggregate(\n            aggregation, \"Sales\", TotalSales.class);\n    return results.getMappedResults();\n}\n```\n\n**References:**\n\n-   [https://medium.com/mongodb-performance-tuning/explaining-aggregation-pipelines-2d1edd46a341](https://medium.com/mongodb-performance-tuning/explaining-aggregation-pipelines-2d1edd46a341)\n\n## 9. Leverage Bulk Operations\n\nBulk operations allow you to batch multiple operations (insert, update, or delete) in a single request. This results in fewer network roundtrips and significantly faster performance.\n\nMongoDB bulk operations are not atomic by default. However, they can be integrated with Spring's transaction management capabilities to ensure consistency across multiple operations.\n\nThe following example demonstrates inserting multiple records using a bulk operation.\n\n```java\n@Component\n@RequiredArgsConstructor\npublic class DataLoader implements CommandLineRunner {\n\n    private static final String FILE_PATH = \"src/main/resources/products.csv\";\n\n    private final MongoTemplate mongoTemplate;\n\n    @Override\n    public void run(String... args) throws Exception {\n        List\u003cProduct\u003e products = parseCsv(FILE_PATH, Product.class)\n                .stream()\n                .map(row -\u003e new Product(row.getId(), row.getName(), row.getBrand()))\n                .toList();\n\n        mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED, Product.class)\n                .insert(products)\n                .execute();\n    }\n\n    public static \u003cT\u003e List\u003cT\u003e parseCsv(String filePath, Class\u003cT\u003e type) throws IOException {\n        try (Reader reader = new FileReader(filePath)) {\n            return new CsvToBeanBuilder\u003cT\u003e(reader).withType(type).build().parse();\n        }\n    }\n}\n```\n\n## 10. Use Capped Collections When Applicable\n\nCapped collections are fixed-size collections that maintain insertion order and automatically remove the oldest documents when the collection reaches its maximum size.\n\nYou're not allowed to delete documents from a capped collection. If you want to delete all documents, you can drop the whole collection.\n\nA capped collection can be useful if you want to create a real-time logging system that maintains a rolling log of the most recent user activities.\n\n```java\nmongoTemplate.createCollection(LogEntry.class,\n        CollectionOptions.empty().capped()\n                .size(MAX_SIZE)\n                .maxDocuments(MAX_DOCUMENTS));\n```\n"])</script>
1<script>self.__next_f.push([1,"1e:T14f3,"])</script>
1<script>self.__next_f.push([1,"\nThe Java Collections API is a set of interfaces and implementations included in the Java standard library. The collections framework defines different data structures for storing, grouping, and retrieving objects.\n\nEach implementation has its own trade-offs in ordering, performance, and thread-safety, so picking the right one matters more than people usually assume. All collection interfaces and classes live under the `java.util` package.\n\nIn this course, we'll walk through the most commonly used collections and learn how to perform the basic operations on each one.\n\n## Collection Interface\n\nThe `Collection` interface sits at the root of the collection hierarchy and defines the general-purpose behaviour shared across the hierarchy. It has no concrete implementation of its own.\n\n![](/media/summernote/Collection-Hierarchy2x-min.png)  \n\n## List Interface\n\nA `List` is an ordered collection of elements that may contain duplicates. Elements are indexed the same way as an array, starting at zero.\n\nElements can be inserted, accessed, and removed based on their index. The common `List` implementations in Java are:\n\n-   [ArrayList](/articles/arraylist-in-java)\n-   [LinkedList](/articles/linkedlist-in-java)\n-   [CopyOnWriteArrayList](/articles/copyonwritearraylist-in-java)\n-   [Vector](/articles/vector-in-java)\n-   [Stack](/articles/stack-in-java)\n\n## Set Interface\n\nA `Set` is a collection that doesn't allow duplicate entries. It exposes largely the same methods as `List`, but it can hold at most one `null` element.\n\nThe common `Set` implementations in Java include:\n\n-   [HashSet](/articles/hashset-in-java)\n-   [LinkedHashSet](/articles/linkedhashset-in-java)\n-   [TreeSet](/articles/treeset-in-java)\n\n## Queue Interface\n\nA `Queue` represents a collection where elements are inserted at the back and removed from the front (FIFO — first in, first out).\n\nThe common `Queue` implementations include:\n\n-   [LinkedList](/articles/linkedlist-in-java)\n-   [PriorityQueue](/articles/priorityqueue-in-java)\n-   [DelayQueue](/articles/delayqueue)\n-   [ArrayDeque](/articles/arraydeque-in-java)\n\n## Map Interface\n\n`Map` isn't technically a `Collection`, but it's still part of the Collections Framework. A `Map` stores data as key-value pairs, where each key maps to exactly one value.\n\n![](/media/summernote/Map-Hierarchy2x-min.png)  \n\nThe common `Map` implementations include:\n\n-   [HashMap](/articles/hashmap-in-java): unordered, allows one null key and multiple null values.\
1n-   [LinkedHashMap](/articles/linkedhashmap-in-java): ordered by insertion, allows one null key and multiple null values.\n-   [IdentityHashMap](/articles/identityhashmap-in-java): uses reference equality for keys.\n-   [TreeMap](/articles/treemap-in-java): sorted order, doesn't allow null keys, allows multiple null values.\n-   [Hashtable](/articles/hashtable-in-java): synchronized, doesn't allow null keys or values.\n\n## Fail-Fast vs Fail-Safe Iterators\n\nEvery non-concurrent collection in this course — `ArrayList`, `HashMap`, `HashSet`, `TreeMap`, `TreeSet`, and so on — tracks a `modCount` field that increments on every structural change (add/remove, not `set()`). Their iterators capture `modCount` at creation and compare it on every `next()` call. If the two don't match, you get a `ConcurrentModificationException`. This is called **fail-fast**: it exists to catch bugs, not to provide thread safety — it's a best-effort detector, not a guarantee, and it won't reliably trigger under genuine concurrent access.\n\nTwo implementations in this course opt out of that behaviour:\n\n-   `CopyOnWriteArrayList` iterates over a private snapshot of the array taken when the iterator was created. It never throws `ConcurrentModificationException`, and it won't see mutations made after the iterator was created either.\n-   `DelayQueue` uses a weakly consistent iterator — it also won't throw, and it may or may not reflect concurrent changes, with no guarantee either way.\n\nThe practical rule: never call `list.remove(item)` inside a `for-each` loop over `list`. Use `Iterator.remove()`, `ListIterator`, or `removeIf()` instead — all three update `modCount` in a way the iterator already accounts for.\n\n## Choosing a Collection\n\n| You need | Reach for |\n| --- | --- |\n| An indexable, resizable list | `ArrayList` |\n| Frequent inserts/removals at both ends | `ArrayDeque` |\n| A thread-safe list you mostly read, rarely write | `CopyOnWriteArrayList` |\n| Unique elements, no ordering guarantees | `HashSet` |\n| Unique elements, insertion order preserved | `LinkedHashSet` |\n| Unique elements, sorted order | `TreeSet` |\n| Fast key lookups, no ordering | `HashMap` |\n| Fast key lookups, insertion (or access) order preserved | `LinkedHashMap` |\n| Fast key lookups, sorted by key | `TreeMap` |\n| Always process the smallest/largest element next | `PriorityQueue` |\n| Process elements only after a delay expires | `DelayQueue` |\n| A LIFO stack | `ArrayDeque` (not `Stack`) |\n\nLegacy classes worth knowing but avoiding in new code: `Vector`, `Stack`, and `Hashtable`. They predate the Collections Framework, use coarse-grained per-method synchronization that hurts single-threaded performance for no benefit, and have modern replacements that are either faster (`ArrayDeque`) or genuinely thread-safe under concurrent access (`ConcurrentHashMap`, `CopyOnWriteArrayList`).\n"])</script>
1<script>self.__next_f.push([1,"1f:T5f5,"])</script>
1<script>self.__next_f.push([1,"\nThe `Hashtable` is a legacy implementation of HashMap. It provides a key-value store where the keys are hashed. HashMap performs better than `Hashtable`.\n\n### Key Properties of Hashtable\n\nThe `Hashtable` is synchronized, meaning it is thread-safe and can be shared between multiple threads.\n\n`Hashtable` does not allow `null` keys or values. If you try to add `null` as a key or value, it will throw a `NullPointerException`.\n\n```java\npublic class _1a_Hashtable {\n\n    public static void main(String[] args) {\n        Hashtable\u003cInteger, String\u003e hashtable = new Hashtable\u003c\u003e();\n        hashtable.put(1, \"One\");\n        hashtable.put(2, \"Two\");\n        hashtable.put(3, \"Three\");\n\n        // Retrieve a value by its key\n        String value = hashtable.get(2);\n        System.out.println(\"Value for key 2: \" + value);\n\n        // Remove a key-value pair\n        hashtable.remove(3);\n\n        // Check if a key exists\n        boolean containsKey = hashtable.containsKey(1);\n        System.out.println(\"Hashtable contains key 1: \" + containsKey);\n\n        // Check if a value exists\n        boolean containsValue = hashtable.containsValue(\"Two\");\n        System.out.println(\"Hashtable contains value 'Two': \" + containsValue);\n\n        // Get the size of the hashtable\n        int size = hashtable.size();\n        System.out.println(\"Size of hashtable: \" + size);\n\n        // Check if the hashtable is empty\n        boolean isEmpty = hashtable.isEmpty();\n        System.out.println(\"Is hashtable empty? \" + isEmpty);\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"20:T1446,"])</script>
1<script>self.__next_f.push([1,"\nThe `TreeMap` class in Java implements the `NavigableMap` interface, which in turn extends `SortedMap`. This means a `TreeMap` always stores its entries in sorted order.\n\n### Key Properties of TreeMap\n\nWe can also provide a comparator while initializing the TreeMap. If a comparator is not provided then it stores the elements in their natural ordering.\n\nThe NavigableMap interface provides several navigation methods such as `lowerEntry()`, `floorEntry()`, `ceilingEntry()`, and `higherEntry()`. It can be traversed in either ascending or descending key order.\n\nUnlike HashMap, the TreeMap does not allow `null` keys.\n\n### How it actually works\n\n`TreeMap` is a **red-black tree** — a self-balancing binary search tree that guarantees O(log n) for `put`, `get`, and `remove`, and O(log n) height even in the worst case (unlike a naive BST, which can degrade to a linked list under sorted-order insertion). Because it's a genuine tree of node objects rather than an array-backed bucket table, it has no load factor or resizing step to think about — there's nothing to resize.\n\n### Key equality is decided by compareTo, not equals\n\nSame caveat as [TreeSet](/articles/treeset-in-java), and it matters more here because map keys are so often domain objects with multi-field `equals()`: `TreeMap` never calls `equals()` or `hashCode()` on its keys. Two keys are \"the same\" if `compareTo()` (or your `Comparator`) returns `0` — full stop, regardless of what `equals()` would say. If your comparator only orders by one field, `put()` with a second key that ties on that field will silently overwrite the first entry, even if the two key objects are unequal by `equals()`.\n\nThe same rule governs mutation: change a field your comparator depends on while the key is already in the map, and you corrupt the tree's ordering invariant — lookups, range queries, and iteration can all start behaving incorrectly, not just for that one key.\n\n`TreeMap`'s iterator is fail-fast and always walks keys in sorted order — unlike `HashMap`, there's no separate \"insertion order vs iteration order\" question to think about.\n\n```java\npublic class TreeMapExample {\n    public static void main(String[] args) {\n        TreeMap\u003cInteger, String\u003e treeMap = new TreeMap\u003c\u003e();\n        treeMap.put(3, \"Three\");\n        treeMap.put(1, \"One\");\n        treeMap.put(4, \"Four\");\n        treeMap.put(2, \"Two\");\n\n        for (Map.Entry\u003cInteger, String\u003e entry : treeMap.entrySet()) {\n            System.out.println(entry.getKey() + \" -\u003e \" + entry.getValue());\n        }\n\n        // Accessing elements\n        System.out.println(\"Value for key 2: \" + treeMap.get(2));\n\n        // Getting first and last keys\n        System.out.println(\"First key: \" + treeMap.firstKey());\n        System.out.println(\"Last key: \" + treeMap.lastKey());\n\n        // Getting a subMap\n        System.out.println(\"SubMap from 2 to 4: \" + treeMap.subMap(2, 4));\n\n        // Removing an element\n        treeMap.remove(3);\n        System.out.println(\"TreeMap after removal of key 3: \" + treeMap);\n    }\n}\n\n/*\nOutputs:\n1 -\u003e One\n2 -\u003e Two\n3 -\u003e Three\n4 -\u003e Four\nValue for key 2: Two\nFirst key: 1\nLast key: 4\nSubMap from 2 to 4: {2=Two, 3=Three}\nTreeMap after removal of key 3: {1=One, 2=Two, 4=Four}\n*/\n```\n\n### TreeMap using Custom Comparator\n\nA custom comparator can be set to `TreeMap` during initialization. The above example can be rewritten using a comparator that stores entries in the reverse order of keys.\n\n```java\npublic class TreeMapCustomComparatorExample {\n    public static void main(String[] args) {\n        Comparator\u003cInteger\u003e reverseOrderComparator = (key1, key2) -\u003e key2.compareTo(key1);\n        TreeMap\u003cInteger, String\u003e treeMap = new TreeMap\u003c\u003e(reverseOrderComparator);\n        treeMap.put(3, \"Three\");\n        treeMap.put(1, \"One\");\n        treeMap.put(4, \"Four\");\n        treeMap.put(2, \"Two\");\n\n        for (Map.Entry\u003cInteger, String\u003e entry : treeMap.entrySet()) {\n            System.out.println(entry.getKey() + \" -\u003e \" + entry.getValue());\n        }\n\n        treeMap.remove(3);\n        System.out.println(\"TreeMap after removal of key 3: \" + treeMap);\n    }\n}\n/*\nOutputs:\n4 -\u003e Four\n3 -\u003e Three\n2 -\u003e Two\n1 -\u003e One\nTreeMap after removal of key 3: {4=Four, 2=Two, 1=One}\n*/\n```\n\n## TreeMap vs the Alternatives\n\n-   **vs `HashMap`**: O(log n) instead of O(1) average — the cost of keeping keys sorted. Only pay it when you need sorted iteration or range operations (`headMap`, `tailMap`, `ceilingKey`, `floorKey`); otherwise `HashMap` is faster.\n-   **vs `LinkedHashMap`**: different ordering guarantees entirely — `TreeMap` sorts by key value, `LinkedHashMap` preserves insertion or access order. Neither substitutes for the other.\n-   **vs `ConcurrentSkipListMap`**: `TreeMap` isn't thread-safe. If you need a sorted map under concurrent access, `ConcurrentSkipListMap` is the direct equivalent — a skip list instead of a red-black tree, but the same `NavigableMap` contract and similar O(log n) guarantees.\n\n### References\n\n-   [NavigableMap documentation](https://docs.oracle.com/javase/8/docs/api/java/util/NavigableMap.html)\n-   [SortedMap documentation](https://docs.oracle.com/javase/8/docs/api/java/util/SortedMap.html)\n"])</script>
1<script>self.__next_f.push([1,"21:Tdb7,"])</script>
1<script>self.__next_f.push([1,"\nThe `IdentityHashMap` implements the `Map` interface. Where `HashMap` compares keys by their content (using `equals()`), `IdentityHashMap` compares keys by reference — it only treats two keys as equal if they're the exact same object.\n\n### Key Properties of IdentityHashMap\n\nIt uses reference equality (`==`) instead of the `equals()` method, which makes it faster than `HashMap` for lookups, since it skips calling `equals()` and `hashCode()` altogether.\n\nIt also supports `null` keys and values.\n\n### How it actually works — and why it's not just \"HashMap with ==\"\n\n`IdentityHashMap` isn't a `HashMap` variant internally — it uses a genuinely different data structure. Where `HashMap` buckets colliding entries into linked lists (or trees), `IdentityHashMap` stores keys and values as alternating slots in one flat `Object[] table` (`table[2i]` is a key, `table[2i+1]` is its value) and resolves collisions with **open addressing**: if a key's slot is taken, it linearly probes forward to the next free pair of slots instead of chaining. The bucket index comes from `System.identityHashCode()` (or the JVM's internal object hash) rather than the key's own `hashCode()` — which is exactly why mutating a key's fields never breaks a lookup here, unlike `HashMap`.\n\nThe `Map` Javadoc says explicitly that `IdentityHashMap` is meant to violate the general `Map` contract on purpose. Its real use cases are narrow: cycle detection during deep-copy or serialization of an object graph (this is literally how `ObjectOutputStream` tracks already-serialized objects), or any case where tw
1o objects that are `equals()` to each other genuinely need to be treated as different keys. It is not a faster general-purpose `HashMap` — don't reach for it as a performance optimization unless reference identity is the actual semantic you need.\n\n```java\n// key1 and key2 are string literals, so the JVM interns them to the same object\nMap\u003cString, String\u003e map1 = new IdentityHashMap\u003c\u003e();\nString key1 = \"key\";\nString key2 = \"key\";\nmap1.put(key1, \"value1\");\nmap1.put(key2, \"value2\");\n\nfor (String key: map1.keySet()) {\n    System.out.println(key + \" -\u003e \" + map1.get(key));\n}\n\n/*\nOutputs:\nkey -\u003e value2\n*/\n\nMap\u003cString, String\u003e map2 = new IdentityHashMap\u003c\u003e();\nString key3 = new String(\"key\");\nString key4 = new String(\"key\");\nmap2.put(key3, \"value1\");\nmap2.put(key4, \"value2\");\n\nfor (String key : map2.keySet()) {\n    System.out.println(key + \" -\u003e \" + map2.get(key));\n}\n\n/*\nOutputs:\nkey -\u003e value2\nkey -\u003e value1\n*/\n```\n\nIn the second map, `key3` and `key4` have the same content but are different objects, since `new String(...)` always allocates a fresh object instead of reusing the interned one. `IdentityHashMap` treats them as two distinct keys, so `map2` ends up with two entries instead of one.\n\nIts iterator is fail-fast, same as `HashMap`'s.\n\n## IdentityHashMap vs the Alternatives\n\n-   **vs `HashMap`**: use `HashMap` for essentially everything — key equality by content is what you want in the overwhelming majority of cases. Reach for `IdentityHashMap` only when reference identity genuinely is the semantic (cycle detection, object-graph tracking), not as a \"faster HashMap.\"\n-   **vs a `HashMap` with a custom `IdentityWrapper` key**: some codebases hand-roll a wrapper class that overrides `equals()`/`hashCode()` to use `==`/`System.identityHashCode()`, just to get identity semantics out of a regular `HashMap`. `IdentityHashMap` gives you the same guarantee without the wrapper allocation on every key.\n"])</script>
1<script>self.__next_f.push([1,"22:T1054,"])</script>
1<script>self.__next_f.push([1,"\nThe `LinkedHashMap` works very similar to `HashMap` but it maintains a doubly-linked list to maintain the insertion order of elements.\n\n### Key Properties of LinkedHashMap\n\nDue to the additional overhead for maintaining order, `LinkedHashMap` is generally slower as compared to `HashMap`.\n\n### How it actually works\n\n`LinkedHashMap` extends `HashMap` and reuses its entire bucket/hash-table mechanism for lookups — same [treeification and resizing behaviour covered in the HashMap article](/articles/hashmap-in-java), and the same [mutable-key trap](/articles/hashmap-in-java) if you mutate a hashCode-relevant field after insertion. What it adds is a doubly-linked list threading through every entry (`LinkedHashMap.Entry` extends `HashMap.Node` with two extra `before`/`after` references), maintained alongside the hash table purely to give iteration a predictable order. `get`/`put`/`remove` stay O(1) average, same as `HashMap`; the linked list only costs you memory and a small constant amount of pointer maintenance per operation, not asymptotic complexity. Its iterator is fail-fast, same as `HashMap`'s.\n\n```java\nMap\u003cString, Integer\u003e map = new LinkedHashMap\u003c\u003e();\nmap.put(\"B\", 2);\nmap.put(\"A\", 1);\nmap.put(\"C\", 3);\nmap.put(null, 4);\n\nfor (Map.Entry\u003cString, Integer\u003e entry : map.entrySet()) {\n    System.out.println(entry.getKey() + \": \" + entry.getValue());\n}\n```\n\n**Output:**\n\n```text\nB: 2\nA: 1\nC: 3\nnull: 4\n```\n\nBy default, `LinkedHashMap` maintains insertion order, but you can switch it to access order by passing `true` for the `accessOrder` constructor parameter.\n\n```java\nMap\u003cString, Integer\u003e map = new LinkedHashMap\u003c\u003e(16, 0.75f, true);\nmap.put(\"B\", 2);\nmap.put(\"A\", 1);\nmap.put(\"C\", 3);\nmap.put(null, 4);\n\nmap.get(\"A\");\nmap.get(\"B\");\n\nfor (Map.Entry\u003cString, Integer\u003e entry : map.entrySet()) {\n    System.out.println(entry.getKey() + \": \" + entry.getValue());\n}\n```\n\n**Output:**\n\n```text\nC: 3\nnull: 4\nA: 1\nB: 2\n```\n\nNotice that `A` and `B` moved to the end after being read — in access-order mode, every `get()` (and `put()`) relinks that entry to the tail of the internal list, so the list naturally orders itself from least-recently-used to most-recently-used.\n\n### Building an LRU cache\n\nThis is the real reason `accessOrder` exists. Override `removeEldestEntry()` — a protected hook `HashMap` doesn't have but `LinkedHashMap` adds specifically for this — to tell the map when to evict the oldest entry, and you get a working bounded LRU cache in a handful of lines, without hand-rolling the linked-list bookkeeping yourself:\n\n```java\nclass LruCache\u003cK, V\u003e extends LinkedHashMap\u003cK, V\u003e {\n    private final int maxSize;\n\n    LruCache(int maxSize) {\n        super(16, 0.75f, true); // accessOrder = true\n        this.maxSize = maxSize;\n    }\n\n    @Override\n    protected boolean removeEldestEntry(Map.Entry\u003cK, V\u003e eldest) {\n        return size() \u003e maxSize;\n    }\n}\n\nLruCache\u003cString, String\u003e cache = new LruCache\u003c\u003e(3);\ncache.put(\"A\", \"1\");\ncache.put(\"B\", \"2\");\ncache.put(\"C\", \"3\");\ncache.get(\"A\");        // \"A\" is now most-recently-used\ncache.put(\"D\", \"4\");    // evicts \"B\" — the least-recently-used entry\n\nSystem.out.println(cache.keySet()); // [C, A, D]\n```\n\n`removeEldestEntry()` is called automatically after every `put()`, with the current least-recently-used entry passed in — returning `true` removes it. This is the standard, JDK-provided way to build an LRU cache; you don't need a separate data structure.\n\n## LinkedHashMap vs the Alternatives\n\n-   **vs `HashMap`**: same average-case performance, plus predictable order, for a small constant memory overhead per entry. Default to `HashMap` unless you specifically need insertion order, access order, or the `removeEldestEntry` LRU hook.\n-   **vs `TreeMap`**: `LinkedHashMap` gives you insertion/access order in O(1) average time; `TreeMap` gives you sorted-by-key order in O(log n). They're not interchangeable — pick based on which ordering you actually need.\n-   **vs hand-rolling an LRU cache with a `HashMap` + a separate queue/list**: don't — `LinkedHashMap` with `accessOrder=true` and `removeEldestEntry` already does exactly this, c
1orrectly, with less code and less room for bugs.\n"])</script>
1<script>self.__next_f.push([1,"23:T1b7f,"])</script>
1<script>self.__next_f.push([1,"\nA `HashMap` works fundamentally differently than the other collections. A `HashMap` uses key-value pairs to insert and access items.\n\n### Key Properties of HashMap\n\nAll keys must be unique, and like a `HashSet`, a `HashMap` doesn't maintain order. `HashMap` is a great choice when you already know the key of the item you want to access.\n\nA `HashMap` can hold multiple null values, and one of its keys can also be null.\n\n### How it actually works\n\n`HashMap` stores entries in a `Node\u003cK,V\u003e[] table`, where each slot (\"bucket\") holds either nothing, one entry, a linked list of entries that collided into the same bucket, or — since Java 8, once a bucket collects 8+ entries **and** the table itself has grown to at least 64 buckets — a red-black tree. That treeification caps the worst case at O(log n) instead of degrading to O(n) the way pre-Java-8 `HashMap` did under hash-collision-heavy workloads; a bucket un-treeifies back to a linked list if it later drops to 6 or fewer entries.\n\nWhich bucket a key lands in is `(table.length - 1) \u0026 hash`, where `hash` isn't just `key.hashCode()` — it's `hashCode() ^ (hashCode() \u003e\u003e\u003e 16)`. That XOR-with-its-own-upper-bits step spreads high-order bits into the low-order bits before masking, so keys whose hash codes only differ in their upper bits (a real problem your own `hashCode()` implementations can produce) still land in different buckets.\n\nDefault initial capacity is 16, default load factor is 0.75. Once `size` exceeds `capacity × loadFactor`, the table doubles and every entry gets rehashed into the new bucket array. If you know roughly how many entries you'll store, passing an initial capacity up front avoids paying for that rehashing repeatedly.\n\n### The mutable key trap\n\nThis is the classic Java gotcha, and it applies to `HashMap` even more often than `HashSet` in practice, because map keys are frequently domain objects:\n\n```java\nclass UserId {\n    String value;\n    UserId(String value) { this.value = value; }\n\n    @Override\n    public boolean equals(Object o) {\n        return o instanceof UserId u \u0026\u0026 value.equals(u.value);\n    }\n\n    @Override\n    public int hashCode() {\n        return value.hashCode();\n    }\n}\n\nMap\u003cUserId, String\u003e sessions = new HashMap\u003c\u003e();\nUserId id = new UserId(\"abc\");\nsessions.put(id, \"active\");\n\nid.value = \"xyz\"; // mutated after being used as a key\n\nSystem.out.println(sessions.get(id));             // null — looks in the (now) \"xyz\" bucket\nSystem.out.println(sessions.get(new UserId(\"abc\"))); // also null — that bucket no longer holds this entry\nSystem.out.println(sessions);                      // still shows {UserId@...=active} — the entry is right there, just unreachable by key\n```\n\n`sessions.get(id)` recomputes the hash from `id`'s *current* state, so it looks in a different bucket than the one the entry actually lives in. The entry isn't lost — `entrySet()`/`toString()` will still show it — it's just unreachable through `get()`/`containsKey()`/`remove()`. Treat any object used as a `HashMap` key (or `HashSet` element) as effectively immutable for as long as it's in the map.\n\nAlso worth internalizing: `HashMap`'s iterator (over `keySet()`, `values()`, or `entrySet()`) is fail-fast — mutating the map structurally while iterating throws `ConcurrentModificationException`, same as every other non-concurrent collection in this course. Use `Iterator.remove()` or `entrySet().removeIf(...)` instead of removing through the map directly inside a loop.\n\n### Creating a HashMap\n\n```java\n// Using the default constructor\nHashMap\u003cString, Integer\u003e hashMap = new HashMap\u003c\u003e();\nhashMap.put(\"A\", 1);\nhashMap.put(\"B\", 2);\nhashMap.put(\"C\", 3);\n\n// Using a constructor with an initial capacity\nHashMap\u003cString, Integer\u003e hashMapWithCapacity = new HashMap\u003c\u003e(50);\n\n// Using a constructor with an initial capacity and load factor\nHashMap\u003cString, Integer\u003e hashMapWithLoadFactor = new HashMap\u003c\u003e(50, 0.75f);\n\n// Using a constructor to copy another map\nMap\u003cString, Integer\u003e map1 = new HashMap\u003c\u003e();\nmap1.put(\"A\", 1);\nmap1.put(\"B\", 2);\nHashMap\u003cString, Integer\u003e map2 = new HashMap\u003c\u003e(map1);\n\n// Using Java 8 streams to initialize from parallel lists\nList\u003cString\u003e keys = Arrays.asList(\"A\", \"B\", \"C\");\nList\u003cInteger\u003e values = Arrays.asList(1, 2, 3);\nHashMap\u003cString, Integer\u003e hashMapFromStream = IntStream.range(0, keys.size())\n        .boxed()\n        .collect(Collectors.toMap(keys::get, values::get, (e1, e2) -\u003e e2, HashMap::new));\n\n// Using the Map.of factory method\nMap\u003cString, Integer\u003e immutableMap = Map.of(\"A\", 1, \"B\", 2, \"C\", 3);\nHashMap\u003cString, Integer\u003e hashMapFromImmutable = new HashMap\u003c\u003e(immutableMap);\n```\n\nThe order of items stored in a map isn't guaranteed. We access an item inside the map using its key.\n\n```java\nhashMap.get(\"A\");\n```\n\n### Iterate over a HashMap\n\n```java\n// Using an Iterator\nIterator\u003cString\u003e keyIterator = hashMap.keySet().iterator();\nwhile (keyIterator.hasNext()) {\n    String key = keyIterator.next();\n    System.out.println(\"Key: \" + key);\n}
1\n\n// Iterating over Values\nIterator\u003cInteger\u003e valueIterator = hashMap.values().iterator();\nwhile (valueIterator.hasNext()) {\n    Integer value = valueIterator.next();\n    System.out.println(\"Value: \" + value);\n}\n\n// Iterating over Entries\nIterator\u003cMap.Entry\u003cString, Integer\u003e\u003e entryIterator = hashMap.entrySet().iterator();\nwhile (entryIterator.hasNext()) {\n    Map.Entry\u003cString, Integer\u003e entry = entryIterator.next();\n    System.out.println(\"Key: \" + entry.getKey() + \", Value: \" + entry.getValue());\n}\n\n//Using Java 8 forEach and Lambda Expression\nhashMap.forEach((key, value) -\u003e {\n    System.out.println(\"Key: \" + key + \", Value: \" + value);\n});\n\n//Using Streams\nhashMap.entrySet().stream().forEach(entry -\u003e {\n    System.out.println(\"Key: \" + entry.getKey() + \", Value: \" + entry.getValue());\n});\n\n//Using the forEach Method\nhashMap.entrySet().forEach(entry -\u003e {\n    System.out.println(\"Key: \" + entry.getKey() + \", Value: \" + entry.getValue());\n});\n```\n\n## HashMap vs the Alternatives\n\n-   **vs `LinkedHashMap`**: identical O(1) average performance, plus predictable iteration order, for a small constant memory overhead per entry. Default to `HashMap` unless order specifically matters.\n-   **vs `TreeMap`**: O(1) average vs O(log n), but `TreeMap` keeps keys sorted and supports range queries (`headMap`, `tailMap`, `ceilingKey`). Pick based on whether you need sorted keys at all.\n-   **vs `Hashtable`**: `Hashtable` is a legacy synchronized map with coarse-grained per-method locking and no null keys/values — there's no reason to choose it over `HashMap` in single-threaded code, or over `ConcurrentHashMap` in multi-threaded code.\n-   **vs `ConcurrentHashMap`**: `HashMap` isn't thread-safe — concurrent structural modification can corrupt its internal bucket/tree structure, not just throw an exception. If multiple threads write to the same map, use `ConcurrentHashMap`, which uses lock striping (locking individual buckets, not the whole map) instead of the single coarse lock `Collections.synchronizedMap()` or `Hashtable` would give you.\n"])</script>
1<script>self.__next_f.push([1,"24:T1245,"])</script>
1<script>self.__next_f.push([1,"\nThe `ArrayDeque` is a resizable array implementation of the `Deque` interface. It supports adding and removing elements from both ends of the deque (double-ended queue) efficiently.\n\n### Key Properties of ArrayDeque\n\nThe `ArrayDeque` can be used as a queue (FIFO) and a stack (LIFO).\n\nIt allows the insertion and removal of elements from both ends. The underlying array resizes dynamically as elements are added or removed.\n\nIt is not synchronized, meaning you need to manage synchronization externally for multithreaded use.\n\n### How it actually works\n\n`ArrayDeque` is backed by a **circular array** — not a linked list of nodes, despite implementing the same `Deque` interface as `LinkedList`. It tracks a `head` and `tail` index into that array; adding to the front decrements `head` (wrapping around to the end when it hits `0`), and adding to the end increments `tail`, wrapping the same way. The array's capacity is always kept a power of two specifically so that wraparound can be computed with a cheap bitmask (`index \u0026 (capacity - 1)`) instead of the more expensive modulo operator. When the array fills up, it doubles, same as `Vector`'s default growth.\n\nThis circular-array design is exactly why `ArrayDeque` beats both `LinkedList` and `Stack` for stack/queue workloads: no per-element node allocation, and elements sit contiguously in memory for better cache locality, at the cost of losing `LinkedList`'s ability to splice in O(1) at an arbitrary interior position.\n\n### No null elements allowed\n\nUnlike `LinkedList`, `ArrayDeque` throws a `NullPointerException` if you try to add `null`. This isn't an arbitrary restriction — `peek()` and `poll()`-style methods return `null` to signal \"the deque is empty,\" so allowing `null` as an actual element would make that signal ambiguous. If your existing code stores `null` in a `LinkedList` used as a queue, switching to `ArrayDeque` is not a drop-in replacement.\n\nIts iterator is fail-fast, like the other non-concurrent collections in this course.\n\n**Example:** Suppose you are developing a text editor with an undo and redo feature. You can use two `ArrayDeque` instances to manage the history of operations: one for undo and one for redo.\n\n```java\npublic class TextEditor {\n    private StringBuilder text;\n    private ArrayDeque\u003cString\u003e undoStack;\n    private ArrayDeque\u003cString\u003e redoStack;\n\n    public TextEditor() {\n        text = new StringBuilder();\n        undoStack = new ArrayDeque\u003c\u003e();\n        redoStack = new ArrayDeque\u003c\u003e();\n    }\n\n    public void appendText(String newText) {\n        undoStack.push(text.toString());\n        redoStack.clear();\n        text.append(newText);\n    }\n\n    public void undo() {\n        if (!undoStack.isEmpty()) {\n            redoStack.push(text.toString());\n            text = new StringBuilder(undoStack.pop());\n        }\n    }\n\n    public void redo() {\n        if (!redoStack.isEmpty()) {\n            undoStack.push(text.toString());\n            text = new StringBuilder(redoStack.pop());\n        }\n    }\n\n    public String getText() {\n        return text.toString();\n    }\n\n    public static void main(String[] args) {\n        TextEditor editor = new TextEditor();\n        editor.appendText(\"Hello\");\n        editor.appendText(\", World!\");\n        System.out.println(\"Current Text: \" + editor.getText());\n\n        editor.undo();\n        System.out.println(\"After Undo: \" + editor.getText());\n\n        editor.redo();\n        System.out.println(\"After Redo: \" + editor.getText());\n\n        editor.undo();\n        editor.undo();\n        System.out.println(\"After two Undos: \" + editor.getText());\n    }\n}\n```\n\n**Output:**\n\n```text\nCurrent Text: Hello, World!\nAfter Undo: Hello\nAfter Redo: Hello, World!\nAfter two Undos:\n```\n\n## ArrayDeque vs the Alternatives\n\n-   **vs `LinkedList`**: `ArrayDeque` is faster and lighter for the same `Deque`/`Queue` operations — no per-node allocation, better cache behaviour, and the JDK's own documentation recommends it over `LinkedList` for this purpose. `LinkedList` only wins if you need `null` elements or O(1) insertion at an arbitrary interior position via a `ListIterator`.\n-   **vs `Stack`**: see the [Stack article](/articles/stack-in-java) — `Stack extends Vector`, inherits synchronized-by-default overhead most code doesn't need, and exposes a full `List` API that can be used to accidentally break LIFO ordering. `ArrayDeque` avoids both problems.\n-   **vs `PriorityQueue`**: different job entirely — `ArrayDeque` preserves insertion order (whichever end you push/pop from); `PriorityQueue` reorders by priority. Don't reach for `ArrayDeque` if what you actually need is \"always process the smallest/largest next.\"\n"])</script>
1<script>self.__next_f.push([1,"25:T1274,"])</script>
1<script>self.__next_f.push([1,"\nA `DelayQueue` in Java is a specialized implementation of a blocking queue that supports delayed elements. Elements can only be taken from the queue when their delay has expired. This makes it useful for scenarios where tasks need to be executed after a certain delay.\n\n### Key Properties of DelayQueue\n\nElements in the `DelayQueue` must implement the `Delayed` interface, which requires implementing the `getDelay` method to specify the delay time and the `compareTo` method for ordering.\n\nThe queue blocks retrieval operations until the delay of the head element has expired.\n\n### How it actually works\n\nInternally, `DelayQueue` wraps a `PriorityQueue` — the same binary heap [covered in the PriorityQueue article](/articles/priorityqueue-in-java) — ordered by `compareTo()`, guarded by a `ReentrantLock` and a `Condition`. `take()` peeks the head; if its delay hasn't expired, the calling thread awaits on the condition for exactly that remaining duration (not a busy loop) and re-checks on wake. Internally it also uses a \"leader-follower\" optimization: only one waiting thread (the \"leader\") ever times its wait against the head element's actual delay — every other waiting thread just blocks indefinitely until signaled, which avoids every consumer thread waking up and re-checking the clock every time the head changes.\n\n### Its iterator makes no ordering promises at all\n\nThis is worth calling out explicitly, because it's easy to assume `iterator()` returns elements in delay/expiry order — it doesn't. `DelayQueue`'s iterator doesn't even guarantee the heap-order that `PriorityQueue`'s iterator gives you; the Javadoc explicitly says it makes no guarantees of any kind about traversal order. It's also **weakly consistent** rather than fail-fast: it won't throw `ConcurrentModificationException` if the queue is modified during iteration, and it may or may not reflect those concurrent changes. If you need the current contents in delay order, drain via `take()`/`poll()`, or copy with `toArray()` and sort.\n\n**Example:** Suppose you are developing a system where tasks need to be executed after a certain delay, such as sending out delayed notifications.\n\n```java\nclass Notification implements Delayed {\n    private final String name;\n    private final long startTime;\n\n    public Notification(String name, long delay, TimeUnit unit) {\n        this.name = name;\n        this.startTime = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(delay, unit);\n    }\n\n    @Override\n    public long getDelay(TimeUnit unit) {\n        long delay = startTime - System.currentTimeMillis();\n        return unit.convert(delay, TimeUnit.MILLISECONDS);\n    }\n\n    @Override\n    public int compareTo(Delayed other) {\n        return Long.compare(this.startTime, ((Notification) other).startTime);\n    }\n\n    @Override\n    public String toString() {\n        return \"Task: {name='\" + name + \"', startTime=\" + startTime + '}';\n    }\n}\n\npublic class DelayQueueExample {\n    public static void main(String[] args) throws InterruptedException {\n        DelayQueue\u003cNotification\u003e notifications = new DelayQueue\u003c\u003e();\n        notifications.add(new Notification(\"Task 1\", 5, TimeUnit.SECONDS));\n        notifications.add(new Notification(\"Task 2\", 10, TimeUnit.SECONDS));\n        notifications.add(new Notification(\"Task 3\", 3, TimeUnit.SECONDS));\n\n        // Processing tasks as they expire\n        while (!notifications.isEmpty()) {\n            Notification task = notifications.take();\n            System.out.println(\"Notifying \" + task);\n        }\n    }\n}\n```\n\nNote that the `take()` method retrieves and removes tasks from the queue when their delay has expired, blocking until a task is available.\n\n**Output:**\n\n```text\nNotifying Task: {name='Task 3', startTime=1721688863846}\nNotifying Task: {name='Task 1', startTime=1721688865846}\nNotifying Task: {name='Task 2', startTime=1721688870846}\n```\n\n## DelayQueue vs the Alternatives\n\n-   **vs `ScheduledExecutorService`**: for the common case of \"run this task after a delay\" or \"run this task repeatedly,\" `ScheduledExecutorService`/`ScheduledThreadPoolExecutor` is the higher-level tool and handles thread management for you. Reach for `DelayQueue` when you need custom control over the consumer side — for example, a cache that evicts entries only after they've expired, where you're pulling expired items yourself rather than firing a fixed callback.\n-   **vs a plain `PriorityQueue` with manual sleep logic**: `DelayQueue` already handles the blocking-until-ready and multi-consumer coordination correctly, including the leader-follower optimization. Reimplementing that on top of `PriorityQueue` yourself is a lot of concurrency detail to get right for no benefit.\n"])</script>
1<script>self.__next_f.push([1,"26:T14d5,"])</script>
1<script>self.__next_f.push([1,"\nA `PriorityQueue` in Java is a type of queue that stores elements in a way such that the element with the highest priority is always at the front of the queue. It is implemented as a binary heap, providing an efficient way to access and manage elements based on priority.\n\n### Key Properties of PriorityQueue\n\nElements are ordered based on their natural ordering, or by a `Comparator` supplied at queue construction time.\n\n`PriorityQueue` is not synchronized. If you need a thread-safe option, use `PriorityBlockingQueue` instead.\n\nThe queue has no fixed size, it can grow as elements are added.\n\nUse `PriorityQueue` when you need to manage tasks or elements that should be processed in a priority order.\n\n### How it actually works\n\nA `PriorityQueue` is a **binary heap** stored in a plain `Object[]`, not a tree of node objects. Each element's parent and children are computed by index arithmetic — the children of index `i` live at `2i + 1` and `2i + 2`, and the parent of `i` lives at `(i - 1) / 2`. `offer()` appends to the end and \"sifts up\" (swapping with its parent until the heap property holds); `poll()` removes index `0` (always the smallest/highest-priority element under the given ordering), moves the last element to the root, and \"sifts down.\" Both are O(log n); `peek()` is O(1) since the top element is always at index `0`.\n\n### Iterating does not give you priority order\n\nThis is the single most common `PriorityQueue` surprise: only `poll()` (or repeated `peek()`+`poll()`) guarantees elements come out in priority order. The `Iterator` returned by `iterator()` walks the backing array in whatever order the heap happens to store it in — which satisfies the heap property (a parent is always ≤ its children) but is *not* a fully sorted order.\n\n```java\nPriorityQueue\u003cInteger\u003e pq = new PriorityQueue\u003c\u003e(List.of(5, 1, 3, 2, 4));\n\nSystem.out.print(\"Iterator order: \");\nfor (int n : pq) {\n    System.out.print(n + \" \");\n}\n\nSystem.out.print(\"\\nPoll order:     \");\nwhile (!pq.isEmpty()) {\n    System.out.print(pq.poll() + \" \");\n}\n```\n\n```text\nIterator order: 1 2 3 5 4\nPoll order:     1 2 3 4 5\n```\n\nIf you need a fully sorted snapshot without draining the queue, sort a copy: `Arrays.sort(pq.toArray())` or `pq.stream().sorted().toList()`.\n\nThe iterator is still fail-fast for structural changes made outside the iterator itself — it just isn't ordered.\n\n### Mutating priority after insertion breaks the heap\n\nSame category of bug as [TreeSet's compareTo trap](/articles/treeset-in-java): if you change a field your `Comparator` (or `compareTo`) depends on after the element is already in the queue, the heap's internal ordering invariant silently breaks — `poll()` can start returning elements out of order, because the heap was built around a priority that no longer matches. If a task's priority needs to change, remove it (`remove(task)` — O(n), since it has to search first) and re-add it.\n\n**Example:** Suppose you are developing a task management system where tasks have different priorities. Higher-priority tasks should be processed before lower-priority tasks.\n\n```java\nclass Task {\n    private String name;\n    private int priority;\n\n    public Task(String name, int priority) {\n        this.name = name;\n        this.priority = priority;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public int getPriority() {\n        return priority;\n    }\n\n    @Override\n    public String toString() {\n        return \"Task{name='\" + name + \"', priority=\" + priority + \"}\";\n    }\n}\n\npublic class TaskManager {\n    public static void main(String[] args) {\n        PriorityQueue\u003cTask\u003e taskQueue = new PriorityQueue\u003c\u003e(Comparator.comparingInt(Task::getPriority).reversed());\n        taskQueue.add(new Task(\"Task 1\", 3));\n        taskQueue.add(new Task(\"Task 2\", 1));\n        taskQueue.add(new Task(\"Task 3\", 4));\n        taskQueue.add(new Task(\"Task 4\", 2));\n\n        System.out.println(\"Printing tasks based on priority:\");\n        while (!taskQueue.isEmpty()) {\n            Task task = taskQueue.poll();\n            System.out.println(\"Processing \" + task);\n        }\n    }\n}\n```\n\n**Output:**\n\n```text\nPrinting tasks based on priority:\nProcessing Task{name='Task 3', priority=4}\nProcessing Task{name='Task 1', priority=3}\nProcessing Task{name='Task 4', priority=2}\nProcessing Task{name='Task 2', priority=1}\n```\n\n## PriorityQueue vs the Alternatives\n\n-   **vs `TreeSet`/`TreeMap`**: both are O(log n) for insert, but `PriorityQueue` only gives you efficient access to the single smallest/largest element. Finding or removing an *arbitrary* element is O(n) in a `PriorityQueue` (it has to scan the array) versus O(log n) in a `TreeSet`. If you only ever need \"give me the next one,\" `PriorityQueue` is lighter — array-backed, no per-node allocation, better cache locality. If you need range queries or arbitrary removal, use `TreeSet`.\n-   **vs sorting a `List` repeatedly**: don't. Sorting is O(n log n) every time; a `PriorityQueue` amortizes that cost across individual O(log n) insertions, which wins as soon as you're doing more than one insert between reads.\n-   **vs `PriorityBlockingQueue`**: same heap semantics, but thread-safe and blocking — `take()` waits if the queue is empty instead of returning `null`. Reach for it when producers and consumers run on different threads.\n"])</script>
1<script>self.__next_f.push([1,"27:T119d,"])</script>
1<script>self.__next_f.push([1,"\nA `TreeSet` in Java is a collection that implements the `NavigableSet` interface and uses a `TreeMap` internally to store elements.\n\n### Key Properties of TreeSet\n\nTreeSet provides an ordered set implementation that sorts elements based on their natural ordering or according to a specified comparator.\n\nWhen you need to maintain a collection of unique elements in a sorted order, you can go for `TreeSet`.\n\n### How it actually works\n\nA `TreeSet\u003cE\u003e` is a thin wrapper around a `TreeMap\u003cE, Object\u003e` — the same relationship `HashSet` has with `HashMap`. Elements become keys in the backing map, paired with a shared dummy value, and `TreeMap` is a self-balancing red-black tree. That gives `add`, `remove`, and `contains` O(log n) worst-case time — slower than `HashSet`'s O(1) average, but you get sorted iteration and range operations (`headSet`, `tailSet`, `subSet`, `ceiling`, `floor`) for free.\n\n### Uniqueness is decided by compareTo, not equals\n\nThis trips people up: `TreeSet` never calls `equals()` or `hashCode()`. It decides whether two elements are \"the same\" purely by whether `compareTo()` (or your `Comparator`) returns `0`. If your `compareTo` only looks at one field, two objects that differ in every other field but tie on that one will be treated as duplicates — the second `add()` silently does nothing, even though `equals()` on those same two objects would return `false`. This is exactly the trap `BigDecimal` is famous for: `new BigDecimal(\"1.0\").compareTo(new BigDecimal(\"1.00\"))` is `0`, but `.equals()` on the same pair is `false`. If you're using a `TreeSet`, `compareTo` *is* your equality definition — make sure that's actually what you want.\n\nThe same applies to mutation after insertion: if you change a field your comparator depends on while the object is already in the set, you corrupt the tree's internal ordering invariant. Unlike `HashSet` (which just can't find the element anymore), a `TreeSet` with a broken invariant can behave unpredictably across all sorted operations, not just lookups of that one element.\n\n`TreeSet`'s iterator is fail-fast, same as the other collections in this course, and it always traverses in sorted order.\n\n**Example:** Suppose you're building an application for managing a library. You need to keep track of book titles in sorted order, so you can search and display them alphabetically.\n\n```java\npublic class LibraryManager {\n    public static void main(String[] args) {\n        TreeSet\u003cString\u003e bookTitles = new TreeSet\u003c\u003e();\n        bookTitles.add(\"To Kill a Mockingbird\");\n        bookTitles.add(\"1984\");\n        bookTitles.add(\"Pride and Prejudice\");\n        bookTitles.add(\"Queen of England\");\n        bookTitles.add(\"The Catcher in the Rye\");\n        bookTitles.add(\"1984\"); // Duplicate title, will not be added again\n\n        // Display the book titles in sorted order\n        System.out.println(\"Book titles (sorted):\");\n        for (String title : bookTitles) {\n            System.out.println(title);\n        }\n\n        // Finding the first and last book titles\n        System.out.println(\"\\nFirst book in the library: \" + bookTitles.first());\n        System.out.println(\"Last book in the library: \" + bookTitles.last());\n\n        // Displaying a subset of books\n        System.out.println(\"\\nBooks between 'P' and 'T':\");\n        for (String title : bookTitles.subSet(\"P\", \"T\")) {\n            System.out.println(title);\n        }\n    }\n}\n```\n\n**Output:**\n\n```text\nBook titles (sorted):\n1984\nPride and Prejudice\nQueen of England\nThe Catcher in the Rye\nTo Kill a Mockingbird\n\nFirst book in the library: 1984\nLast book in the library: To Kill a Mockingbird\n\nBooks between 'P' and 'T':\nPride and Prejudice\nQueen of England\n```\n\n## TreeSet vs the Alternatives\n\n-   **vs `HashSet`**: O(log n) instead of O(1) average for the basic operations — that's the price of keeping elements sorted. Only pay it when you actually need sorted iteration or range queries; otherwise `HashSet` is faster.\n-   **vs `LinkedHashSet`**: `TreeSet` sorts by value; `LinkedHashSet` preserves insertion order. Neither is a substitute for the other — they answer different questions about \"what order.\"\n-   **vs `PriorityQueue`**: both keep elements ordered, but `PriorityQueue` only gives you efficient access to the single smallest/largest element (`peek`/`poll`). `TreeSet` gives you the full sorted structure — arbitrary range queries, removal of arbitrary elements in O(log n), and full sorted iteration — at a similar per-operation cost.\n"])</script>
1<script>self.__next_f.push([1,"28:Tc89,"])</script>
1<script>self.__next_f.push([1,"\nA `LinkedHashSet` combines the behaviour of a hash table and a linked list. It extends `HashSet` and implements the `Set` interface, so elements stay unique while also preserving insertion order.\n\n### Key Properties of LinkedHashSet\n\n`HashSet` doesn't guarantee insertion order, but `LinkedHashSet` maintains the order in which elements were added.\n\nReach for `LinkedHashSet` whenever you need unique elements but also need to iterate them in the order they were added.\n\n### How it actually works\n\n`LinkedHashSet` extends `HashSet`, and `HashSet` is itself a wrapper around `HashMap` — so `LinkedHashSet` is really backed by a `LinkedHashMap` under the hood, not a plain `HashMap`. Every entry gets two extra reference fields (`before` and `after`) threading it into a doubly-linked list alongside its normal position in the hash table. Lookups (`contains`, `add`, `remove`) still go through the hash table, so they stay O(1) average — the linked list exists purely to give iteration a stable, predictable order, and it costs a small, constant amount of extra memory per element compared to `HashSet`.\n\nSince it inherits from `HashSet`, it inherits the same [mutable-element trap](/articles/hashset-in-java) — mutating a field involved in `hashCode()`/`equals()` after insertion breaks lookups the same way. Its iterator is also fail-fast, same as `HashSet`.\n\n**Example:** Suppose you are developing a system for tracking user activities on a website. You want to keep track of the unique pages visited by a user in the order they were visited. This can be efficiently managed using a `LinkedHashSet`.\n\n```java\npublic class UserActivityTracker {\n    public static void main(String[] args) {\n        LinkedHashSet\u003cString\u003e pagesVisited = new LinkedHashSet\u003c\u003e();\n\n        pagesVisited.add(\"home.html\");\n        pagesVisited.add(\"about.html\");\n        pagesVisited.add(\"contact.html\");\n        pagesVisited.add(\"home.html\");\n        pagesVisited.add(\"services.html\");\n\n        // Display the pages visited in the order of insertion\n        System.out.println(\"Pages visited by the user in order:\");\n        for (String page : pagesVisited) {\n            System.out.println(page);\n        }\n\n        System.out.println(\"-----\");\n        pagesVisited.spliterator().forEachRemaining(System.out::println);\n    }\n}\n```\n\nNotice that `home.html` is added only once to the `LinkedHashSet`, even though we called `add()` on it twice.\n\n**Output:**\n\n```text\nPages visited by the user in order:\nhome.html\nabout.html\ncontact.html\nservices.html\n-----\nhome.html\nabout.html\ncontact.html\nservices.html\n```\n\n## LinkedHashSet vs the Alternatives\n\n-   **vs `HashSet`**: identical performance characteristics, plus predictable iteration order, at the cost of two extra references per entry. Use `LinkedHashSet` when the order you display or process elements in actually matters to correctness (or to a human reading the output) — otherwise `HashSet` is marginally cheaper.\n-   **vs `TreeSet`**: `LinkedHashSet` preserves *insertion* order in O(1) average time; `TreeSet` maintains *sorted* order in O(log n). They solve different problems — pick based on whether \"order added\" or \"order by value\" is what you actually need.\n"])</script>
1<script>self.__next_f.push([1,"29:T1c97,"])</script>
1<script>self.__next_f.push([1,"\nThe `HashSet` is a collection that uses a hash table for storage. Elements are stored by hashing and as a result, it only supports unique elements.\n\n### Key Properties of HashSet\n\nUnlike most other collections, a `HashSet` does not keep track of order.\n\nA `HashSet` is preferred when your data is unique and the order of elements is not required. HashSet performs faster for basic operations like add, remove, and contains, which typically run in constant time, O(1) — but that O(1) depends entirely on your elements having a good `hashCode()` implementation, which is worth understanding.\n\n### How it actually works\n\n`HashSet` isn't really its own data structure — it's a thin wrapper around a `HashMap\u003cE, Object\u003e`. Every element you add becomes a key in that backing map, paired with a shared dummy value (a `private static final Object PRESENT`). `add()` is really `map.put(element, PRESENT)`, `contains()` is `map.containsKey(element)`, and so on. Everything about `HashSet`'s performance and behaviour — bucket layout, resizing, treeification of long collision chains — is really `HashMap`'s behaviour. The [HashMap article](/articles/hashmap-in-java) covers that internal mechanism in more depth.\n\nThe O(1) average case assumes `hashCode()` spreads your elements evenly across buckets. A poor `hashCode()` (or none at all, falling back to `Object`'s identity-based default) that clusters everything into a handful of buckets degrades lookups toward O(n) in the worst case, since Java 8+, an over-full bucket becomes a red-black tree instead of a linked list, capping the true worst case at O(log n) — but you still lose the O(1) you were counting on.\n\n### The mutable element trap\n\nThis is the single most common `HashSet` bug: mutate an element's `hashCode()`-relevant fields *after* adding it, and the set effectively loses track of it.\n\n```java\nclass Point {\n    int x, y;\n    Point(int x, int y) { this.x = x; this.y = y; }\n\n    @Override\n    public boolean equals(Object o) {\n        if (!(o instanceof Point p)) return false;\n        return x == p.x \u0026\u0026 y == p.y;\n    }\n\n    @Override\n    public int hashCode() {\n        return Objects.hash(x, y);\n    }\n}\n\nSet\u003cPoint\u003e points = new HashSet\u003c\u003e();\nPoint p = new Point(1, 2);\npoints.add(p);\n\np.x = 99; // mutated after insertion\n\nSystem.out.println(points.contains(p)); // false — still stored in the (1,2) bucket, but now hashes to a different one\nSystem.out.println(points.contains(new Point(99, 2))); // also false — that bucket doesn't have this object\n```\n\n`p` is still physically inside the set — iterating `points` will print it — but `contains()` and `remove()` both recompute the hash from `p`'s *current* state to find the bucket to look in, and that bucket is no longer where `p` actually lives. The fix is simple: never use mutable fields in `equals()`/`hashCode()` for objects you plan to put in a `HashSet` or use as a `HashMap` key. If you need to change something about an object that's already in a set, remove it first, mutate it, then re-add it.\n\n#### Creating and initializing HashSet\n\n```java\n// Creating a HashSet using the default constructor\nHashSet\u003cString\u003e hashSet = new HashSet\u003c\u003e();\nhashSet.add(\"A\");\nhashSet.add(\"B\");\nhashSet.add(\"C\");\n\n// Creating a HashSet with an initial capacity\nHashSet\u003cString\u003e hashSetWithCapacity = new HashSet\u003c\u003e(50);\n\n// Creating a HashSet with an initial capacity and load factor\nHashSet\u003cString\u003e hashSetWithLoadFactor = new HashSet\u003c\u003e(50, 0.75f);\n\n// Creating a HashSet from another collection\nList\u003cString\u003e list = Arrays.asList(\"A\", \"B\", \"C\", \"D\");\nHashSet\u003cString\u003e hashSetFromList = new HashSet\u003c\u003e(list);\n\n// Using the factory method\nSet\u003cString\u003e set = Set.of(\"A\", \"B\", \"C\");\nHashSet\u003cString\u003e hashSetFromSet = new HashSet\u003c\u003e(set);\n```\n\n-   The load factor defines how full the hash table is allowed to get before its capacity is automatically increased.\n\n#### Iterate HashSet Elements\n\nSince a `HashSet` doesn't support indexed access, you'll need an iterator (or one of its Java 8 equivalents) to walk through its elements. Its iterator is fail-fast — it throws `ConcurrentModificationException` if the set is structurally modified any way other than through the iterator itself while you're iterating. Also note that iteration order is not the insertion order — it's whatever order the backing hash table happens to lay elements out in, which can change entirely after a resize.\n\n```java\nHashSet\u003cString\u003e hashSet = new HashSet\u003c\u003e(Arrays.asList(\"A\", \"B\", \"C\", \"D\"));\n\n// Using an enhanced for-each loop\nfor (String element : hashSet) {\n    System.out.println(element);\n}\n\n// Using an Iterator\nIterator\u003cString\u003e iterator = hashSet.iterator();\nwhile (iterator.hasNext()) {\n    String element = iterator.next();\n    System.out.println(element);\n}\n\n// Using a Java 8 Spliterator\nSpliterator\u003cString\u003e spliterator = hashSet.spliterator();\nspliterator.forEachRemaining(System.out::println);\n\n// Using the forEach() method (Java 8+)\nhashSet.forEach(element -\u003e System.out.println(element));
1\n\n// Using a Stream (Java 8+)\nhashSet.stream().forEach(System.out::println);\n```\n\n-   A `Spliterator` can be used for traversing and partitioning elements of a source. It is particularly useful for parallel processing.\n\n#### Removing Items in a HashSet\n\nThere are several methods available to remove an item from HashSet.\n\n```java\n// Remove a single element using remove()\nHashSet\u003cString\u003e hashSet = new HashSet\u003c\u003e(Arrays.asList(\"A\", \"B\", \"C\", \"D\"));\nhashSet.remove(\"B\");\n\n// Remove elements conditionally using a predicate\nHashSet\u003cString\u003e hashSet1 = new HashSet\u003c\u003e(Arrays.asList(\"A\", \"B\", \"C\", \"D\"));\nhashSet1.removeIf(s -\u003e s.startsWith(\"A\"));\n\n// Remove all elements\nHashSet\u003cString\u003e hashSet2 = new HashSet\u003c\u003e(Arrays.asList(\"A\", \"B\", \"C\", \"D\"));\nhashSet2.clear();\n\n// Remove an element using an Iterator\nHashSet\u003cString\u003e hashSet3 = new HashSet\u003c\u003e(Arrays.asList(\"A\", \"B\", \"C\", \"D\"));\nIterator\u003cString\u003e iterator = hashSet3.iterator();\nwhile (iterator.hasNext()) {\n    String element = iterator.next();\n    if (\"B\".equals(element)) {\n        iterator.remove();\n    }\n}\n\n// Retain specific elements and remove the rest\nHashSet\u003cString\u003e hashSet4 = new HashSet\u003c\u003e(Arrays.asList(\"A\", \"B\", \"C\", \"D\"));\nhashSet4.retainAll(Arrays.asList(\"A\", \"C\"));\n\n// Remove elements found in another collection\nHashSet\u003cString\u003e hashSet5 = new HashSet\u003c\u003e(Arrays.asList(\"A\", \"B\", \"C\", \"D\"));\nhashSet5.removeAll(Arrays.asList(\"A\", \"C\"));  // Removes \"A\" and \"C\" from the HashSet\n```\n\n## HashSet vs the Alternatives\n\n-   **vs `LinkedHashSet`**: same O(1) average performance, but `LinkedHashSet` also maintains insertion order at the cost of two extra reference fields per entry. If you don't specifically need predictable iteration order, plain `HashSet` uses less memory for the same data.\n-   **vs `TreeSet`**: `HashSet` is O(1) average vs `TreeSet`'s O(log n), but `TreeSet` keeps elements sorted and supports range queries (`headSet`, `tailSet`, `ceiling`, etc.). Choose based on whether you need order at all — if you don't, `HashSet` is strictly faster.\n-   **vs `Collections.newSetFromMap(new ConcurrentHashMap\u003c\u003e())`**: `HashSet` isn't thread-safe. For concurrent access, wrap it with `Collections.synchronizedSet()`, or use a set backed by `ConcurrentHashMap` for lock-striped concurrent access instead of a single lock around the whole set.\n"])</script>
1<script>self.__next_f.push([1,"2a:Tfe9,"])</script>
1<script>self.__next_f.push([1,"\nStack extends `Vector` with five operations that allow a vector to be treated as a stack. It supports last-in, first-out (LIFO) operations.\n\n![](/media/summernote/Collections-Stack.jpg)  \n\nStack allows the following operations:\n\n-   **push(item)**: Adds an item to the top of the stack.\n-   **pop()**: Removes and returns the item at the top of the stack.\n-   **peek()**: Returns the item at the top of the stack without removing it.\n-   **empty()**: Checks if the stack is empty.\n-   **search(item)**: Locates the presence of an item in the stack and it returns the distance from the top. If there are duplicate items it returns the top most occurrence.\n\nAs the `Stack` extends `Vector`, all the stack operations are synchronized and thread-safe — and it inherits `Vector`'s doubling growth strategy and non-fail-fast `Enumeration`, covered in the [Vector article](/articles/vector-in-java).\n\nOne detail worth knowing: `push()` and `pop()` operate on the *end* of the underlying array, not the beginning. `push()` is really just `addElement()`, and `pop()` removes the last element — so both are O(1) amortized, not O(n). If `push`/`pop` worked at index 0 instead, every operation would require shifting the entire array.\n\n`search(item)` returns a **1-based** distance from the top, not a zero-based index — `search()` returning `1` means \"the top element,\" not \"index 1.\"\n\nTake a text editor's undo/redo feature as an example — you need to track every typing action in order, and a `Stack` is a natural fit for that.\n\n```java\npublic class TextEditor {\n    private final Stack\u003cString\u003e textStack = new Stack\u003c\u003e();\n    private final Stack\u003cString\u003e undoStack = new Stack\u003c\u003e();\n\n    public void type(String text) {\n        textStack.push(text);\n        undoStack.clear();\n    }\n\n    public void undo() {\n        if (!textStack.isEmpty()) {\n            String lastText = textStack.pop();\n            undoStack.push(lastText);\n        } else {\n            System.out.println(\"Nothing to undo.\");\n        }\n    }\n\n    public void redo() {\n        if (!undoStack.isEmpty()) {\n            String lastUndoText = undoStack.pop();\n            textStack.push(lastUndoText);\n        } else {\n            System.out.println(\"Nothing to redo.\");\n        }\n    }\n\n    public void display() {\n        System.out.println(\"Current Text: \" + String.join(\"\", textStack));\n    }\n\n    public static void main(String[] args) {\n        TextEditor editor = new TextEditor();\n        editor.type(\"Hello, \");\n        editor.type(\"world!\");\n        editor.display();\n\n        editor.undo();\n        editor.display();\n\n        editor.redo();\n        editor.display();\n\n        editor.undo();\n        editor.undo();\n        editor.display();\n\n        editor.redo();\n        editor.display();\n    }\n}\n```\n\n## Why the JDK Recommends Against Stack\n\nThe `Stack` Javadoc says outright: prefer `Deque` for LIFO operations, implemented by `ArrayDeque`. Two reasons:\n\n-   **`Stack extends Vector`**, which means it inherits `Vector`'s entire `List` API. Nothing stops you from calling `stack.add(0, item)` or `stack.remove(0)` on a `Stack` and silently breaking the LIFO ordering the class exists to enforce — the type system won't catch it.\n-   `Stack` inherits `Vector`'s synchronized-on-every-method behaviour and doubling growth strategy, both of which cost you in the (far more common) single-threaded case where you don't need the synchronization at all.\n\n`ArrayDeque` doesn't have either problem: it isn't a `List`, so it can't expose operations that would break stack semantics, and it's unsynchronized by default with array-backed storage that resizes more efficiently. The `textStack`/`undoStack` fields in the example above translate directly:\n\n```java\nprivate final Deque\u003cString\u003e textStack = new ArrayDeque\u003c\u003e();\nprivate final Deque\u003cString\u003e undoStack = new ArrayDeque\u003c\u003e();
1\n// push(), pop(), isEmpty() are all the same method names on Deque\n```\n\nThe only thing you lose is `search()` — `Deque` has no equivalent, since finding an item's position isn't really a stack operation to begin with.\n"])</script>
1<script>self.__next_f.push([1,"2b:T10f9,"])</script>
1<script>self.__next_f.push([1,"\nVector is a legacy implementation of a list added to Java since version 1.0. It was later moved to the Java Collections Framework and retrofitted to implement the `List` interface.\n\n`Vector` is synchronized — every method on the class is synchronized, so only one thread can access it at a time.\n\n`Vector` implements the `List` interface, and it also exposes `iterator()`, `listIterator()`, and `elements()` methods, which return an `Iterator`, `ListIterator`, and `Enumeration` respectively for traversing its elements.\n\n### Growth strategy: doubling, not 1.5x\n\n`Vector` is array-backed, same as `ArrayList`, but it resizes differently. Unless you give it a `capacityIncrement` (the third constructor's second argument), a full `Vector` **doubles** its capacity on the next `add()`. `ArrayList`, by contrast, grows by roughly 1.5x. Neither is \"correct\" — doubling wastes more memory on average but resizes less often; 1.5x wastes less but resizes more.\n\nIf you do supply a `capacityIncrement`, growth becomes linear instead of geometric — `vector3` above grows by a fixed 5 slots every time it fills up, not by a multiple of its current size. That's rarely what you want for an unbounded-growth collection; it's a relic from when Java expected you to hand-tune this.\n\n### Enumeration isn't fail-fast\n\n`iterator()` and `listIterator()` are fail-fast, same as every other `List` in this course. `elements()` is not — the `Enumeration` it returns has no `modCount` check at all, because `Enumeration` predates the fail-fast mechanism entirely (it's a Java 1.0 type, older than the Collections Framework itself). Mutating the `Vector` while enumerating won't throw `ConcurrentModificationException` — you'll just get undefined behaviour, possibly a stale view or an `ArrayIndexOutOfBoundsException`. Prefer `iterator()` unless you have legacy code that specifically needs `Enumeration`.\n\n### Creating and initializing Vector\n\n```java\n//Using default constructor\nVector\u003cString\u003e vector1 = new Vector\u003c\u003e();\nvector1.add(\"One\");\nvector1.add(\"Two\");\nvector1.add(\"Three\");\n\n// Initial capacity of 20\nVector\u003cString\u003e vector2 = new Vector\u003c\u003e(20);\nvector2.add(\"One\");\nvector2.add(\"Two\");\nvector2.add(\"Three\");\n\n// Initial capacity of 20, capacity increment of 5\nVector\u003cString\u003e vector3 = new Vector\u003c\u003e(20, 5);\nvector3.add(\"One\");\nvector3.add(\"Two\");\nvector3.add(\"Three\");\n\n//Creating vector from another collection\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"One\");\nlist.add(\"Two\");\nlist.add(\"Three\");\nVector\u003cString\u003e vector4 = new Vector\u003c\u003e(list);\n```\n\n### Iterate Items in Vector\n\nVectors can be iterated using for loop, enhanced for loop, Java 8 `forEach`, `Iterator`, `ListIterator` or using `Enumeration`.\n\n```java\n//for loop\nfor (int i = 0; i \u003c vector1.size(); i++) {\n    System.out.println(vector1.get(i));\n}\n\n// Enhanced for Loop\nfor (String element: vector1) {\n     System.out.println(element);\n}\n\n//using iterator\nIterator\u003cString\u003e iterator = vector1.iterator();\nwhile (iterator.hasNext()) {\n    System.out.println(iterator.next());\n}\n\n// using a ListIterator\nListIterator\u003cString\u003e listIterator = vector1.listIterator();\nwhile (listIterator.hasNext()) {\n    System.out.println(listIterator.next());\n}\n\n// Using Enumeration\nEnumeration\u003cString\u003e enumeration = vector1.elements();\nwhile (enumeration.hasMoreElements()) {\n    System.out.println(enumeration.nextElement());\n}\n\n//Using Java 8 forEach\nvector1.forEach(element -\u003e {\n    System.out.println(element);\n});\n```\n\n## Vector vs the Alternatives\n\nThere's no scenario in modern Java where `Vector` is the best choice — it's kept around for backward compatibility with pre-Collections-Framework code.\n\n-   **vs `ArrayList` + `Collections.synchronizedList()`**: gives you the same synchronization guarantee, but only where you actually need it, instead of paying the lock cost on every single method call — including in single-threaded code that happens to use a `Vector` out of habit.\n-   **vs `CopyOnWriteArrayList`**: if the real goal is safe concurrent reads with occasional writes, `CopyOnWriteArrayList` gets you there without any locking on the read path at all.\n-   **vs `ArrayDeque`**: if you're using `Vector` for its `Stack`-like methods (`addElement`/`firstElement`), see the [Stack article](/articles/stack-in-java) — `ArrayDeque` is the modern replacement for that too.\n"])</script>
1<script>self.__next_f.push([1,"2c:T10fc,"])</script>
1<script>self.__next_f.push([1,"\nThe `CopyOnWriteArrayList` is the thread-safe implementation of the `List` interface. CopyOnWriteArrayList is very useful when we want to iterate over a list in a thread-safe way without explicit synchronization.\n\n### Key Properties of CopyOnWriteArrayList\n\nThe trade-off is speed. It's noticeably slower than `ArrayList` when you're making frequent modifications, since every write copies the entire backing array.\n\n### How it actually works\n\nThe name is literal: on every mutating call (`add`, `set`, `remove`), `CopyOnWriteArrayList` takes the current backing array, copies it into a new array of the required size via `Arrays.copyOf`, applies the change, and swaps in the new array under a lock. The array reference itself is `volatile`, so readers always see a consistent, fully-formed array — never a partially updated one — without needing any locking of their own.\n\nThat's also why its iterator is **fail-safe** rather than fail-fast: `iterator()` just captures whatever array reference was current at that moment and walks it directly. If another thread mutates the list afterward, that thread gets its own new array — your iterator keeps reading the old one. No `ConcurrentModificationException`, but also no visibility into changes made after you started iterating.\n\nHere's an example that shows why you'd reach for it in the first place:\n\n```java\npublic class ConcurrentModificationDemo {\n\n    public static void main(String[] args) {\n        List\u003cString\u003e list = new ArrayList\u003c\u003e();\n        list.add(\"Apple\");\n        list.add(\"Banana\");\n        list.add(\"Guava\");\n        list.add(\"Grapes\");\n\n        for (String value: list) {\n            if (value.equals(\"Banana\")) {\n                list.remove(\"Grapes\");  // ConcurrentModificationException\n            }\n        }\n        System.out.println(list);\n    }\n}\n```\n\nNotice that in the above program, we're modifying the list while iterating over it, so the application throws a `ConcurrentModificationException`.\n\n```text\nException in thread \"main\" java.util.ConcurrentModificationException\n    at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)\n    at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)\n    at ConcurrentModificationDemo.main(ConcurrentModificationDemo.java:11)\n```\n\nTo avoid this exception, we can either call the `remove()` method on an iterator or use `CopyOnWriteArrayList`.\n\nThe `CopyOnWriteArrayList` class makes a fresh copy of the underlying array while performing mutative operations (such as `add`, `set`, and `remove`).\n\n```java\npublic class CopyOnWriteArrayListDemo {\n\n    public static void main(String[] args) {\n        List\u003cString\u003e list = new CopyOnWriteArrayList\u003c\u003e();\n        list.add(\"Apple\");\n        list.add(\"Banana\");\n        list.add(\"Guava\");\n        list.add(\"Grapes\");\n\n        for (String value : list) {\n            System.out.println(\"Visiting: \" + value);\n            if (value.equals(\"Banana\")) {\n                list.remove(\"Grapes\");\n            }\n        }\n        System.out.println(\"Final list: \" + list);\n    }\n}\n```\n\n**Output:**\n\n```text\nVisiting: Apple\nVisiting: Banana\nVisiting: Guava\nVisiting: Grapes\nFinal list: [Apple, Banana, Guava]\n```\n\nNotice that the loop still visits `Grapes` even though it was removed mid-iteration — the iterator is walking the snapshot array captured when the loop started. The live list, printed afterward, correctly reflects the removal.\n\n## CopyOnWriteArrayList vs the Alternatives\n\n-   **vs `Collections.synchronizedList(new ArrayList\u003c\u003e())`**: `synchronizedList` locks on every call, including reads, and its iterator is still fail-fast — you have to wrap iteration in a manual `synchronized` block yourself to avoid `ConcurrentModificationException`. `CopyOnWriteArrayList` never locks readers and never throws during iteration, at the cost of copying the array on every write.\n-   **vs plain `ArrayList`**: only reach for `CopyOnWriteArrayList` when the list is actually shared across threads. In single-threaded code it's strictly worse — same memory profile as `ArrayList` plus the overhead of copying on every mutation.\n-   **Typical use case**: listener/observer lists, where registrations are rare but iteration (firing an event to every listener) happens constantly — exactly the read-heavy, write-rare pattern this class is built for.\n"])</script>
1<script>self.__next_f.push([1,"2d:T1cc8,"])</script>
1<script>self.__next_f.push([1,"\nWhile an `ArrayList` uses a normal array to store elements, a `LinkedList` uses a doubly linked list to store elements. It implements both the `List` and `Queue` interfaces.\n\n## Key Properties of LinkedList\n\nEach element inside a `LinkedList` is called a node. A node holds the data along with references to both the previous and next node — that's what makes it doubly linked.\n\n![](/media/summernote/linkedlist.jpg)  \n\nLinkedList is preferred when the list size is unknown beforehand and the ability to grow or shrink dynamically is important.\n\nThe `LinkedList` in Java is not synchronized by default. If multiple threads attempt to modify a `LinkedList` concurrently, it must be synchronized externally to prevent unexpected behaviour.\n\n### \"Fast middle inserts\" is a half-truth\n\nA common claim is that `LinkedList` is efficient for inserting or removing in the middle. That's only true if you already hold a `ListIterator` positioned at that spot — the actual splice is O(1). But `linkedList.add(index, value)` and `linkedList.remove(index)` still have to *walk the list node by node to find that index first*, which is O(n). `LinkedList` does optimize the walk itself — `node(index)` traverses from the head if `index \u003c size / 2`, and from the tail otherwise — but that only halves the constant, it doesn't change the complexity.\n\nIn practice, `get(index)` is also O(n) for the same reason, which rules `LinkedList` out for anything that needs random access.\n\n### Memory cost\n\nEach element costs more than it looks like it should. Where `ArrayList` stores a bare reference per slot in a contiguous array, every `LinkedList` element is wrapped in its own `Node` object holding the value plus `prev`/`next` references — roughly 3–4x the memory per element once you count object headers. That overhead, plus the poor cache locality of chasing pointers scattered across the heap, is why `LinkedList` tends to lose real-world benchmarks against `ArrayList` and `ArrayDeque` even in scenarios that look like its strong suit on paper.\n\n### Creating and Initialising LinkedList\n\nLet us look at how we create and add elements to `LinkedList`.\n\n```java\n// Creating LinkedList using the default constructor\nList\u003cString\u003e linkedList = new LinkedList\u003c\u003e();\nlinkedList.add(\"Apple\");\nlinkedList.add(\"Banana\");\nlinkedList.add(\"Orange\");\n\n// Adding elements at a specific position\nlinkedList.add(1, \"Guava\");\n\n// Adding elements to the beginning\nlinkedList.addFirst(\"Orange\");\n\n// Adding an element to the end\nlinkedList.addLast(\"Orange\");\n\n// Using ListIterator to add items to a specific position\nListIterator\u003cString\u003e iterator = linkedList.listIterator();\niterator.next();\niterator.add(\"Banana\");\n```\n\n```java\n// Creating a LinkedList from another collection\nList\u003cString\u003e arrayList = Arrays.asList(\"Apple\", \"Banana\", \"Orange\");\nList\u003cString\u003e linkedListFromCollection = new LinkedList\u003c\u003e(arrayList);\n\n// Using the offer method\nQueue\u003cString\u003e queue = new LinkedList\u003c\u003e();\nqueue.offer(\"Apple\");\nqueue.offer(\"Banana\");\nqueue.offer(\"Orange\");\n```\n\n-   The `add()` method inserts elements at the end of the list.\n-   The `offer()` methods come from the `Deque` interface and can be used to add elements to a `LinkedList`. They return `true` if the element was added successfully, and `false` otherwise.\n\n### Iterate over a LinkedList\n\n```java\n// Using a For-Each Loop\nfor (String fruit: linkedList) {\n    System.out.println(fruit);\n}\n\n// Using a Traditional For Loop\nfor (int i = 0; i \u003c linkedList.size(); i++) {\n    System.out.println(linkedList.get(i));\n}\n\n//Using an Iterator\nIterator\u003cString\u003e iterator = linkedList.iterator();\nwhile (iterator.hasNext()) {\n    System.out.println(iterator.next());\n}\n\n//Using a ListIterator\nListIterator\u003cString\u003e listIterator = linkedList.listIterator();\nwhile (listIterator.hasNext()) {\n    System.out.println(listIterator.next());\n}\n\n// Backward iteration\nwhile (listIterator.hasPrevious()) {\n    System.out.println(listIterator.previous());\n}\n\n// Using Java 8 Stream API forEach method\nlinkedList.forEach(fruit -\u003e System.out.println(fruit));\n\n// Using Java 8 Stream API streams\nlinkedList.stream().forEac
1h(fruit -\u003e System.out.println(fruit));\n```\n\n### Removing an Item in a LinkedList\n\n```java\n// Removes the element at index 1 (Banana)\nlinkedList.remove(1);\n\n// Removes the first occurrence of \"Banana\"\nlinkedList.remove(\"Banana\");\n\n// Removes the first element (Apple)\nlinkedList.removeFirst();\n\n// Removes the last element (Orange)\nlinkedList.removeLast();\n\n// Removing All Occurrences of a Collection\nList\u003cString\u003e itemsToRemove = Arrays.asList(\"Banana\", \"Orange\");\nlinkedList.removeAll(itemsToRemove);\n\n// Remove elements based on a condition\nlinkedList.removeIf(fruit -\u003e fruit.startsWith(\"B\"));\n\n// Removes all elements from the list\nlinkedList.clear();\n```\n\nGet the size of a LinkedList\n\n```java\nlinkedList.size();\n```\n\nCheck if an item exists in a LinkedList\n\n```java\nlinkedList.contains(\"Banana\");\n```\n\n### Example\n\nHere's a simple playlist built on `LinkedList` where we can add, remove, and display songs.\n\n```java\npublic record Song(String title, String artist) {\n}\n\npublic class MusicPlaylist {\n    private final LinkedList\u003cSong\u003e playlist;\n\n    public MusicPlaylist() {\n        playlist = new LinkedList\u003c\u003e();\n    }\n\n    public void addSong(Song song) {\n        playlist.add(song);\n    }\n\n    public void removeSong(Song song) {\n        playlist.remove(song);\n    }\n\n    public void displayPlaylist() {\n        for (int i = 0; i \u003c playlist.size(); i++) {\n            System.out.println((i + 1) + \". \" + playlist.get(i));\n        }\n    }\n\n    public static void main(String[] args) {\n        MusicPlaylist myPlaylist = new MusicPlaylist();\n\n        Song song1 = new Song(\"Bohemian Rhapsody\", \"Queen\");\n        Song song2 = new Song(\"Imagine\", \"John Lennon\");\n        Song song3 = new Song(\"Hotel California\", \"Eagles\");\n\n        myPlaylist.addSong(song1);\n        myPlaylist.addSong(song2);\n        myPlaylist.addSong(song3);\n\n        System.out.println(\"My Playlist:\");\n        myPlaylist.displayPlaylist();\n\n        System.out.println(\"Removing 'Imagine' from playlist.\");\n        myPlaylist.removeSong(song2);\n\n        System.out.println(\"Updated Playlist:\");\n        myPlaylist.displayPlaylist();\n    }\n}\n```\n\n### Iterating and removing safely\n\n`LinkedList`'s iterator is fail-fast, same as `ArrayList` — it tracks `modCount` and throws `ConcurrentModificationException` if you mutate the list through anything other than the iterator itself while iterating. Use `Iterator.remove()`, `listIterator().remove()`, or `removeIf()` instead of calling `linkedList.remove(...)` inside a for-each loop.\n\n## LinkedList vs the Alternatives\n\n-   **vs `ArrayList`**: `ArrayList` beats `LinkedList` on nearly every practical metric — cache locality, memory per element, and O(1) indexed access. `LinkedList`'s theoretical edge (O(1) splice) only materializes when you're already holding a `ListIterator` at the insertion point.\n-   **vs `ArrayDeque`**: if you're using `LinkedList` purely as a `Queue` or `Deque` (via `offer`/`poll`/`push`/`pop`), `ArrayDeque` is faster and lighter for that same job — no per-node allocation, better cache behaviour, and the JDK documentation explicitly recommends it over `LinkedList` for that use case. `LinkedList` only wins if you specifically need `null` elements, which `ArrayDeque` disallows.\n"])</script>
1<script>self.__next_f.push([1,"2e:T261d,"])</script>
1<script>self.__next_f.push([1,"\nAn `ArrayList` is similar to a regular array except that the size is dynamically adjusted as the number of items in the collection changes. Arrays have a fixed size that cannot change. But with `ArrayList`, you don't need to worry about the size.\n\n## Key Properties of ArrayList\n\nThe initial capacity of `ArrayList` is **10** — since Java 8, the backing array isn't actually allocated until the first element is added, so an empty `ArrayList` costs almost nothing.\n\nArrayList is best suited when we have read-heavy operations. However, if you're required to insert or delete elements in the middle of the collection, `ArrayList` is not preferred.\n\nArrayList is not synchronized (not thread-safe).\n\n| Operation | Time Complexity |\n| --- | --- |\n| Access item | O(1) time complexity |\n| Adding items | O(1) on average, but can be O(n) when resizing is needed |\n| Removing items | O(n) because it may require shifting elements. |\n\n### How resizing actually works\n\n`ArrayList` is backed by a plain `Object[]`. When `add()` finds the array full, it doesn't double it — it grows to `oldCapacity + (oldCapacity \u003e\u003e 1)`, roughly **1.5x**. That's a deliberate trade-off against wasted memory; `Vector` doubles by default instead, which we'll cover in the [Vector](/articles/vector-in-java) article.\n\nEvery resize allocates a new array and copies every existing element into it with `Arrays.copyOf`. If you already know roughly how many elements you'll store, pass that as the initial capacity during intiailization (`new ArrayList\u003c\u003e(1000)`) to skip the repeated copying entirely.\n\n### Mutation while iterating\n\n`ArrayList`'s iterator is fail-fast: it checks an internal `modCount` on every `next()` call and throws `ConcurrentModificationException` if the list was structurally changed by anything other than the iterator itself. This means:\n\n```java\nfor (String fruit : list1) {\n    if (fruit.equals(\"Banana\")) {\n        list1.remove(fruit); // throws ConcurrentModificationException\n    }\n}\n```\n\nUse `Iterator.remove()` or `list1.removeIf(...)` instead — both update `modCount` in a way the iterator expects, so no exception is thrown.\n\n## Creating and initializing ArrayList\n\nLet's look at how to use an `ArrayList`.\n\n```java\n//Using the Default Constructor\nList\u003cString\u003e list1 = new ArrayList\u003c\u003e();\nlist1.add(\"Apple\");\nlist1.add(\"Banana\");\n\n// Using Constructor with Initial Capacity\nList\u003cString\u003e list2 = new ArrayList\u003c\u003e(20);\nlist2.add(\"Apple\");\nlist2.add(\"Banana\");\n\n//Initializing array list using the anonymous inner class method\nList\u003cString\u003e list3 = new ArrayList\u003cString\u003e() {{\n    add(\"Apple\");\n    add(\"Banana\");\n    add(\"Orange\");\n}};\n\n// fixed-size list from the elements of another collection\nList\u003cString\u003e list4 = Arrays.asList(\"Apple\", \"Banana\", \"Orange\");\nList\u003cString\u003e list5 = new ArrayList\u003c\u003e(list4);\n\n// Using Arrays.asList method\nList\u003cString\u003e list6 = new ArrayList\u003c\u003e(Arrays.asList(\"Apple\", \"Banana\", \"Orange\"));\n\n// Using Collections.addAll method\nList\u003cString\u003e list7 = new ArrayList\u003c\u003e();\nCollections.addAll(list7, \"Apple\", \"Banana\", \"Orange\");\n\n// Using Java 8 streams and collectors\nList\u003cString\u003e list8 = Stream.of(\"Apple\", \"Banana\", \"Orange\")\n        .collect(Collectors.toCollection(ArrayList::new));\n```\n\nItems inside an `ArrayList` can be accessed using their index.\n\n```java\nlist1.get(1);\n```\n\nItems inside an `ArrayList` can be changed using the `set()` method, which takes the index and the new value. This replaces the element at the specified position.\n\n```java\nlist1.set(1, \"Guava\");\n```\n\nTo find out how many elements an `ArrayList` holds, use the `size()` method.\n\n```java\nlist1.size();\n```\n\nTo check whether an item exists in an `ArrayList`, use the `contains()` method. It returns `true` or `false`.\n\n```java\nlist1.contains(\"Banana\");\n```\n\n## Iterate ArrayList Items\n\nThere are multiple ways we can iterate an ArrayList.\n\n```java\n// Iterate using enhanced for loop\nfor (String item:list1) {\n    System.out.println(item);\n}\n\n// Iterate using a traditional for loop\nfor (int i = 0; i \u003c list1.size();
1 i++) {\n    System.out.println(list1.get(i));\n}\n\n// Using an Iterator\nIterator\u003cString\u003e iterator = list1.iterator();\nwhile (iterator.hasNext()) {\n    System.out.println(iterator.next());\n}\n\n// Using ListIterator\nListIterator\u003cString\u003e listIterator = list1.listIterator();\nwhile (listIterator.hasNext()) {\n    System.out.println(listIterator.next());\n}\n\n// Using a Java8 Stream and lambda expression\nlist1.stream().forEach(item -\u003e System.out.println(item));\n\n// Using a Java8 forEach method\nlist1.forEach(item -\u003e System.out.println(item));\n```\n\n_Note_\n\nThe Iterator interface provides methods to iterate a collection. The iterator generally traverse elements one by one in a forward direction. However, the `ListIterator` is specific to lists. It offers bidirectional traversal and modification.\n\n## Removing Item in ArrayList\n\nWe can remove an item from an `ArrayList` using the `remove()` method, either by index or by value.\n\n```java\n// Removes the element at index 1\nlist1.remove(1);\n\n// Removes the first occurrence of \"Banana\"\nlist1.remove(\"Banana\");\n\n// Removes all items found in another collection\nList\u003cString\u003e toRemove = Arrays.asList(\"Banana\", \"Orange\");\nlist1.removeAll(toRemove);\n\n// Removes elements matching a condition\nlist1.removeIf(fruit -\u003e fruit.startsWith(\"B\"));\n\n// Removes all elements from the list\nlist1.clear();\n```\n\n## Creating Immutable List in Java\n\nTo create an immutable list using the `List.of()` factory method.\n\n```java\npublic class ImmutableList {\n    public static void main(String[] args) {\n        List\u003cString\u003e immutableList = List.of(\"A\", \"B\", \"C\");\n        System.out.println(immutableList);\n\n        immutableList.add(\"D\"); // throws UnsupportedOperationException\n        System.out.println(immutableList);\n    }\n}\n```\n\nWe can also create an unmodifiable view of the list using the `Collections.unmodifiableList()` method. If you modify the returned list, whether directly or via its iterator will result in an `UnsupportedOperationException`.\n\n```java\npublic class UnmodifiableListExample {\n    public static void main(String[] args) {\n        List\u003cString\u003e list = new ArrayList\u003c\u003e();\n        list.add(\"A\");\n        list.add(\"B\");\n        list.add(\"C\");\n\n        List\u003cString\u003e unmodifiableList = Collections.unmodifiableList(list);\n        System.out.println(unmodifiableList);\n        unmodifiableList.add(\"D\"); // throws UnsupportedOperationException\n        System.out.println(unmodifiableList);\n    }\n}\n```\n\n## ArrayList is not Synchronized\n\nArrayList is not synchronized. What it means, is when multiple threads attempt to modify the same list simultaneously, it can lead to unpredictable behaviour.\n\nLet us look into the following program:\n\n```java\npublic class NonSynchronizedArrayList {\n    public static void main(String[] args) {\n        List\u003cInteger\u003e arrayList = new ArrayList\u003c\u003e();\n\n        // Create a runnable task that adds elements to the list\n        Runnable addItemsTask = () -\u003e {\n            for (int i = 0; i \u003c 1000; i++) {\n                arrayList.add(i);\n            }\n        };\n\n        // Create multiple threads that will run the addItemsTask\n        Thread thread1 = new Thread(addItemsTask);\n        thread1.start();\n        Thread thread2 = new Thread(addItemsTask);\n        thread2.start();\n        try {\n            thread1.join();\n            thread2.join();\n        } catch (InterruptedException e) {\n            System.out.println(e.getMessage());\n        }\n        System.out.println(\"Size of List: \" + arrayList.size());\n    }\n}\n```\n\nIn this example, you expect the size of the list to be 2000, but it will be less than 2000. This is because multiple threads are interfering with each other which leads to corrupted data.\n\nTo make the `ArrayList` thread-safe, we can use `Collections.synchronizedList()` method. The `synchronizedList()` method returns a synchronized (thread-safe) list backed by the specified list.\n\nTo guarantee serial access, all access to the backing list must be accomplished through the returned list. The above program can be written as follows:\n\n```java\npublic class SynchronizedArrayList {\n    public static void main(String[] args) {\n        List\u003cInteger\u003e arrayList = Collections.synchronizedList(new ArrayList\u003c\u003e());\n\n        // Create a runnable task that adds elements to the list\n        Runnable addItemsTask = () -\u003e {\n            for (int i = 0; i \u003c 1000;
1 i++) {\n                arrayList.add(i);\n            }\n        };\n\n        // Create multiple threads that will run the addItemsTask\n        Thread thread1 = new Thread(addItemsTask);\n        thread1.start();\n\n        Thread thread2 = new Thread(addItemsTask);\n        thread2.start();\n        try {\n            thread1.join();\n            thread2.join();\n        } catch (InterruptedException e) {\n            System.out.println(e.getMessage());\n        }\n        System.out.println(\"Size of List: \" + arrayList.size());\n    }\n}\n```\n\n## ArrayList vs the Alternatives\n\n-   **vs `LinkedList`**: `ArrayList` wins for random access (`get(i)` is O(1) vs O(n)) and for cache locality — elements sit contiguously in memory, so iteration is faster in practice even where both are O(n) on paper. `LinkedList` only pulls ahead when you're inserting or removing at a position you already hold via a `ListIterator`, since that's O(1) with no shifting.\n-   **vs `ArrayDeque`**: if you only ever add/remove at the ends, `ArrayDeque` is faster and lighter than `ArrayList` for that access pattern — no shifting of interior elements, and it doesn't need to keep the array fully packed.\n-   **vs `CopyOnWriteArrayList`**: reach for `ArrayList` in single-threaded code or when you'll synchronize externally yourself. `CopyOnWriteArrayList` only pays off when reads vastly outnumber writes.\n"])</script>
1<script>self.__next_f.push([1,"2f:Tf91,"])</script>
1<script>self.__next_f.push([1,"\nThe static keyword in Java can be applied to a class, a member or a method. In this tutorial, we will explore how the members, methods and classes behave in Java when they are declared static.\n\n## Static Variables and Methods\n\nVariables and methods declared with `static` keywords are associated with the class rather than with any specific instance of the class. This means all instances of the class share the same copy of the static variable.\n\nStatic variables are allocated memory only once when the class is loaded into memory and before any instance is created. They exist throughout the entire lifecycle of the program.\n\nFor accessing the static members, you don't need to create an instance and they can be accessed directly using the name of the class. However, it is possible to access them through an instance.\n\n```java\npublic class Vehicle {\n    protected static String brand;\n\n    public static String getBrand() {\n        return brand;\n    }\n\n    public static void setBrand(String brand) {\n        Vehicle.brand = brand;\n    }\n}\n\npublic class Car extends Vehicle {\n    private String model;\n\n    public Car(String model) {\n        this.model = model;\n    }\n\n    public String getModel() {\n        return model;\n    }\n}\n\npublic class Bus extends Vehicle {\n    private int seatingCapacity;\n\n    public Bus(int seatingCapacity) {\n        this.seatingCapacity = seatingCapacity;\n    }\n\n    public int getSeatingCapacity() {\n        return seatingCapacity;\n    }\n}\n```\n\nIn the above example, the variable `brand` is declared as static, which means it will be shared among all instances of the `Vehicle` class.\n\n![](/media/summernote/static-class_diagram.jpg)  \n\nWhen the program starts, the `Car` class is loaded into the Method Area and the static variable `brand` is initialized.\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        Vehicle.setBrand(\"Toyota\");\n\n        Car car = new Car(\"Camry\");\n        System.out.println(\"Car brand: \" + Vehicle.getBrand());\n        System.out.println(\"Car model: \" + car.getModel());\n\n        Bus bus = new Bus(50);\n        System.out.println(\"Bus brand: \" + Vehicle.getBrand());\n        System.out.println(\"Bus seating capacity: \" + bus.getSeatingCapacity());\n    }\n}\n```\n\n## Static Classes\n\nIn Java, you can declare a class as `static` but they can only be defined as inner class. A static class cannot be a top-level class.\n\nA static class can have static variables, static methods and instance members, just like a regular top-level class.\n\nA static nested class is associated with its outer class, but it doesn't have direct access to the instance variables and methods of the outer class. Static classes can be instantiated without needing an instance of the outer class.\n\n```java\npublic class OuterClass {\n    private String var1;\n    private static String staticOuterField = \"Static Outer Field\";\n\n    public String getVar1(){\n        return var1;\n    }\n\n    public static class StaticNestedClass {\n        public void printMessage() {\n            System.out.println(staticOuterField);\n        }\n    }\n}\n\npublic class Main {\n    public static void main(String[] args) {\n        OuterClass.StaticNestedClass obj1 = new OuterClass.StaticNestedClass();\n        obj1.printMessage();\n    }\n}\n```\n\nIn the above example, we are accessing `staticOuterField` within the `StaticNestedClass` static `printMessage()` method, but we cannot directly access it using the instance of `StaticNestedClass`.\n\nWe cannot also directly access the `getVar1()` method by using the instance of `StaticNestedClass`.\\`\\`\n\nThe static inner class is useful for logically grouping classes or encapsulating functionality closely related to the outer class.\n\nFor example, let's say you are developing an application that needs access to data from a database. You can use a static inner class to encapsulate the logic for managing the database connections, while your outer class can be responsible for database queries. # Static\n"])</script>
1<script>self.__next_f.push([1,"30:T51d5,"])</script>
1<script>self.__next_f.push([1,"\n## Introduction to Spring Batch\n\nSpring Batch is a powerful module of the Spring framework that provides out-of-the-box implementation for batch processing tasks.\n\nIt is used in scenarios where data needs to be processed in multiple batches, for example, generating daily reports, periodic import of data into a database, or for any complex calculations and transformations of your data.\n\nA typical batch-processing application involves the following steps:\n\n![](/media/summernote/spring-batch-process-flow.png)  \n\nAll the above steps can be achieved without using the spring batch. However, the spring batch provides the following benefits which makes a strong case for the framework.\n\n1.  You do not need to reinvent the wheel\n2.  Seamless integration with Spring ecosystem\n3.  Chunk-based processing\n4.  Includes I/O capabilities such as support for a wide range of data sources and targets, including databases, XML, JSON, and flat files.\n5.  Detailed monitoring and logging: Allows tracking of job and step execution, making it easier to understand the status and performance of batch jobs.\n\nSpring Batch provides two different ways to implement a job. We can process data using **Tasklets** and **Chunks**.\n\n-   A **Tasklet** is a single task within a step. The `Tasklet` interface defines a single method `execute()`, called once during the step execution.\n-   A **Chunk-based** approach is more suitable for processing large datasets where data can be read, processed, and written in smaller, manageable chunks. This is typically used for reading data from a database or a file and processing it record by record. The chunk model is built around three main components; `Reader`, `Writer` and `Processor`\n\n## Spring Boot Batch Chunk Processing\n\nThe key components of a Spring boot batch application include: - Job - Step - Readers, Writers, Processors - Job Repository - Job Launcher\n\nThe primary components of the Spring Batch and overall process flow are shown in the figure below.\n\n![](/media/summernote/spring-batch-chunk-processing.png)  \n\n**JobLauncher**: The `JobLauncher` is an interface that represents the component responsible for running the jobs. It takes care of receiving job parameters and launching a job with those parameters. It's typically used to start a job from different triggers such as an application event, a REST API call, or from scheduler.\n\n**Job**: A `Job` in a Spring Batch is an entity that encapsulates an entire batch process and is defined by a series of steps.\n\n**Step**: A single job may have one or more steps, where each step typically involves reading data, processing it, and writing the processed data to the output source.\n\n**ItemReader**: The `ItemReader` is responsible for reading data from different sources such as databases or files. The ItemReader has a `read()` method, every time this method is invoked, it will return one item. If there are no more items to read, it returns `null` to indicate the end of the data input.\n\nThe `FlatFileItemReader` can be used for reading data from flat files (like CSV), `JdbcCursorItemReader` for reading from databases using a JDBC cursor, and `JpaPagingItemReader` can be used for reading database records using JPA pagination.\n\n**ItemProcessor** The `ItemProcessor` is completely optional. It is used to validate, transform, or filter the items before passing them to the `ItemWriter`.\n\n**ItemWriter** The `ItemWriter` takes processed items and writes them to a database or a file. The `FlatFileItemWriter` can be used for writing data to flat files, `JdbcBatchItemWriter` for batching database operations through JDBC, and `JpaItemWriter` for handling database operations using JPA.\n\n**Job Repository**: The `JobRepository` does all the hard work such as recording the status of jobs in a database. It keeps track of which jobs are running, which have been completed, and if a job fails, what step it failed at. This is critical for jobs that need to be restarted after a failure, ensuring that the job can pick up where it left off.\n\n## Load CSV Data to Postgres SQL using Spring Batch\n\nThis example uses chunk-based processing for reading CSV files, processing it and then storing it in Postgres SQL. For managing the database migrations we will use Flyway.\n\nUse Spring Initializr to bootstrap a spring boot project by selecting the required dependencies. This example uses Java 17 and Spring Boot 3.2.4 and has the following dependencies.\n\n-   Spring Batch\n-   Spring Data JPA\n-   PostgreSQL Driver\n-   Lombok - completely optional for reducing boilerplate code.\n-   [Flyway](https://stacktips.com/articles/using-flyway-for-database-migration-in-spring-boot) - Database migration\n\n```groovy\ndependencies {\n    implementation 'org.springframework.boot:spring-boot-starter-batch'\n    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'\n    compileOnly 'org.projectlombok:lombok'\n    annotationProcessor 'org.projectlombok:lombok'\n\n    runtimeOnly 'org.postgresql:postgresql'\n    implementation 'org.flywaydb:flyway-core:10.10.0'\n    runtimeOnly 'org.flywaydb:flyway-database-postgresql:10.10.0'\n\n    testImplementation 'org.springframework.boot:spring-boot-starter-test'\n    testImplementation 'org.springframework.batch:spring-batch-test'\n}\n```\n\n### Configuring Database Properties\n\nLet us now configure the data source and batch configuration in the `application.properties` file.\n\n```properties\n# Datasource configurations\nspring.datasource.url=jdbc:postgresql://localhost:5432/spring_batch\nspring.datasource.username=postgres\nspring.datasource.password=Passw0rd\nspring.datasource.driver-class-name=org.postgresql.Driver\n\n# JPA settings\nspring.jpa.hibernate.ddl-auto=update\nspring.jpa.properties.hibernate.j
1dbc.lob.non_contextual_creation=true\nspring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect\n```\n\n### Define Your Domain Model\n\nIn this example, we will read the customer data from the CSV (`customers.csv`) file and insert it into PostgreSQL. Each row in the `customers.csv` file has the following columns.\n\nYou can download the sample `customers.csv` file from [here](https://raw.githubusercontent.com/StackTipsLab/spring-boot-tutorials/main/spring-batch-chunk-processing/src/main/resources/customers.csv)\n\n```csv\nIndex,Customer Id,First Name,Last Name,Company,City,Country,Phone 1,Phone 2,Email,Subscription Date,Website\n1,4962fdbE6Bfee6D,Pam,Sparks,Patel-Deleon,Blakemouth,British Indian Ocean Territory (Chagos Archipelago),267-243-9490x035,480-078-0535x889,[email protected],2020-11-29,https://nelson.com/\n2,9b12Ae76fdBc9bE,Gina,Rocha,\"Acosta, Paul and Barber\",East Lynnchester,Costa Rica,027.142.0940,+1-752-593-4777x07171,[email protected],2021-01-03,https://pineda-rogers.biz/\n3,39edFd2F60C85BC,Kristie,Greer,Ochoa PLC,West Pamela,Ecuador,+1-049-168-7497x5053,+1-311-216-7855,[email protected],2021-06-20,https://mckinney.com/\n```\n\nLet us now create an entity class with fields matching the CSV row. I have intentionally ignored the `Index` column as we do not want to import it into our database.\n\n```java\n@Builder\n@Data\n@Entity\n@Table(name = \"customers\")\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Customer {\n\n    @Id\n    private String customerId;\n    private String firstName;\n    private String lastName;\n    private String company;\n    private String city;\n    private String country;\n    private String phone1;\n    private String phone2;\n    private String email;\n    private LocalDate subscriptionDate;\n    private String website;\n}\n```\n\n### Create a Repository\n\nWe will use Spring Data JPA to handle database operations. Let us now create a repository for the `Customer` entity. This JPA repository will be used by the writer to save data to Postgres DB.\n\n```java\n@Repository\npublic interface CustomerRepository extends JpaRepository\u003cCustomer, Long\u003e {\n\n}\n```\n\n### Flyway Migrations Scripts\n\nSpring Batch uses a database backend to maintain the state of the job execution. It can resume the job execution from the point of failure.\n\nThe state is maintained in an SQL database. The list of supported database schemas can be found [here](https://github.com/spring-projects/spring-batch/tree/main/spring-batch-core/src/main/resources/org/springframework/batch/core)\n\nFor the database migration, we will use [Flyway](https://stacktips.com/articles/using-flyway-for-database-migration-in-spring-boot). For Flyway to work, we need to add the flyway dependency and the following configurations to the `application.properties` file.  \n\n```properties\nspring.flyway.enabled=true\nspring.flyway.locations=classpath:db/migration\n```\n\nLet us now create two migration scripts inside the `resources/db/migration` directory.\n\n-   `V1__added_spring_batch_tables.sql` - Spring batch schemas for Postgres SQL can be found [here](https://github.com/spring-projects/spring-batch/blob/main/spring-batch-core/src/main/resources/org/springframework/batch/core/schema-postgresql.sql)\n-   `v2__added_customers_table.sql` - Contains schema for customer table.\n\n```sql\nCREATE TABLE customers\n(\n    subscription_date DATE,\n    city              CHARACTER VARYING(255),\n    company           CHARACTER VARYING(255),\n    country           CHARACTER VARYING(255),\n    customer_id       CHARACTER VARYING(255) NOT NULL,\n    email             CHARACTER VARYING(255),\n    first_name        CHARACTER VARYING(255),\n    last_name         CHARACTER VARYING(255),\n    phone1            CHARACTER VARYING(255),\n    phone2            CHARACTER VARYING(255),\n    website           CHARACTER VARYING(255),\n    PRIMARY KEY (customer_id)\n);\n```\n\n### Configure Spring Batch\n\nLet us now define a `SpringBatchConfig` class to set up the Spring Batch job and annotate it with `@Configuration` and `@EnableBatchProcessing` annotation.\n\nThe `@EnableBatchProcessing` annotation enables 
1Spring Batch features and provides a base configuration for setting up batch jobs in an @Configuration class.\n\nThis class will contain the configuration for the Step, Job, ItemReader and ItemWriter.\n\n```java\n@Configuration\n@EnableBatchProcessing\npublic class SpringBatchConfig {\n\n    @Bean\n    public FlatFileItemReader\u003cCustomer\u003e reader() {\n       //TODO\n    }\n\n    @Bean\n    public JpaItemWriter\u003cCustomer\u003e writer() {\n       //TODO\n    }\n\n    @Bean\n    public Job csvImporterJob(Step customerStep, JobRepository jobRepository) {\n        return new JobBuilder(\"csvImporterJob\", jobRepository)\n                .incrementer(new RunIdIncrementer())\n                .flow(customerStep)\n                .end()\n                .build();\n    }\n\n    @Bean\n    public Step csvImporterStep(\n        ItemReader\u003cCustomer\u003e csvReader, ItemWriter\u003cCustomer\u003e csvWriter,\n        JobRepository jobRepository, PlatformTransactionManager tx) {\n\n        return new StepBuilder(\"csvImporterStep\", jobRepository)\n                .\u003cCustomer, Customer\u003echunk(50, tx)\n                .reader(csvReader)\n                .writer(csvWriter)\n                .allowStartIfComplete(true)\n                .build();\n    }\n}\n```\n\nThe `flow()` method defines the flow of the job, starting with `customerStep`, and the `end()` method marks the end of the job flow. If you have multiple steps for your batch job, you can specify using the `next(step2)` method.\n\nWe will use the chunk-based processing and the chunk size to process at a single time is configured using the `chunk()` method on Step configuration.\n\n### ItemReader Configuration\n\nThe `ItemReader` bean is responsible for reading data from a CSV file and mapping the data to Java objects. In this case, it is of type `Customer`.\n\nSpring batch provides `FlatFileItemReader` class to parse the `customers.csv` file from our classpath. Ensure the `customers.csv` file is present in your `/src/main/resources` directory.\n\n```java\n@Bean\npublic FlatFileItemReader\u003cCustomer\u003e reader() {\n    return new FlatFileItemReaderBuilder\u003cCustomer\u003e()\n            .linesToSkip(1)\n            .name(\"csvItemReader\")\n            .resource(new ClassPathResource(\"customers.csv\"))\n            .delimited()\n            .delimiter(\",\")\n            .names(\"index\", \"customerId\", \"firstName\", \"lastName\", \"company\", \"city\", \"country\", \"phone1\", \"phone2\",\n                    \"email\", \"subscriptionDate\", \"website\")\n            .fieldSetMapper(fieldSet -\u003e Customer.builder()\n                    .customerId(fieldSet.readString(\"customerId\"))\n                    .firstName(fieldSet.readString(\"firstName\"))\n                    .lastName(fieldSet.readString(\"lastName\"))\n                    .company(fieldSet.readString(\"company\"))\n                    .city(fieldSet.readString(\"city\"))\n                    .country(fieldSet.readString(\"country\"))\n                    .phone1(fieldSet.readString(\"phone1\"))\n                    .phone2(fieldSet.readString(\"phone2\"))\n                    .email(fieldSet.readString(\"email\"))\n                    .subscriptionDate(DateUtils.parseDate(fieldSet.readString(\"subscriptionDate\")))\n                    .website(fieldSet.readString(\"website\"))\n                    .build()\n            ).build();\n}\n```\n\nThe `linesToSkip()` method is used to skip a specified number of rows while reading the file. This is particularly used to skip the header row of the CSV file.\n\nThe `delimiter()` method specifies the delimiter used in the file to separate the fields.\n\nThe `names()` method specifies the column names in the CSV file. It is important to maintain the order of the column names as they appear in the source CSV file. These names are used to map values from each column to fields in the `Customer` object.\n\nThe `fieldSetMapper()` defines how to map fields from the CSV to the `Customer` object.\n\nIn this example, we are manually mapping each field and setting the values to the `Customer` object. But if you want to parse all the fields from CSV and if it maps exactly to the field names, you can use `BeanWrapperFieldSetMapper` to automatically map each column to a Java object.\n\n```java\n.fieldSetMapper(new BeanWrapperFieldSetMapper\u003c\u003e() {{\n    setTargetType(Customer.class);\n}})\n```\n\n### ItemWriter Configuration\n\nFor saving the data into the database using JPA we will create an instance of `JpaItemWriter` and set the `EntityManagerFactory` bean.\n\nThe `EntityManagerFactory` is configured automatically by Spring Boot when we add the Spring Data JPA to our classpath. Thanks to the Spring boot auto configuration.\n\n```java\n@Bean\npublic JpaItemWriter\u003cCustomer\u003e writer(EntityManagerFactory entityManagerFactory) {\n    JpaItemWriter\u003cCustomer\u003e writer = new JpaItemWriter\u003c\u003e();\n    writer.setEntityManagerFactory(entityManagerFactory);\n    return writer;\n}
1\n```\n\nWith this, we are done with the job configurations.\n\n### Running a Job\n\nThe Job can triggered from a command line runner, from a REST controller, using a [Spring Scheduler](https://stacktips.com/articles/task-execution-and-scheduling-in-spring-boot) cron job or from [application events](https://stacktips.com/articles/how-to-execute-code-on-spring-boot-application-startup#option-3-using-spring-boot-events).\n\nIn this example, we will use an application-ready event to trigger the job. This will trigger the job immediately after the application starts.\n\n```java\n@Component\n@RequiredArgsConstructor\npublic class ApplicationStartEvent {\n\n    private final JobLauncher jobLauncher;\n    private final Job csvImporterJob;\n\n    @EventListener(ApplicationReadyEvent.class)\n    public void onReadyEvent() throws JobExecutionException {\n        jobLauncher.run(csvImporterJob, new JobParameters());\n    }\n}\n```\n\nNow, build and run the application. Notice that the importer job will be triggered and CSV file content will be imported into the Postgres database.\n\n## Job Execution Listener\n\nDuring the Job execution of a `Job`, it may be useful to be notified of various events in its lifecycle. For that, we can create a listener for the importer job by implementing the `JobExecutionListener` interface.\n\nThe `JobExecutionListener` interface has `beforeJob()` and `afterJob()` methods. As the name indicates they are triggered accordingly based on the Job lifecycle. Note that the `afterJob()` method is called regardless of the success or failure of the `Job`.\n\nFor now, we are logging but you can add your custom business logic here.\n\n```java\n@Slf4j\n@Component\npublic class ImportJobListener implements JobExecutionListener {\n\n    @Override\n    public void beforeJob(JobExecution jobExecution) {\n        log.info(\"Job:{} execution started\", jobExecution.getJobInstance().getJobName());\n    }\n\n    @Override\n    public void afterJob(JobExecution jobExecution) {\n        if (jobExecution.getStatus() == BatchStatus.COMPLETED) {\n            log.info(\"Job completed: {}\", jobExecution.getJobInstance().getJobName());\n        } else if (jobExecution.getStatus() == BatchStatus.FAILED) {\n            log.error(\"Error while running job: {}\", jobExecution.getJobInstance().getJobName());\n        }\n    }\n}\n```\n\nThe custom job listener can be added to the job by calling the `listener()` method on `JobBuilder`.\n\n```java\n@Bean\npublic Job csvImporterJob(Step customerStep, JobRepository jobRepository,\n                          ImportJobListener importJobListener) {\n    return new JobBuilder(\"csvImporterJob\", jobRepository)\n            .incrementer(new RunIdIncrementer())\n            .listener(importJobListener)\n            .flow(customerStep)\n            .end()\n            .build();\n}\n```\n\n## Passing Job Parameters\n\nWhile running a job, we can also pass the runtime parameters using `JobParameters` . The Spring batch can parse the job parameters while running the task and you can use custom logic based on your use case.\n\nFor example, let us pass `ignoreCountry` parameter to our import job and ignore the customers that are from **'India'**.\n\n```java\n@Component\n@RequiredArgsConstructor\npublic class ApplicationStartEvent {\n\n    private final JobLauncher jobLauncher;\n    private final Job csvImporterJob;\n\n    @EventListener(ApplicationReadyEvent.class)\n    public void onReadyEvent() throws JobExecutionException {\n        JobParameters jobParameters = new JobParametersBuilder()\n                .addString(\"ignoreCountry\", \"India\")\n                .toJobParameters();\n\n        jobLauncher.run(csvImporterJob, jobParameters);\n    }\n}\n```\n\nYou can read the parameters passed to the job using `getCurrentJobParameters()` method.\n\n```java\nJobParameters jobParameters = jobLauncher.getCurrentJobParameters();\nString ignoreCountry = jobParameters.getString(\"ignoreCountry\");\n```\n\nTo exclude customers based on the parameter, we will create a custom processor to filter the customers based on customer location.\n\nTo access the parameters from the processor, we need to obtain the `JobExecution` linked to the current execution context. Since `ItemProcessor` does not have access to job parameters directly, you can use `StepExecutionListener` to inject these parameters before the step begins.\n\nThe `@JobScope` annotation can be used on the processor to bind the job lifecycle to the execution of a job. This allows us to inject job parameters directly into the processor using Spring Expression Language (SpEL).\n\n```java\n@Slf4j\n@StepScope\n@Component\npublic class CustomerJobProcessor implements ItemProcessor\u003cCustomer, Customer\u003e {\n\n    private final Str
1ing ignoreCountry;\n\n    public CustomerJobProcessor(@Value(\"#{jobParameters['ignoreCountry']}\") String ignoreCountry) {\n        this.ignoreCountry = ignoreCountry;\n    }\n\n    @Override\n    public Customer process(Customer customer) {\n        if (customer.getCountry().equalsIgnoreCase(ignoreCountry)) {\n            log.info(\"Ignoring customer {} {} belongs to country {}\", customer.getFirstName(),\n                    customer.getLastName(), customer.getCountry());\n            return null;\n        }\n        return customer;\n    }\n}\n```\n\nWe can optionally validate job parameters at runtime using `JobParametersValidator` and override the `validate()` method.\n\n```java\n@Bean\npublic Job csvImporterJob(Step customerStep, JobRepository jobRepository,\n                          ImportJobListener importJobListener) {\n    return new JobBuilder(\"csvImporterJob\", jobRepository)\n            .incrementer(new RunIdIncrementer())\n            .validator(new JobParametersValidator() {\n                @Override\n                public void validate(JobParameters parameters) throws JobParametersInvalidException {\n                    String ignoreCountry = parameters.getString(\"ignoreCountry\");\n                    if (\"Costa Rica\".equals(ignoreCountry)) {\n                        throw new JobParametersInvalidException(\"Country ignored\");\n                    }\n                }\n            })\n            .listener(importJobListener)\n            .flow(customerStep)\n            .end()\n            .build();\n}\n```\n\nFor the complete project source code check out the download link.\n\nIf you have any questions, write down in the comment section below. Will be happy to respond, soon as I can.\n"])</script>
1<script>self.__next_f.push([1,"31:T3453,"])</script>
1<script>self.__next_f.push([1,"\nOver the past few years working in Spring, I had the opportunity to use different HTTP clients for consuming third-party REST API calls. Starting from `RestTemplate` to the more modern `RestClient` and all-new declarative HTTP interface.\n\nWhile talking to different candidates during the interviews, almost all of them have used RestTemplate, while only a few know about the other modern alternatives available in the spring framework.\n\nThis post covers different options available for making REST API calls from Spring and dives into the strengths and weaknesses of each.\n\nMainly we have the following choices:\n\n1.  [RestTemplate](https://stacktips.com/articles/calling-rest-services-using-resttemplate)\n2.  Feign Client\n3.  Rest Client\n4.  [WebClient](https://stacktips.com/articles/what-is-webclient-how-to-use-webclient-in-java-springboot)\n5.  New declarative HTTP Interface\n\n### 1. RestTemplate\n\nThe `RestTemplate` was Introduced almost 14 years ago in Spring Framework version 3.0. RestTemplate is a synchronous client used to make HTTP requests from the Spring application. It simplifies the process of making HTTP requests using template-like classes.\n\nFor using `RestTemplate` in Spring boot, we need to include `spring-boot-starter-web` dependency.\n\nThe following code snippet is used to consume the FakeStore API and perform different HTTP API calls.\n\n```java\n@Component  \npublic class ProductApiClient {  \n\n    private static final String POST_API = \"https://fakestoreapi.com/products\";  \n    private static final String GET_API = \"https://fakestoreapi.com/products/{productId}\";  \n    private static final String DELETE_API = \"https://fakestoreapi.com/products/{productId}\";  \n\n    @Value(\"${product-api.key}\")  \n    private String apiKey;  \n\n    private final RestTemplate restTemplate;  \n\n    public ProductApiClient(RestTemplateBuilder restTemplateBuilder) {  \n        this.restTemplate = restTemplateBuilder.build();  \n    }  \n\n    public ResponseEntity\u003cProduct\u003e getProduct(String productId) {  \n        Map\u003cString, String\u003e params = new HashMap\u003c\u003e();  \n        params.put(\"productId\", productId);  \n\n        return restTemplate.getForEntity(GET_API, Product.class, params);  \n    }  \n\n    public Product createProduct(Product product) {  \n        HttpHeaders headers = new HttpHeaders();  \n        headers.set(\"X-API-KEY\", apiKey);  \n        headers.setContentType(MediaType.APPLICATION_JSON);  \n\n        HttpEntity\u003cProduct\u003e httpEntity = new HttpEntity\u003c\u003e(product, headers);  \n        return restTemplate.postForObject(POST_API, httpEntity, Product.class);  \n    }  \n\n    public void updateProduct(Product product) {  \n        Map\u003cString, String\u003e params = new HashMap\u003c\u003e();  \n        params.put(\"productId\", product.getId());  \n        restTemplate.put(GET_API, product, params);  \n    }  \n\n    public void deleteProduct(String productId) {  \n        Map\u003cString, String\u003e params = new HashMap\u003c\u003e();  \n        params.put(\"productId\", productId);  \n        restTemplate.delete(DELETE_API, params);  \n    }  \n}\n```\n\nThe `RestTemplate` operates on a synchronous and blocking model, which is not as efficient as other modern alternatives.\n\nWhile `RestTemplate` has been a very reliable workhorse for making HTTP calls for over a decade, a modern version of the HTTP client called `WebClient` was introduced in Spring 5.\n\n_Notice_\n\nIf you’re developing a new application or migrating the old codebase, it is recommended to use [WebClient](https://stacktips.com/articles/what-is-webclient-how-to-use-webclient-in-java-springboot) over `RestTemplate`. Even better, if you're using Spring 6, you can use `RestClient` backed Spring Interface declarative clients.\n\n### 2. Feign Client\n\nFor many years, we relied on `RestTemplate` for our HTTP communications from Spring, and it served us well. However, as our API contracts expanded and we added new endpoints, we began to see that keeping up with the API changes with `RestTemplate` was becoming increasingly difficult.\n\nWe were on a hunt for an alternative to `RestTemplate` that requires writing less code. Fast forward to 2020, the `FeignClient` was first introduced as a part of the **Spring Cloud Netflix** stack.\n\nFeign is a declarative REST client designed to simplify the process of writing web service clients by handling boilerplate tasks such as client creation and response handling. Users simply need to define an interface using standard JAX-RS annotations, and the framework manages the rest. Additionally, Feign provides support for encoders, decoders, and extensive logging support.\n\nTo use FeignClient, we need to add the `spring-cloud-starter-openfeign` dependency.\n\nThe above `ProductApiClient` can be written in Feign as:\n\n```java\n@FeignClient(name = \"product-api-client\", url = \"https://fakestoreapi.com\")  \npublic interface ProductApiClient {  \n\n    @GetMapping(\"/products/{productId}\")  \n    ResponseEntity\u003cProduct\u003e getProduct(@PathVariable(\"productId\") String productId);  \n\n    @PostMapping(\"/products\")  \n    Product createProduct(@RequestBody Product product, \n                    @RequestHeader(\"X-API-KEY\") String apiKey);
1  \n\n    @PutMapping(\"/products/{productId}\")  \n    void updateProduct(@PathVariable(\"productId\") String productId, \n                    @RequestBody Product product);  \n\n    @DeleteMapping(\"/products/{productId}\")  \n    void deleteProduct(@PathVariable(\"productId\") String productId);  \n}\n```\n\nBoth **Feign** and **RestTemplate** are designed for synchronous operations and do not support asynchronous API calls. To achieve asynchronous behaviour, we have to write a custom implementation using `CompletableFuture` or another asynchronous execution mechanism.\n\n_Notice_\n\nStarting with Spring 6 and Spring Cloud 2022, the Spring community recommend WebClient-backed Spring interface clients as a declarative client solution of choice.\n\n### 3. WebClient\n\nThe `WebClient` is an alternative to `RestTemplate`. It was introduced in Spring 5 as part of the **WebFlux** stack. It provides both synchronous and asynchronous APIs to make the REST calls from the Spring application.\n\nTo use `WebClient` in a Spring Boot application, we need to add the `spring-boot-starter-webflux` dependency.\n\nThe above `ProductApiClient` can be written using `WebClient` as follows:\n\n```java\n@Component  \npublic class ProductApiClient {  \n\n    @Value(\"${product-api.key}\")  \n    private String apiKey;  \n\n    private final WebClient webClient;  \n\n    public ProductApiClient(WebClient.Builder webClientBuilder) {  \n        this.webClient = webClientBuilder  \n                .baseUrl(\"https://fakestoreapi.com\")  \n                .build();  \n    }  \n\n    public Mono\u003cResponseEntity\u003cProduct\u003e\u003e getProduct(String productId) {  \n        return webClient.get()  \n                .uri(\"/products/{productId}\", productId)  \n                .retrieve()  \n                .toEntity(Product.class);  \n    }  \n\n    public Mono\u003cProduct\u003e createProduct(Product product) {  \n        return webClient.post()  \n                .uri(\"/products\")  \n                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)  \n                .header(\"X-API-KEY\", apiKey)  \n                .bodyValue(product)  \n                .retrieve()  \n                .bodyToMono(Product.class);  \n    }  \n\n    public Mono\u003cVoid\u003e updateProduct(String productId, Product product) {  \n        return webClient.put()  \n                .uri(\"/products/{productId}\", productId)  \n                .bodyValue(product)  \n                .retrieve()  \n                .bodyToMono(Void.class);  \n    }  \n\n    public Mono\u003cVoid\u003e deleteProduct(String productId) {  \n        return webClient.delete()  \n                .uri(\"/products/{productId}\", productId)  \n                .retrieve()  \n                .bodyToMono(Void.class);  \n    }  \n}\n```\n\nThe `WebClient` works similar way to `RestTemplate` but with a modern functional and fluent style API.\n\nRef: [WebClient](https://docs.spring.io/spring-framework/reference/integration/rest-clients.html#rest-webclient)\n\n### 4. RestClient\n\nThe `RestClient` is a newer client in Spring 6, designed to overcome some limitations of `RestTemplate`. It supports both synchronous and asynchronous operations.\n\nAs you can see in the following example, the `RestClient` work similarly to the `WebClient` API, except we don’t have to add the WebFlux dependency.\n\nIt also provides helper methods to extract the response including status, headers, and body without calling the `block()` or `subscribe()` method.\n\nThe `RestTemplate` is marked for deprecation in Spring 6 and it is recommended to use `RestClient` for applications using Spring 6 or above.\n\nTo use `RestClient` in Spring Boot, we need to add the `spring-boot-starter-web` dependency.\n\n```java\n@Component  \npublic class ProductApiClient {  \n\n    private static final String BASE_URL = \"https://fakestoreapi.com\";  \n\n    @Value(\"${product-api.key}\")  \n    private String apiKey;  \n\n    private final RestClient restClient;  \n\n    public ProductApiClient() {  \n        this.restClient = RestClient.builder()  \n                .baseUrl(BASE_URL)  \n                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)  \n                .build();  \n    }  \n\n    public ResponseEntity\u003cProduct\u003e getProduct(String productId) {  \n        return restClient.get()  \n                .uri(\"/products/{productId}\", productId)  \n                .retrieve()  \n                .toEntity(Product.class);  \n    }  \n\n    public ResponseEntity\u003cProduct\u003e createProduct(Product product) {  \n        return restClient.post()  \n                .uri(\"/products\")  \n                .header(\"X_API_KEY\", apiKey)  \n                .body(product)  \n                .retrieve()  \n                .toEntity(Product.class);  \n    }  \n\n    public void updateProduct(Product product) {  \n        restClient.put()  \n                .uri(\"/products/{productId}\", product.getId())  \n                .header(\"X_API_KEY\", apiKey)  \n                .body(product)  \n                .retrieve().toEntity(Product.class);  \n    }  \n\n    public void deleteProduct(String productId) {  \n        restClient.delete()  \n                .uri(\"/products/{productId}\", productId)  \n                .header(\"X_API_KEY\", apiKey)  \n                .retrieve().toBodilessEntity();  \n    }  \n}\n```\n\nRef: [RestClient](https://docs.spring.io/spring-framework/reference/integration/rest-clients.html#rest-restclient)\n\n### 5. HTTP Interface\n\nSpring 6 also adds the ability to create a declarative HTTP interface (similar to Fe
1ign) using the existing HTTP clients such as RestTemplate, WebClient and RestClient.\n\nIt creates a proxy to perform requests and attach it to the preferred HTTP client configured. For example, the above `ProductApiClient` can be written using a declarative HTTP interface as follows:\n\n```java\n@HttpExchange(url = \"/products\")  \npublic interface ProductApiClient {  \n\n    @GetExchange(url = \"/{productId}\")  \n    ResponseEntity\u003cProduct\u003e getProduct(@PathVariable String productId);  \n\n    @PostExchange  \n    Product createProduct(@RequestBody Product product);  \n\n    @PutExchange(url = \"/{productId}\")  \n    void updateProduct(@PathVariable String productId, @RequestBody Product product,  \n                       @RequestHeader(name = \"X_API_KEY\") String apikey);  \n\n    @DeleteExchange(url = \"/{productId}\")  \n    void deleteProduct(@PathVariable String productId,  \n                       @RequestHeader(name = \"X_API_KEY\") String apikey);  \n}\n```\n\nNow you can create a proxy that performs requests when methods are called.\n\nTo use it with `RestTemplate`:\n\n```java\n@Bean  \npublic ProductApiClient productApiClient() {  \n    RestTemplate restTemplate = new RestTemplate();  \n    restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(\"https://fakestoreapi.com\"));  \n    RestTemplateAdapter adapter = RestTemplateAdapter.create(restTemplate);  \n    HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();  \n    return factory.createClient(ProductApiClient.class);  \n}\n```\n\nTo use it with `WebClient`:\n\n```java\n@Bean  \npublic ProductApiClient productApiClient() {  \n    WebClient webClient = WebClient.builder()  \n            .baseUrl(\"https://fakestoreapi.com\")  \n            .build();  \n    WebClientAdapter adapter = WebClientAdapter.create(webClient);  \n    HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();  \n    return factory.createClient(ProductApiClient.class);  \n}\n```\n\nTo use it with `RestClient`:\n\n```java\n@Bean  \npublic ProductApiClient productApiClient() {  \n    RestClient restClient = RestClient.builder()  \n            .baseUrl(\"https://fakestoreapi.com\")  \n            .build();  \n    RestClientAdapter adapter = RestClientAdapter.create(restClient);  \n    HttpServiceProxyFactory factory = HttpServiceProxyFactory  \n            .builderFor(adapter)  \n            .build();  \n    return factory.createClient(ProductApiClient.class);  \n}\n```\n\nThe all-new declarative HTTP interface simplifies the code and improves readability. It also provides compile-time checks and validations, reducing runtime errors.\n\n### Conclusion\n\nSpring framework has evolved over the years from synchronous to reactive and declarative HTTP clients. While `RestTemplate` provides fully tested and stable APIs, the new reactive and declarative clients using `RestClient` is the way forward.\n"])</script>
1<script>self.__next_f.push([1,"32:T2f57,"])</script>
1<script>self.__next_f.push([1,"\nFlyway is a popular open-source tool for managing database migrations. It makes it easy to manage and version control the database schema for your application.\n\nFlyway supports almost all popular databases including Oracle, SQL Server, DB2, MySQL, Amazon RDS, Aurora MySQL, MariaDB, PostgreSQL and more. For the full list of supported databases, you can check the [official documentation](https://documentation.red-gate.com/fd/supported-databases-184127454.html) here.\n\n## How Flyway Migrations Works\n\nAny changes to the database are called migrations. Flyway supports two types of migrations; **versioned** or **repeatable** migrations.\n\n-   **Versioned migrations** Versioned migrations are the most common type of migration, they are applied once in the order they appear. Versioned migrations are used for creating, altering, and dropping tables, indexes or foreign keys.\n    \n    Versioned migration files uses naming convention using `[Prefix][Separator][Migration Description][Suffix]` for example, `V1__add_user_table.sql` and `V2__alter_user_table.sql`\n    \n-   **Repeatable migration** Repeatable migrations on the other hand are (re-)applied every time they change. Repeatable migrations are useful for managing views, stored procedures, or bulk reference data updates where the latest version should replace the previous one without considering versioning.\n    \n    Repeatable migrations are always applied last after all pending versioned migrations are been executed. Repeatable migration files use naming convention such as `R__add_new_table.sql`\n    \n\nThe migration schemas can be written in either SQL or Java.\n\nWhen we start the application to an empty database, Flyway will first create a schema history table (`flyway_schema_history`) table. This table IS used to track the state of the database.\n\nAfter the `flyway_schema_history` table is created, it will scan the classpath for the migration files. The migrations are then **sorted** based on their **version number** and applied in order.\n\nAs each migration gets applied, the schema history table is updated accordingly.\n\n## Integrating Flyway in Spring Boot\n\nIn this tutorial, we will create a Spring Boot application to deal with MySQL8 database migration using Flyway. This example uses Java 17, Spring Boot 3.2.4 and MySQL 8.0.26. For the database operation, we will use Spring boot JPA.\n\n### Install Flyway Dependencies\n\nFirst, add the following dependencies to your `pom.xml` or your `build.gradle` file.\n\n-   The `spring-boot-starter-data-jpa` dependency is used for using Spring Data Java Persistence API (JPA) with Hibernate.\n-   The `mysql-connector-j` is the official JDBC driver for MySQL databases. It allows your Java application to connect to a MySQL database for operations such as creating, reading, updating, and deleting records.\n-   The `flyway-core` dependency is essential for integrating Flyway into your project, enabling migrations and version control for your database schema.\n-   The `flyway-mysql` dependency adds the Flyway support for MySQL databases. It provides MySQL-specific functionality and optimisations for Flyway operations. It's necessary when your application uses Flyway for managing database migrations on a MySQL database.\n\n**pom.xml**\n\n```xml\n\u003cdependencies\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n        \u003cartifactId\u003espring-boot-starter-data-jpa\u003c/artifactId\u003e\n    \u003c/dependency\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003ecom.mysql\u003c/groupId\u003e\n        \u003cartifactId\u003emysql-connector-j\u003c/artifactId\u003e\n        \u003cscope\u003eruntime\u003c/scope\u003e\n    \u003c/dependency\u003e\n\n    \u003cdependency\u003e\n        \u003cgroupId\u003eorg.flywaydb\u003c/groupId\u003e\n        \u003cartifactId\u003eflyway-core\u003c/artifactId\u003e\n    \u003c/dependency\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003eorg.flywaydb\u003c/groupId\u003e\n        \u003cartifactId\u003eflyway-mysql\u003c/artifactId\u003e\n    \u003c/dependency\u003e\n    \u003c!-- Other dependencies--\u003e\n\u003c/dependencies\u003e\n```\n\n### Configure the Database Connection\n\nNow let us provide the database connection properties in your `application.properties` file.\n\n```properties\n# DB properties\nspring.datasource.url=jdbc:mysql://localhost:3306/flyway_demo\nspring.datasource.username=root\nspring.datasource.password=Passw0rd\nspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver\n\n#JPA\nspring.jpa.show-sql=true\n```\n\n### Create Database Changelog Files\n\nLet us now create a couple of database migration schema files inside the `resources/db/migrations` directory.\n\n**V1\\_\\_add\\_movies\\_table**\n\n```sql\nCREATE TABLE movie\n(\n    id        bigint NOT NULL AUTO_INCREMENT,\n    title     varchar(255) DEFAULT NULL,\n    headline  varchar(255) DEFAULT NULL,\n    language  varchar(255) DEFAULT NULL,\n    region    varchar(255) DEFAULT NULL,\n    thumbnail varchar(255) DEFAULT NULL,\n    rating    enum('G','PG','PG13','R','NC17') DEFAULT NULL,\n    PRIMARY KEY (id)\n) ENGINE=InnoDB;\n```\n\n**V2\\_\\_add\\_actor\\_table.sql**\n\n```sql\nCREATE TABLE actor\n(\n    id         bigint NOT NULL AUTO_INCREMENT,\n    first_name varchar(255) DEFAULT NULL,\n    last_name  varchar(255) DEFAULT NULL,\n    PRIMARY KEY (id)\n) ENGINE=InnoDB;\n```\n\n**V3\\_\\_add\\_movie\\_actor\\_relations.sql**\n\n```sql\nCREATE TABLE movie_actors\n(\n    actors_id bigint NOT NULL,\n    movie_id  bigint NOT NULL,\n    PRIMARY KEY (actors_id, movie_id),\
1n    KEY       fk_ref_movie (movie_id),\n    CONSTRAINT fk_ref_movie FOREIGN KEY (movie_id) REFERENCES movie (id),\n    CONSTRAINT fl_ref_actor FOREIGN KEY (actors_id) REFERENCES actor (id)\n) ENGINE=InnoDB;\n```\n\n**R\\_\\_create\\_or\\_replace\\_movie\\_view.sql**\n\n```sql\nCREATE OR REPLACE VIEW movie_view AS\nSELECT id, title\nFROM movie;\n```\n\n**V4\\_\\_insert\\_test\\_data.sql**\n\n```sql\nINSERT INTO movie (title, headline, language, region, thumbnail, rating)\nVALUES ('Inception', 'A thief who steals corporate secrets through the use of dream-sharing technology.', 'English',\n        'USA', 'inception.jpg', 'PG13'),\n       ('The Godfather',\n        'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.',\n        'English', 'USA', 'godfather.jpg', 'R'),\n       ('Parasite',\n        'A poor family, the Kims, con their way into becoming the servants of a rich family, the Parks. But their easy life gets complicated when their deception is threatened with exposure.',\n        'Korean', 'South Korea', 'parasite.jpg', 'R'),\n       ('Amélie',\n        'Amélie is an innocent and naive girl in Paris with her own sense of justice. She decides to help those around her and, along the way, discovers love.',\n        'French', 'France', 'amelie.jpg', 'R');\n\n-- Inserting data into the 'actor' table\nINSERT INTO actor (first_name, last_name)\nVALUES ('Leonardo', 'DiCaprio'),\n       ('Al', 'Pacino'),\n       ('Song', 'Kang-ho'),\n       ('Audrey', 'Tautou');\n\n-- Leonardo DiCaprio in Inception\nINSERT INTO movie_actors (actors_id, movie_id)\nVALUES (1, 1);\n\n-- Al Pacino in The Godfather\nINSERT INTO movie_actors (actors_id, movie_id)\nVALUES (2, 2);\n\n-- Song Kang-ho in Parasite\nINSERT INTO movie_actors (actors_id, movie_id)\nVALUES (3, 3);\n\n-- Audrey Tautou in Amélie\nINSERT INTO movie_actors (actors_id, movie_id)\nVALUES (4, 4);\n```\n\nThese tables are mapped to the following entity classes.\n\n**Movie.java**\n\n```java\n@Entity\n@Data\npublic class Movie {\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private Long id;\n    private String title;\n    private String headline;\n    private String thumbnail;\n    private String language;\n    private String region;\n    @Enumerated(EnumType.STRING)\n    private ContentRating rating;\n\n    @ManyToMany\n    Set\u003cActor\u003e actors;\n}\n\npublic enum ContentRating {\n    G,\n    PG,\n    PG13,\n    R,\n    NC17\n}\n```\n\n**Actor.java**\n\n```java\n@Entity\n@Data\npublic class Actor {\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    Long id;\n    String firstName;\n    String lastName;\n}\n```\n\n### Configure Flyway\n\nWe can control the migration process using the following properties in `application.properties` file:\n\n**application.properties**\n\n```properties\nspring.flyway.enabled=true\nspring.flyway.locations=classpath:db/migrations\nspring.flyway.baseline-on-migrate=true\nspring.flyway.validate-on-migrate=true\n```\n\n| Property | Use |\n| --- | --- |\n| spring.flyway.enabled=true | Enables or disables Flyway's migration functionality for your application |\n| spring.flyway.validate-on-migrate=true | When this property is set to true, Flyway will validate the applied migrations against the migration scripts every time it runs a migration. This ensures that the migrations applied to the database match the ones available in the project.If validation fails, Flyway will prevent the migration from running, which helps catch potential problems early. |\n| spring.flyway.baseline-on-migrate=true | Used when you have an existing database that wasn't managed by Flyway and you want to start using Flyway to manage it. Setting this to true allows Flyway to baseline an existing database, marking it as a baseline and starting to manage subsequent migrations. |\n| spring.flyway.locations | Specifies the locations of migration scripts within your project. |\n\n### Run the Migrations\n\nWhen you start your Spring Boot application, Flyway will automatically check the `db/migrations` directory for any new migrations that have not yet been applied to the database and will apply them in ver
1sion order.\n\n```bash\n./mvnw spring-boot:run\n```\n\n### Reverse/Undo Migrations in Flyway\n\nFlyway allows you to revert migrations that was applied to the database. However, this feature requires you to have Flyway Teams (Commercial) license.\n\nIf you're using the community/free version of Flyway, the workaround is to create a new migration changelog file to undo the changes made by the previous migration and apply them.\n\nFor example, **V5\\_\\_delete\\_movie\\_actors\\_table.sql**\n\n```sql\nDROP TABLE movie_actors;\n```\n\nNow run the application to apply the V5 migration changelog to your database.\n\n## Using Flyway Maven Plugin\n\nFlyway provides a maven plugin to manage the migrations from command line. It provides 7 goals.\n\n| Goal | Description |\n| --- | --- |\n| flyway:baseline | Baselines an existing database, excluding all migrations up to and including baselineVersion. |\n| flyway:clean | Drops all database objects (tables, views, procedures, triggers, ...) in the configured schemas. The schemas are cleaned in the order specified by the schemas property.. |\n| flyway:info | Retrieves the complete information about the migrations including applied, pending and current migrations with details and status |\n| flyway:migrate | Triggers the migration of the configured database to the latest version. |\n| flyway:repair | Repairs the Flyway schema history table. This will remove any failed migrations on databases without DDL transactions |\n| flyway:undo | Undoes the most recently applied versioned migration. Flyway teams only |\n| flyway:validate | Validate applied migrations against resolved ones on the classpath. This detect accidental changes that may prevent the schema(s) from being recreated exactly. |\n\nTo integrate the flyway maven plugin in your maven project, we need to add `flyway-maven-plugin` plugin to your `pom.xml` file.\n\n```xml\n\u003cproperties\u003e\n    \u003cdatabase.url\u003ejdbc:mysql://localhost:3306/flyway_demo\u003c/database.url\u003e\n    \u003cdatabase.username\u003eYOUR_DB_USER\u003c/database.username\u003e\n    \u003cdatabase.password\u003eYOUR_DB_PASSWORD\u003c/database.password\u003e\n\u003c/properties\u003e\n\n\u003cbuild\u003e\n    \u003cplugins\u003e\n        \u003cplugin\u003e\n            \u003cgroupId\u003eorg.flywaydb\u003c/groupId\u003e\n            \u003cartifactId\u003eflyway-maven-plugin\u003c/artifactId\u003e\n            \u003cversion\u003e10.10.0\u003c/version\u003e\n            \u003cconfiguration\u003e\n                \u003curl\u003e${database.url}\u003c/url\u003e\n                \u003cuser\u003e${database.username}\u003c/user\u003e\n                \u003cpassword\u003e${database.password}\u003c/password\u003e\n            \u003c/configuration\u003e\n        \u003c/plugin\u003e\n\n        \u003c!-- other plugins --\u003e\n    \u003c/plugins\u003e\n\u003c/build\u003e\n```\n\nNow you can use the Maven goals\n\n```bash\n./mvnw flyway:migrate\n```\n\nMaven allows you to define properties in the project's POM and pass the value from the command line.\n\n```bash\n./mvnw -Ddatabase.username=root -Ddatabase.password=Passw0rd flyway:migrate\n```\n"])</script>
1<script>self.__next_f.push([1,"33:T1c9b,"])</script>
1<script>self.__next_f.push([1,"\nIn the previous lesson, we saw different ways to bootstrap a Spring Boot project and we have learnt about different methods available for building and running the project. In this chapter, we will understand the different files and folders present inside the spring boot project.\n\nSpring Boot organizes the code according to some of the best practices in the industry. Since we generated our project with Gradle in the previous chapter, here's what the `hello-spring` project looks like:\n\n```\nhello-spring\n├── build\n├── build.gradle\n├── settings.gradle\n├── gradlew\n├── gradlew.bat\n├── gradle\n│   └── wrapper\n│       ├── gradle-wrapper.jar\n│       └── gradle-wrapper.properties\n└── src\n    ├── main\n    │   ├── java\n    │   │   └── com\n    │   │       └── stacktips\n    │   │           └── hello_spring\n    │   │               └── HelloSpringApplication.java\n    │   └── resources\n    │       ├── application.properties\n    │       ├── static\n    │       └── templates\n    └── test\n        └── java\n            └── com\n                └── stacktips\n                    └── hello_spring\n                        └── HelloSpringApplicationTests.java\n```\n\nIf you generated a Maven project instead in the previous chapter, the layout is the same under `src/`, but the build tooling differs slightly:\n\n```\nhello-spring\n├── target\n├── pom.xml\n├── mvnw\n├── mvnw.cmd\n└── .mvn\n    └── wrapper\n        └── maven-wrapper.properties\n```\n\nEverything from `src/` down works identically regardless of which build tool you picked — only the sections below covering the build file, wrapper, and output folder differ between the two.\n\n### `build.gradle` (or `pom.xml`)\n\nThis is the file we looked at back in [Chapter 2](/articles/prerequisites-for-spring-boot-development) — it outlines the project metadata, dependencies, and build configuration for your project. Gradle projects use `build.gradle`; Maven projects use `pom.xml` instead.\n\n### `settings.gradle`\n\nThis file declares the root project's name and, in multi-module projects, which sub-modules belong to the build. For a single-module project like ours, it just contains a single line setting the project name (`rootProject.name = 'hello-spring'`). Maven projects don't have an equivalent file — the same information lives inside `pom.xml`.\n\n### The Gradle/Maven Wrapper\n\nThe `gradlew` and `gradlew.bat` scripts (or `mvnw` and `mvnw.cmd` for Maven) are the wrapper scripts we used in the previous chapter to run the project — `./gradlew bootRun` on macOS/Linux, `gradlew.bat bootRun` on Windows. They let anyone build the project with the exact Gradle (or Maven) version it was built with, without installing Gradle or Maven globally. The supporting jar and version info live in `gradle/wrapper/` (or `.mvn/wrapper/` for Maven) — you don't need to touch these files directly.\n\n### The `build` (or `target`) Directory\n\nThis directory is generated automatically when you build the project — `build/` for Gradle, `target/` for Maven. It contains the compiled `.class` files, the packaged JAR, and other build artifacts. You don't need to manually modify anything in this directory, and it's typically excluded from version control via `.gitignore`.\n\n### The `src/main/java` Directory\n\nThe `src/main/java` directory contains the Java source code for your project, following the standard Java packaging structure. Recall from [Chapter 3](/articles/setting-up-your-first-spring-boot-project) that we set the Spring Initializr **Group** to `com.stacktips` and **Package name** to `com.stacktips.hello_spring` — that's exactly the folder path you see here: `com/stacktips/hello_spring`. This is your project's base package, and it's where the rest of your application code will live as the course progresses.\n\n#### The Main Application Class\n\nThe `HelloSpringApplication` class is the entry point of your Spring Boot application. It contains a `main()` method, which is responsible for initializing the Spring application context and starting the application.\n\nThis class is annotated with `@SpringBootApplication`, a convenience annotation that combines three other Spring Boot annotations:\n\n-   `@EnableAutoConfiguration` enables 
1Spring Boot's auto-configuration mechanism, which automatically configures many common Spring beans based on the dependencies present in the classpath.\n-   `@Configuration` indicates that the class contains one or more bean definitions via `@Bean` annotations.\n-   `@ComponentScan` scans the classpath for classes annotated with `@Component`, `@Service`, `@Repository`, or `@Configuration`. Classes registered with any of these four annotations are registered as beans in the Spring application context.\n\nWe will learn more about this annotation in [Chapter 5, Dependency Injection](/articles/dependency-injection-in-spring-boot).\n\n```java\n@SpringBootApplication\npublic class HelloSpringApplication {\n\n    public static void main(String[] args) {\n        SpringApplication.run(HelloSpringApplication.class, args);\n    }\n}\n```\n\nBy using `@SpringBootApplication`, you don't need to declare `@Configuration`, `@EnableAutoConfiguration`, and `@ComponentScan` separately — it bundles all three for you.\n\n### The `src/main/resources` Directory\n\nThe `resources` directory is for non-Java resources your application needs — configuration files, static assets and templates.\n\n**`application.properties`** — contains the configuration for your Spring Boot application, as key-value pairs separated by `=`. We'll cover this in depth in the upcoming [Chapter 7, Configuration Management](/articles/configuration-management-in-spring-boot) chapter.\n\n**`resources/static`** — dedicated to static assets served as-is, such as CSS, JS, and images.\n\n**`resources/templates`** — the default location for server-side view templates that render dynamic HTML. Spring Boot natively supports:\n\n-   **Thymeleaf:** the default template engine in Spring Boot, activated through the `spring-boot-starter-thymeleaf` starter dependency.\n-   **FreeMarker:** activated using the `spring-boot-starter-freemarker` starter dependency.\n-   **Mustache:** a logic-less templating engine, activated via the `spring-boot-starter-mustache` dependency.\n\nAll of these template engines automatically resolve template files from `resources/templates`.\n\n### The `src/test/java` Directory\n\nThis directory contains the unit and integration test classes for your project, mirroring the same package structure as `src/main/java`. Spring Initializr already generated a starter test class, `HelloSpringApplicationTests`, that simply verifies the application context loads successfully. We'll write our own tests in [Chapter 24, Testing Spring Boot REST API using Mockito and MockMvc](/articles/testing-spring-boot-using-mockito-and-mockmvc).\n\n## Summary\n\nIn this chapter, we walked through every file and folder Spring Initializr generated for us. In the next chapter, we'll look at [Dependency Injection in Spring Boot](/articles/dependency-injection-in-spring-boot), one of the core concepts that makes Spring Boot applications easy to build and test.\n"])</script>
1<script>self.__next_f.push([1,"34:T2c1c,"])</script>
1<script>self.__next_f.push([1,"\nIn the [previous chapter](/articles/configuration-management-in-spring-boot), we saw how Spring Boot loads configuration from properties and profiles. Logging works the same way — it's just another set of properties you set in `application.properties` file.\n\nLogging is the process of recording events as they occur within your application. The purpose of logging is to create a record of what happened in an application. These events can be anything from errors, warnings or informational messages.\n\nApplication logs can be used for a variety of purposes, including:\n-   Debugging or troubleshooting applications\n-   Monitoring real-time metrics such as CPU usage, API response time, etc.\n-   Auditing the activities of a Java application\n\n## Logging in Spring Boot\n\nMost applications provide some form of logging, and even if your application doesn't log anything directly, the dependencies used within your application will certainly log their activity.\n\nTo implement logging in your Spring Boot application, you don't have to do any additional configuration as it is built into the Spring Boot framework.\n\nThe Logging library is the only mandatory external dependency in the Spring Boot framework.\n\nA log message generally contains the following information:\n-   Date and Time: Millisecond precision and easily sortable.\n-   Log Level: `ERROR`, `WARN`, `INFO`, `DEBUG`, or `TRACE`.\n-   Process ID.\n-   A `--` separator to distinguish the start of actual log messages.\n-   Thread name: Enclosed in square brackets (Sometimes it is truncated for console output).\n-   Logger name: This is usually the class name where the log is printed from\n-   The log message.\n\n### Logging Facade (SLF4J)\n\nThe logging dependencies in Spring Boot include a Simple Logging Facade (SLF4J) and the Logback framework.\n\nThe SLF4J is a simple front-facing facade supported by all major Java logging frameworks. The SLF4J provides a unified API for logging, which helps developers use the same logging API regardless of the underlying logging framework.\n\nApplications will integrate directly with the Facade and hence it is easy to switch from one logging framework to another without breaking your implementation.\n\nThe facade includes the necessary bridges to ensure your application logs are delegated to the corresponding logging framework as per the configuration.\n\nThis is exactly the kind of thing starter dependencies handle for you, the way 
1we saw back in [Chapter 1](/articles/introduction-to-spring-boot-framework) — adding `spring-boot-starter-web` is enough to pull in the whole logging stack transitively:\n\n```mermaid\ngraph TD\n    A[\"spring-boot-starter-web\"] --\u003e B[\"spring-boot-starter\"]\n    B --\u003e C[\"spring-boot-starter-logging\"]\n    C --\u003e D[\"logback-classic\"]\n    C --\u003e E[\"jul-to-slf4j\"]\n    D --\u003e F[\"slf4j-api\"]\n    D --\u003e G[\"logback-core\"]\n```\n\n`jul-to-slf4j` is a bridge — it catches log calls made through Java's built-in `java.util.logging` (used by some third-party libraries) and routes them through SLF4J too, so everything ends up going through the same pipeline no matter which logging API a dependency happens to use internally.\n\n### Logging Frameworks\n\nThese are some of the most popular logging frameworks used in Spring Boot:\n\n-   Log4j\n-   Logback\n-   Log4j 2\n-   Apache Commons Logging\n\nAll of the above frameworks are compatible with SLF4J.\n\nPutting it all together, here's how the pieces fit at runtime:\n\n```mermaid\ngraph LR\n    A[\"Your code\u003cbr/\u003elogger.info(...)\"] --\u003e B[\"SLF4J API\u003cbr/\u003e(facade)\"]\n    L[\"Third-party library\u003cbr/\u003eusing JUL / Commons Logging\"] -.-\u003e|bridge| B\n    B --\u003e C[\"Logback\u003cbr/\u003e(default binding)\"]\n    B -.-\u003e|swappable for| D[\"Log4j2\"]\n    C --\u003e E[\"Console Appender\"]\n    C --\u003e F[\"File Appender\"]\n```\n\nYour code and any third-party libraries only ever talk to the SLF4J API — never to Logback directly. Logback is just the binding that happens to be plugged in by default, and it's the thing that decides where a log line actually ends up: the console, a file, or both, depending on your appender configuration. \n\n### Log Levels\n\nLog levels indicate the severity/importance of the log event. Here is the list of log levels used by SLF4J:\n\n| Log Level | Purpose |\n| --- | --- |\n| TRACE | Used for debugging purposes. It includes the most detailed information. |\n| DEBUG | Used for debugging purposes |\n| INFO | Used for the normal, expected, relevant event that happened. |\n| WARN | Used to log events caused due to application anomalies, which are auto-recoverable. For example, the DB connection temporarily dropped but auto-connected during the retry. |\n| ERROR | Used in the event of any fatal errors. These errors will force the administrator's intervention. These are usually used for incorrect connection strings, missing services, etc. |\n| FATAL | The FATAL level designates severe error events that presumably lead the application to abort. Note that the Logback framework does not have a FATAL level. It is mapped to ERROR. |\n| OFF | This is a special log level. It has the highest priority and is intended to turn off logging. |\n| ALL | This is a special log level. It has the lowest priority and is intended to turn on all logging. |\n\n## Logging an Event in Spring Boot\n\nLet's add some log statements to our `HelloSpringApplication` class, the same one we've been building since Chapter 3:\n\n```java\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class HelloSpringApplication {\n\n    private static final Logger logger = LoggerFactory.getLogger(HelloSpringApplication.class);\n\n    public static void main(String[] args) {\n        SpringApplication.run(HelloSpringApplication.class, args);\n\n        logger.trace(\"TRACE message\");\n        logger.debug(\"DEBUG message\");\n        logger.info(\"INFO message\");\n        logger.warn(\"WARNING message\");\n        logger.error(\"ERROR message\");\n        logger.error(\"FATAL message\");\n    }\n}\n```\n\nINFO is the default logging level used in Spring Boot. Hence, if we run the above code, it will only log the INFO, WARN, and ERROR events. The TRACE and DEBUG messages will be suppressed.\n\n### Setting Log Level when Starting Application\n\nWe can enable the DEBUG or TRACE mode while starting our application using a `--debug` or `--trace` flag. Example:\n\n```bash\njava -jar build/libs/hello-spring-0.0.1-SNAPSHOT.jar --debug\n```\n\n### Setting Log Level for Spring Boot\n\nYou can specify `debug=true` or `trace=true` in your `application.properties` file to enable DEBUG or TRACE mode.\n\nEnabling the debug mode using the above method does not configure your application to log all messages with a `DEBUG` level. It will only allow some of the core loggers inside the Spring Boot starter to log additional messages.\n\nThe application log levels can be set from the `application.properties` file using the following properties.\n\n```properties\nlogging.level.root=WARN\nlogging.level.com.stacktips.hello_spring=TRACE\n```\n\nIf you run your application, it will print as follows:\n\n```text\n2026-08-17T10:12:53.419+00:00  INFO 12345 --- [           main] c.s.h.HelloSpringApplication  : Starting HelloSpringApplication using Java 17 with PID 12345\n2026-08-17T10:12:53.421+00:00 DEBUG 12345 --- [           main] c.s.h.HelloSpringApplication  : Running with Spring Boot v3.3.4, Spring v6.1.13\n2026-08-17T10:12:53.422+00:00  INFO 12345 --- [           main] c.s.h.HelloSpringApplication  : No active profile set, falling back to 1 default profile: \"default\"\n2026-08-17T10:12:54.235+00:00  INFO 12345 --- [           main] c.s.h.HelloSpringApplication  : Started HelloSpringApplication in 0.981 seconds\n2026-08-17T10:12:54.238+00:00 TRACE 12345 --- [           main] c.s.h.HelloSpringApplication  : TRACE message\n2026-08-17T10:12:54.238+00:00 DEBUG 12345 --- [           main] c.s.h.HelloSpringApplication  : DEBUG message\n2026-08-17T10:12:54.238+00:00  INFO 12345 --- [           main] c.s.h.HelloSpringApplication  : INFO message\n2026-08-17T10:12:54.238+00:00  WARN 12345 --- [           main] c.s.h.HelloSpringApplication  : WARNING message\n2026-08-17T10:12:54.238+00:00 ERROR 12345 --- [           main] c.s.h.HelloSpringApplication  : ERROR message\n2026-08-17T10:12:54.238+00:00 ERROR 12345 --- [           main] c.s.h.HelloSpringApplication  : FATAL message\n```\n\n### Setting Log Levels Per Profile\n\nSince log levels are just properties, the profile files we set up in the [previous chapter](/articles/configuration-management-in-spring-boot) work for logging too — no new mechanism needed. For example, you might want verbose logs in dev but quieter ones in production:\n\n**application-dev.properties**\n\n```properties\nlogging.level.com.stacktips.hello_spring=DEBUG\n```\n\n**application-prod.properties**\n\n```properties\nlogging.level.com.stacktips.hello_spring=WARN\n```\n\nWhichever profile is active decides which of these gets used, exactly as we saw with `spring.profiles.active` earlier.\n\n### Spring Boot Log File Output\n\nBy default, all logs from Spring Boot applications are printed only to the console and do not write files. If you want to write log files in addition to the console output, you need to set the following properties:\n\n```properties\n# Log file name\nlogging.file.name=myapp-log.log\n\n# It will create `spring.log` file in specified path\nlogging.file.path=/Users/nilanchala/Documents/logs\n```\n\nNote that, Spring considers either `file` or `path` property, not both. Log files are automatically rotated when they reach 10 MB size.\n\n### Dynamic Log Level Changes at Runtime\n\nSpring Boot Actuator lets you change log levels at runtime, without restarting the application — handy for debugging an issue in production without taking the app down. We'll cover Actuator in full in [Chapter 23, Working with Spring Boot Actuators](/articles/working-with-spring-boot-actuators), including how to expose and call the `/actuator/loggers` endpoint to do exactly this.\n\n## Logging Pattern Customization\n\nIf you want to customize the log pattern, you can define your custom pattern in `application.properties` file. For example, to include the class name, method, and line number in the logs:\n\n```properties\nlogging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %highlight(%-5level) --- [%15.15thread] %cyan(%logger{40}) : %msg %n\n```\n\nThis customization can include various elements, such as timestamps, log levels, thread names, logger names, and even colours for different log levels when viewed in a console that supports ANSI colours.\n\nSpring Boot also supports MDC (Mapped Diagnostic Context) for attaching context — like a request ID or a userId — to every log line. It's most useful once you're handling concurrent HTTP requests and want to trace all the log lines that belong to one specific request, so we'll cover it properly later in the course.\n\n## Summary\n\nIn this chapter, we covered how Spring Boot's logging works out of the box using SLF4J and Logback, the standard log levels, and how to change log levels globally, per profile, and at runtime via Actuator.\n\nIn the next chapter, we'll start building something with all of this: [Building Your First REST API with Spring Boot](/articles/building-your-first-rest-api-with-spring-boot).\n"])</script>
1<script>self.__next_f.push([1,"35:T2e83,"])</script>
1<script>self.__next_f.push([1,"\nIn the [previous chapter](/articles/understanding-spring-boot-project-structure), we saw that `@SpringBootApplication` bundles `@ComponentScan` to automatically detect and register your Spring beans. In this chapter, we'll unpack what that actually means — how Spring registers beans, and the different ways it injects them into the classes that need them.\n\nBefore diving into the definition of DI, let us see how we manage dependencies traditionally in Java without using Spring Dependency Injection.\n\n```java\npublic class UserService {\n    final Logger logger = LoggerFactory.getLogger(UserService.class);\n\n    private final EmailService emailService;\n    private final UserRepository userRepository;\n\n    public UserService() {\n        this.emailService = new EmailService();\n        this.userRepository = new UserRepository();\n    }\n\n    public void registerUser(User user) {\n        userRepository.saveUser(user);\n\n        emailService.emailUser(\"User registered successfully!\",\n                user.getEmail());\n    }\n}\n```\n\nIn the above code snippet, the `UserService` class has the `registerUser()` method, which is used to create a user and then send an email notification.\n\nHence the `UserService` class defines the `EmailService` and `UserRepository` member variables, and they are instantiated within the default constructor of the `UserService` class.\n\nThe challenge with the above code is:\n\n-   It creates a hard-coded dependency of `UserRepository` and `EmailService` within your `UserService` class.\n-   The creation and usage of dependencies are tightly intertwined. If there are any changes to the `UserRepository` or `EmailService`, we need to modify the `UserService` implementation.\n-   This can make our code difficult to test as we cannot easily mock the `UserRepository` and `EmailService` instances.\n\nThe testing challenges can be addressed by refactoring the `UserService` to have a constructor that passes two arguments.\n\n```java\npublic class UserService {\n    final Logger logger = LoggerFactory.getLogger(UserService.class);\n\n    private final EmailService emailService;\n    private final UserRepository userRepository;\n\n    public UserService(EmailService emailService, UserRepository userRepository) {\n        this.emailService = emailService;\n        this.userRepository = userRepository;\n    }\n\n    public void registerUser(User user) {\n        userRepository.saveUser(user);\n\n        emailService.emailUser(\"User registered successfully!\",\n                user.getEmail());\n    }\n}\n```\n\nNow we can inject the mocks and do our testing, but this does not solve the real problem, as it is just moving the issue from one place to another.\n\nAs the number of dependencies and classes grows, manually managing dependencies can lead to a lot of repetitive code, which can be error-prone and increase the maintenance burden.\n\nIn essence, while it is technically possible to write your application without a Dependency Injection (DI) container, it becomes cumbersome, less maintainable, and error-prone as your application becomes more complex.\n\nThis is where the Dependency Injection comes to the rescue.\n\n## What is DI?\n\nDI is a software design pattern used in object-oriented programming, where the dependencies of a class are provided by an external entity rather than being created within the class itself.\n\nIn other words, instead of a class creating and managing its dependencies, those dependencies are created and managed outside but, are \"injected\" into your class whenever you need it.\n\nThe main idea behind Dependency Injection is to decouple the bean instantiation process from your actual business logic implementation.\n\n## Dependency Injection (DI) in Spring\n\nDependency Injection (DI) is one of the core concepts of the Spring Framework. It is achieved through the Spring Framework's Inversion of Control (IoC) container. This allows the loose coupling of components and object creation and disposal responsibility is handed over to the spring container.\n\n![Spring Dependency Injection overview](/media/summernote/dependency-injection.jpg)\n\nAny object in the Spring framework that is initialized through the Spring container is called Spring Bean.\n\nDependency Injection works in a two-step approach:\n\n-   **Bean identification/registration** — telling Spring which classes instances should be instantiated and managed by spring\
1n-   **Bean injection** — telling Spring where those beans should be plugged in\n\nThe two steps use different annotations and are easy to conflate as a beginner: registration annotations like `@Service` or `@Component` tell Spring *\"this class should become a bean\"*, while `@Autowired` tells Spring *\"inject an already-registered bean here.\"* You'll always need both of these steps.\n\n### Bean Identification/ Bean Registration\n\nBean identification refers to the way beans are identified within the Spring IoC container. Each bean is given a unique identifier that can be used to reference it later within the spring application context.\n\nIn Spring, this can be done using a XML configuration, Java Configuration or annotation-based configuration:\n\n#### XML Schema Based Configuration:\n\nSpring Beans can be explicitly defined in an XML configuration file. The Spring IOC reads the XML file and registers all the beans defined.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cbeans xmlns=\"http://www.springframework.org/schema/beans\"\n    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xsi:schemaLocation=\"http://www.springframework.org/schema/beans\n    http://www.springframework.org/schema/beans/spring-beans.xsd\"\u003e\n\n    \u003cbean id=\"userService\" class=\"com.stacktips.app.service.UserService\"\u003e\n        \u003c!-- Configure properties and dependencies needed --\u003e\n    \u003c/bean\u003e\n\u003c/beans\u003e\n```\n\nThe downside of using XML configurations is they are not type-safe, meaning errors can be introduced that won't be caught until runtime.\n\n#### Java Configuration:\n\nUsing Java-based configuration, beans are defined in a configuration class using the `@Bean` annotation. The configuration class marked with `@Configuration` annotation. It indicates that the class contains one or more bean definitions containing `@Bean` annotations.\n\nFor example:\n\n```java\n@Configuration\npublic class AppConfig {\n\n    @Bean\n    public EmailService emailService() {\n        return new EmailService();\n    }\n\n    @Bean\n    public UserService userService(EmailService emailService) {\n        return new UserService(emailService);\n    }\n}\n```\n\n#### Annotation-based configuration:\n\nSpring also provides a component scanning feature, using which spring automatically detect and registers the spring managed beans.\n\nThe `@ComponentScan` annotation, searches for all classes that are marked with stereotypes such as `@Service`, `@Component`, `@Repository`, or `@Configuration` annotation, and does the bean registration automatically.\n\nFor example, if you have a package `com.stacktips.app` that contains Spring-managed components, you can use `@ComponentScan` to register all of them with the Spring container.\n\n```java\n@Configuration\n@ComponentScan(\"com.stacktips.app\")\npublic class AppConfig {\n\n}\n```\n\n#### Bean Identification in Spring Boot:\n\nIn Spring Boot, bean registration is typically done automatically using the `@ComponentScan` annotation rather than an explicit XML or Java configuration. As we saw in the [previous chapter](/articles/understanding-spring-boot-project-structure), `@ComponentScan` is already wrapped inside `@SpringBootApplication`.\n\nSince every Spring Boot application's main class is already annotated with `@SpringBootApplication`, we don't have to add `@ComponentScan` explicitly. It performs component scanning starting from the package of your main class.\n\nHence, in case of Spring Boot, all we need to do is to use appropriate stereotypes for our classes.\n\n```java\n@Service\npublic class UserService {\n    // Your UserService implementation here\n}\n```\n\n### Bean Injection\n\nBean Injection is the process by which, one object (the dependency) is passed to another object that needs it (the dependent), rather than the dependent object needing to create the dependency itself.\n\nThere are 3 main types of bean injection in Spring Boot\n\n1.  Field Injection\n2.  Constructor Injection\n3.  Setter Method injection\n\n#### Field Injection\n\nIn Field Injection, the dependencies are injected directly into the component's fields using the `@Autowired` annotation.\n\n```java\n@Service\npublic class MyService {\n\n    @Autowired\n    private MyRepository myRepository;\n\n    // Your UserService implementation here\n}\n```\n\nThis approach is convenient but, due to direct field access it poses testing challenges;\n\n#### Constructor Injection\n\nUsing constructor injection, the dependencies are injected through a component's constructor. The `@Autowired` annotation can be used on the constructor to indicate that a dependency should be injected into the constructor.\n\n```java\n@Service\npublic class MyService {\n    private final MyRepository myRepository;\n\n    @Autowired\n    public MyService(MyRepository myRepository) {\n        this.myRepository = myRepository;\n    }\n}\n```\n\nStarting with Spring _4.3_, if a class, which is configured as a Spring bean, has only one constructor, the `@Autowired` annotation can be omitted and Spring will automatically inject all required dependencies.\n\nIf you have multiple overloaded constructors, we need to specify one of the constructors using `@Autowired` annotation.\n\n#### Setter Method Injection\n\nThe Setter Injection allows for the modification of an object's depen
1dencies after it has been constructed. This can be useful when an object's dependencies need to change dynamically at runtime.\n\nIt's more suitable for optional dependencies that can have default values or can be set to `null`.\n\n```java\n@Service\npublic class MyService {\n    private MyRepository myRepository;\n\n    @Autowired\n    public void setMyRepository(MyRepository myRepository) {\n        this.myRepository = myRepository;\n    }\n}\n```\n\nNote that the field can no longer be declared `final` here — unlike constructor injection, the field is set after the object is constructed, so Java won't allow `final` on it. This is also exactly why setter injection carries a risk that field injection and constructor injection don't: the object can be used before all of its dependencies are set, which can lead to `NullPointerExceptions`.\n\n### Which Injection Type Should You Use?\n\nOf the three, **constructor injection is the recommended** for required dependencies.\n\n-   It lets you declare dependencies as `final`, so they can't accidentally be reassigned or left unset after construction.\n-   A bean is either fully constructed with everything it needs, or it fails to start — you find out immediately at startup instead of getting the `NullPointerException` at runtime.\n-   It's the easiest to unit test without a Spring container at all, since you can just call `new MyService(mockRepository)`\n\nField injection seems convenient, but it hides a class's dependencies from anyone reading its public API and makes it harder to test without using Java reflection. Use setter injection only when a dependency is optional.\n\n\u003e If you end up with two beans that implement the same interface, Spring won't know which one to inject and will throw an error. In such cases, you will require to use `@Qualifier` and `@Primary` annotations to resolve that. \n\n## Summary\n\nIn this chapter, we saw why manually wiring up dependencies gets error-prone as an application grows, and how Spring's Dependency Injection solves it through its IoC container. We covered how beans get registered and different ways to inject beans.\n\nIn the next chapter, we'll look at [Most Commonly Used Annotations in Spring Boot](/articles/spring-boot-annotations), including a closer look at the `@Component`, `@Service`, and `@Repository` stereotypes we used throughout this chapter.\n"])</script>
1<script>self.__next_f.push([1,"36:T2043,"])</script>
1<script>self.__next_f.push([1,"\nTestcontainers are the lightweight, throwaway container instances, used for common test cases like testing against a database, ActiveMQ or anything else that can run in a Docker container.\n\nTestcontainers allows you to run your tests against a real instance of your application's dependencies, such as a real database, rather than against a mock or an in-memory database. We can configure the Testcontainers to closely mimic the production environment by using the specific versions of your your dependencies and pre-load with test data .\n\nIt spins up a new container instance for each tests, hence every tests are completely isolated from each other.\n\nFor running tests using the Testcontainers, we need to have the docker is up and running, no other dependencies are required.\n\nLet us see the following Repository,\n\nWe have defined a `searchMovies()` method that uses `MongoTemplate` to perform search by different search criteria's.\n\n```java\n@Repository\npublic class MovieRepository {\n\n    private final MongoTemplate mongoTemplate;\n\n    public MovieRepository(MongoTemplate mongoTemplate) {\n        this.mongoTemplate = mongoTemplate;\n    }\n\n    public List\u003cMovie\u003e searchMovies(SearchRequest searchRequest) {\n        Query query = new Query();\n        if (null != searchRequest.rating()) {\n            query.addCriteria(Criteria.where(\"rating\")\n                .is(searchRequest.rating()));\n        }\n\n        if (null != searchRequest.language()) {\n            query.addCriteria(Criteria.where(\"language\")\n                .is(searchRequest.language()));\n        }\n\n        if (null != searchRequest.genre()) {\n            query.addCriteria(Criteria.where(\"genres\")\n                .is(searchRequest.genre()));\n        }\n\n        return mongoTemplate.find(query, Movie.class);\n    }\n}\n```\n\n## Add Testcontainers Dependency\n\nBefore we begin, we need to ensure we have the necessary test container dependency added to your `pom.xml` or `build.gradle` file.\n\n```groovy\ntestImplementation 'org.springframework.boot:spring-boot-testcontainers'\ntestImplementation \"org.testcontainers:junit-jupiter:1.19.6\"\ntestImplementation \"org.testcontainers:mongodb:1.19.6\"\n```\n\n## Configure Testcontainer\n\nCreate a test configuration class that starts a MongoDB container. This will be used for testing our Repository that uses `MongoTemplate` for performing MongoDB operations.\n\n```java\n@Testcontainers\n@DataMongoTest(includeFilters = @ComponentScan.Filter(Repository.class))\nclass MovieRepositoryTest {\n\n    @Autowired\n    MovieRepository repository;\n    @Autowired\n    MongoTemplate mongoTemplate;\n\n    @Container\n    static final MongoDBContainer mongoDbContainer = new MongoDBContainer(\"mongo:latest\")\n            .withExposedPorts(27017);\n\n    @DynamicPropertySource\n    static void setProperties(DynamicPropertyRegistry registry) {\n        registry.add(\"spring.data.mongodb.host\", mongoDbContainer::getHost);\n        registry.add(\"spring.data.mongodb.port\", mongoDbContainer::getFirstMappedPort);\n        registry.add(\"spring.data.mongodb.username\", () -\u003e \"test_user\");\n        registry.add(\"spring.data.mongodb.password\", () -\u003e \"test_password\");\n        registry.add(\"spring.data.mongodb.database\", () -\u003e \"movies_db\");\n        registry.add(\"spring.data.mongodb.uri\", mongoDbContainer::getReplicaSetUrl);\n    }\n\n    static {\n        mongoDbContainer.start();\n    }\n}\n```\n\n## Preload MongoDB Testcontainer with Test Data\n\nWe can preload the MongoDB Testcontainer with test data. To do that we need to create an initialization script in `/test/resources` directory. Lets call it `init-schema.js`.\n\n**init-schema.js**\n\n```javascript\ndb = db.getSiblingDB('movies_db');\n\ndb.movies.insertMany([\n    {\n        \"title\": \"Iron Man \u0026 Captain America: Heroes United\",\n        \"headline\": \"Iron Man (Adrian Pasdar) and Captain America ...\",\n        \"thumbnail\": \"https://flxt.tmsimg.com/assets/p10906420_v_h9_aa.jpg\",\n        \"language\": \"EN\",\n        \"region\": \"USA\",\n        \"actors\": [\n            \"David Kaye\",\n            \"Ian McKellen\",\n            \"Adrian Pasdar\"\n        ],\n        \"genre\": \"Adventure\",\n        \"rating\": \"G\",\n    },\n    {\n        \"title\": \"Transformers: Rise of the Beasts\",\n        \"headline\": \"Transformers: Rise of the Beasts will take audiences on a\",\n        \"thumbnail\": \"https://flxt.tmsimg.com/assets/p20201199_v_h9_am.jpg\",\n        \"language\": \"EN\",\n        \"region\": \"USA\",\n        \"actors\": [\n            \"David Kaye\",\n            \"Ian McKellen\",\n            \"Adrian Pasdar\"\n        ],\n        \"genres\": \"Action\",\n        \"rating\": \"G\"\n    },\n]);\n```\n\nFor `init-schema.js` to work, we need to use `withCopyFileToContainer()` method. The `withCopyFileToContainer()` method allows moving the initialization script to a location inside the container.\n\n```java\n@Container\nstatic final MongoDBContainer mongoDbContainer = new MongoDBContainer(\"mongo:latest\")\n        .withExposedPorts(27017)\n        .withCopyFileToContainer(MountableFile.forClasspathResource(\"./init-schema.js\"),\n                \"/docker-entrypoint-initdb.d/init-script.
1js\");\n```\n\n## Testing Repository using Testcontainer\n\nNow that we have setup the test container and our initialization script is ready, let us now use the Testcontainer instance to write some unit tests.\n\nHere is how our `MovieRepositoryTest` class look like:\n\n```java\nimport com.stacktips.movies.dto.SearchRequest;\nimport com.stacktips.movies.models.ContentRating;\nimport com.stacktips.movies.models.Movie;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.data.mongodb.core.MongoTemplate;\nimport org.springframework.stereotype.Repository;\nimport org.springframework.test.context.DynamicPropertyRegistry;\nimport org.springframework.test.context.DynamicPropertySource;\nimport org.testcontainers.containers.MongoDBContainer;\nimport org.testcontainers.junit.jupiter.Container;\nimport org.testcontainers.junit.jupiter.Testcontainers;\nimport org.testcontainers.utility.MountableFile;\n\nimport java.util.List;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.core.Is.is;\n\n@Testcontainers\n@DataMongoTest(includeFilters = @ComponentScan.Filter(Repository.class))\nclass MovieRepositoryTest {\n\n    @Autowired\n    MovieRepository repository;\n    @Autowired\n    MongoTemplate mongoTemplate;\n\n    @Container\n    static final MongoDBContainer mongoDbContainer = new MongoDBContainer(\"mongo:latest\")\n            .withExposedPorts(27017)\n            .withCopyFileToContainer(MountableFile.forClasspathResource(\"./init-schema.js\"),\n                    \"/docker-entrypoint-initdb.d/init-script.js\");\n\n    @DynamicPropertySource\n    static void setProperties(DynamicPropertyRegistry registry) {\n        registry.add(\"spring.data.mongodb.host\", mongoDbContainer::getHost);\n        registry.add(\"spring.data.mongodb.port\", mongoDbContainer::getFirstMappedPort);\n        registry.add(\"spring.data.mongodb.username\", () -\u003e \"test_user\");\n        registry.add(\"spring.data.mongodb.password\", () -\u003e \"test_password\");\n        registry.add(\"spring.data.mongodb.database\", () -\u003e \"movies_db\");\n        registry.add(\"spring.data.mongodb.uri\", mongoDbContainer::getReplicaSetUrl);\n    }\n\n    static {\n        mongoDbContainer.start();\n    }\n\n    @Test\n    void testMoviesCount() {\n        List\u003cMovie\u003e movies = mongoTemplate.findAll(Movie.class);\n        assertThat(4, is(movies.size()));\n    }\n\n    @Test\n    void testSearchMovies() {\n        SearchRequest searchRequest = new SearchRequest(ContentRating.G, \"EN\", \"Action\");\n        List\u003cMovie\u003e movies = repository.searchMovies(searchRequest);\n        assertThat(2, is(movies.size()));\n        assertThat(movies.get(0).title(), is(\"Transformers: Rise of the Beasts\"));\n        assertThat(movies.get(0).language(), is(\"EN\"));\n        assertThat(movies.get(0).region(), is(\"USA\"));\n        assertThat(movies.get(0).rating(), is(ContentRating.valueOf(\"G\")));\n    }\n}\n```\n\nFor the complete project source code check out the download link.\n\nIf you have any questions, write down in the comment section below. Will be happy to respond, soon as I can.\n"])</script>
1<script>self.__next_f.push([1,"37:T2e11,"])</script>
1<script>self.__next_f.push([1,"\nIf you have multiple implementations of the same interface, Spring needs to know which bean to inject into a class.\n\nIn this article we will explore what are the different approaches to inject beans conditionally when you have multiple implantation of an component or service.\n\nLet's us explore this example, we have 2 mail sender implementation, one using SES and other using default mail sender. For sake of simplicity, we have skipped the sending the actual mail, instead it logs which sender service is invoked.\n\n```java\npublic interface MailSender {\n\n    void sendMail(String from, String to, String subject);\n}\n\n@Service\npublic class DefaultMailSender implements MailSender {\n    private final Logger logger = LoggerFactory.getLogger(DefaultMailSender.class);\n\n    @Override\n    public void sendMail(String from, String to, String subject) {\n        logger.info(\"Sending email using DefaultMailSender\");\n    }\n}\n\n@Service\npublic class SesMailSender implements MailSender {\n    private final Logger logger = LoggerFactory.getLogger(HttpMailSender.class);\n\n    @Override\n    public void sendMail(String from, String to, String subject) {\n        logger.info(\"Sending email using SesMailSender\");\n    }\n}\n```\n\nAnd in our MainApplication class, we have injected bean of `MailSender` class using constructor injection.\n\n```java\n@SpringBootApplication\npublic class MyApplication implements CommandLineRunner {\n\n    private final MailSender mailSender;\n\n    public MyApplication(MailSender mailSender) {\n        this.mailSender = mailSender;\n    }\n\n    @Override\n    public void run(String... args) throws Exception {\n        mailSender.sendMail(\"[email protected]\", \"[email protected]\", \"Test mail\");\n    }\n\n    public static void main(String[] args) {\n        SpringApplication.run(MyApplication.class, args);\n    }\n}\n```\n\nWhen you run the application, it will return the following error;\n\n```text\n***************************\nAPPLICATION FAILED TO START\n***************************\n\nDescription:\n\nParameter 0 of constructor in com.stacktips.app.MyApplication required a single bean, but 2 were found:\n    - defaultMailSender: defined in file [/Users/nilanchala/Documents/spring-boot-conditional-bean/build/classes/java/main/com/stacktips/app/service/DefaultMailSender.class]\n    - sesMailSender: defined in file [/Users/nilanchala/Documents/spring-boot-conditional-bean/build/classes/java/main/com/stacktips/app/service/SesMailSender.class]\n\nThis may be due to missing parameter name information\n\nAction:\n\nConsider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed\n```\n\nIt is because, as we have two implementations of the `EmailSender`, spring cannot determine which implementation to inject for `sendMail()` method invocation.\n\nWe have different options available to let spring know which implementation to choose. Let's explore.\n\n### Option-1: Using @Primary Bean Annotation\n\nWhen there are several bean implementations available, we can choose the primary bean candidate using the `@Primary` annotation.\n\nFor example;\n\n```java\n@Primary\n@Service\npublic class DefaultMailSender implements MailSender {\n\n    private final Logger logger = LoggerFactory.getLogger(DefaultMailSender.class);\n\n    @Override\n    public void sendMail(String from, String to, String subject) {\n        logger.info(\"Sending email using DefaultMailSender\");\n    }\n}\n```\n\nWith this, Spring will inject the bean of `DefaultMailSender`.\n\n### Option-2: Autowiring using @Qualifier\n\nThe `@Primary` annotation provides limited control over the bean type selection. When you need more control over the selection process, we can use the `@Qualifier` annotation.\n\nYou can associate qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument.\n\nFor example;\n\n```java\n@SpringBootApplication\npublic class MyApplication implements CommandLineRunner {\n\n    private final MailSender mailSender;\n\n    public MyApplication(@Qualifier(\"sesMailSender\") MailSender mailSender) {\n        this.mailSender = mailSender;\n    }\n\n    @Override\n    public void run(String... args) throws Exception {\n        mailSender.sendMail(\"[email protected]\", \"[email protected]\", \"Test mail\");\n    }\n\n    public static void main(String[] args) {\n        SpringApplication.run(MyApplication.class, args);\n    }\n}\n```\n\nAs we are specifying `@Qualifier(\"sesMailSender\")`, Spring will now inject the `sesMailSender` bean.\n\n### Option-3: Using ApplicationContext to Dynamically Select Beans\n\nBoth approaches defined above uses static approach to inject bean types. To achieve dynamic bean selection based on certain conditions, we can use `@Autowired` in combination with `ApplicationContext`.\n\nLet us create a factory class `EmailService`:\n\n```java\n@Component\npublic class MailService {\n\n    private final Ap
1plicationContext context;\n\n    public MailService(ApplicationContext context) {\n        this.context = context;\n    }\n\n    public MailSender getMailSender(String type) {\n        if (\"ses\".equals(type)) {\n            return context.getBean(\"sesMailSender\", SesMailSender.class);\n        }\n\n        return context.getBean(\"defaultMailSender\", DefaultMailSender.class);\n    }\n\n    public void sendMail(String from, String to, String subject) {\n        getMailSender(\"ses\").sendMail(from, to, subject);\n    }\n}\n```\n\nNow in our `MainApplication` class, instead of injecting `MailSender` bean, we can use `MailService` type instead.\n\n```java\n@SpringBootApplication\npublic class MyApplication implements CommandLineRunner {\n\n    private final MailService mailService;\n\n    public MyApplication(MailService mailService) {\n        this.mailService = mailService;\n    }\n\n    @Override\n    public void run(String... args) throws Exception {\n        mailService.sendMail(\"[email protected]\", \"[email protected]\", \"Test mail\");\n    }\n\n    public static void main(String[] args) {\n        SpringApplication.run(MyApplication.class, args);\n    }\n}\n```\n\n### Option-4: Custom Annotation and Bean Factory\n\nAnother approach is to create a custom annotation and a factory that uses this annotation to decide which bean to inject dynamically based on certain conditions.\n\nThis is similar to Option-4, but using the custom annotation. This approach offers greater flexibility and keeps your code clean.\n\nLet us first define a custom annotation:\n\n```java\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n@Target(ElementType.TYPE)\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface MailSenderSelector {\n\n    String value();\n}\n```\n\nNow use the annotation in your `MailSender` services\n\n```java\n@Service\n@MailSenderSelector(\"default\")\npublic class DefaultMailSender implements MailSender {\n\n    private final Logger logger = LoggerFactory.getLogger(DefaultMailSender.class);\n\n    @Override\n    public void sendMail(String from, String to, String subject) {\n        logger.info(\"Sending email using DefaultMailSender\");\n    }\n}\n\n@Service\n@MailSenderSelector(\"ses\")\npublic class SesMailSender implements MailSender {\n\n    private final Logger logger = LoggerFactory.getLogger(SesMailSender.class);\n\n    @Override\n    public void sendMail(String from, String to, String subject) {\n        logger.info(\"Sending email using SesMailSender\");\n    }\n}\n```\n\nNow we will implement a bean factory that checks this condition at runtime and selects the appropriate bean types based on the argument passed to the annotation.\n\n```java\n@Component\npublic class MailService {\n\n    private final ApplicationContext context;\n\n    public MailService(ApplicationContext context) {\n        this.context = context;\n    }\n\n    public MailSender getMailSender(String type) {\n        Map\u003cString, Object\u003e beansWithAnnotation = context.getBeansWithAnnotation(MailSenderSelector.class);\n        Optional\u003cObject\u003e matchingBean = beansWithAnnotation.values().stream()\n                .filter(bean -\u003e bean.getClass().getAnnotation(MailSenderSelector.class).value().equals(type))\n                .findFirst();\n\n        if (matchingBean.isEmpty()) {\n            throw new IllegalArgumentException(\"No bean found for type: \" + type);\n        }\n\n        return (MailSender) matchingBean.get();\n    }\n\n    public void sendMail(String from, String to, String subject) {\n        getMailSender(\"ses\").sendMail(from, to, subject);\n    }\n}\n```\n\n### Option-5: Bean Selection Using Custom Conditions\n\nAnother approach is to define custom conditions to match the bean types to inject. This method determines whether a condition is met based on the application context and metadata.\n\n```java\nimport org.springframework.context.annotation.Condition;\nimport org.springframework.context.annotation.ConditionContext;\nimport org.springframework.core.type.AnnotatedTypeMetadata;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class DefaultMailSenderCondition implements Condition {\n\n    @Override\n    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {\
1n        String mailSender = context.getEnvironment().getProperty(\"email.mail-sender\");\n        return null== mailSender || mailSender.trim().equals(\"default\");\n    }\n}\n\n@Component\npublic class SesMailSenderCondition implements Condition {\n\n    @Override\n    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {\n        String mailSender = context.getEnvironment().getProperty(\"email.mail-sender\");\n        return null != mailSender \u0026\u0026 mailSender.trim().equals(\"ses\");\n    }\n}\n```\n\nThe two conditions above uses the `email.mail-sender` application property value to determine the bean type to inject.\n\n**application.properties**\n\n```properties\n#default or ses\nemail.mail-sender=ses\n```\n\nIn this case, the condition for `SesMailSender` will be true, and thus, `SesMailSender` will be the active implementation of `MailSender` in the application context.\n\nNow from mail sender implementations, we can use `@Conditional` annotation by passing the corresponding condition that dictates which bean should be registered.\n\n```java\npublic interface MailSender {\n    void sendMail(String from, String to, String subject);\n}\n\n@Primary\n@Component\n@Conditional(DefaultMailSenderCondition.class)\npublic class DefaultMailSender implements MailSender {\n\n    private final Logger logger = LoggerFactory.getLogger(DefaultMailSender.class);\n\n    @Override\n    public void sendMail(String from, String to, String subject) {\n        logger.info(\"Sending email using DefaultMailSender\");\n    }\n}\n\n@Service\n@Conditional(SesMailSenderCondition.class)\npublic class SesMailSender implements MailSender {\n\n    private final Logger logger = LoggerFactory.getLogger(SesMailSender.class);\n\n    @Override\n    public void sendMail(String from, String to, String subject) {\n        logger.info(\"Sending email using SesMailSender\");\n    }\n}\n```\n\nThere is no change in the main application class, we inject the `MailSender` instance using the constructor based injection.\n\n```java\n@SpringBootApplication\npublic class MyApplication implements CommandLineRunner {\n\n    private final MailSender mailSender;\n\n    public MyApplication(MailSender mailSender) {\n        this.mailSender = mailSender;\n    }\n\n    @Override\n    public void run(String... args) throws Exception {\n        mailSender.sendMail(\"[email protected]\", \"[email protected]\", \"Test mail\");\n    }\n\n    public static void main(String[] args) {\n        SpringApplication.run(MyApplication.class, args);\n    }\n}\n```\n\nFor the complete project source code check out the download link.\n\nIf you have any questions, write down in the comment section below. Will be happy to respond, soon as I can.\n"])</script>
1<script>self.__next_f.push([1,"38:T1991,"])</script>
1<script>self.__next_f.push([1,"\nIn the previous article, we integrated the [Quartz Scheduler](/articles/working-with-quartz-scheduler-in-spring-boot) in Spring boot and covered some of the basic configurations.\n\nIn this second part, we will dive into some of the advance Quartz configurations and we will create a [custom actuator](/articles/working-with-spring-boot-actuators) to manage the Quartz Job using actuator endpoints.\n\n### Actuator Dependency\n\nTo enable the Actuator endpoints, we need include the `spring-boot-starter-actuator` starter dependency to your project. If you have Gradle based project, you can add the following dependency to your `build.gradle` file.\n\n```groovy\ndependencies {\n  implementation 'org.springframework.boot:spring-boot-starter-actuator\n}\n```\n\nIf you’re using maven, you can include the following dependency on your `pom.xml` file.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-actuator\u003c/artifactId\u003e\n\u003c/dependency\u003e\n```\n\nOnce you have the dependency added to your application, Spring Boot’s auto-configuration will kick in when the application is running and Actuator will be enabled.\n\n### Custom Actuator Endpoint\n\nLet us now create a custom actuator to start, and stop scheduled jobs using actuator endpoints. To learn more about [Spring Boot actuator](https://stacktips.com/articles/working-with-spring-boot-actuators) basics, please can refer to the linked article.\n\nIn this example, we have `actuator/manage-jobs` actuator endpoint with `@WriteOperation` that accepts an `action`, `jobName` and `jobGroup` as a input parameter.\n\n```java\n@Component\n@Endpoint(id = \"manage-jobs\")\npublic class QuartzJobEndpoint {\n\n    private static final Logger log = LoggerFactory.getLogger(QuartzJobEndpoint.class);\n    private final QuartzJobService quartzJobService;\n\n    public QuartzJobEndpoint(QuartzJobService quartzJobService) {\n        this.quartzJobService = quartzJobService;\n    }\n\n    @WriteOperation\n    public void manageJob(String action, String jobName, String jobGroup) {\n        try {\n            if (\"start\".equals(action)) {\n                String triggerName = \"csvImportInterruptableJobTrigger\";\n                quartzJobService.startJob(jobName, jobGroup, triggerName);\n            } else if (\"stop\".equals(action)) {\n                quartzJobService.stopJob(jobName, jobGroup);\n            }\n        } catch (SchedulerException e) {\n            log.error(\"Error while managing job\", e);\n        }\n    }\n}\n```\n\nBy default, only the `health` endpoint is exposed over HTTP. To allow `manage-job` accessible we need to `include` the following property.\n\n```properties\nmanagement.endpoints.web.exposure.include=health,manage-jobs\n```\n\n### Service to Manage Dynamic Scheduling\n\nThe custom uses `QuartzJobService` to manage the Jobs. The service class contains following methods:\n\n-   `scheduleJob()`: Schedules a new job with the given name, group, and trigger name. It uses the `CsvImportInterruptableJob.class` for the job detail, indicating that this specific job class will be executed.\n-   `startJob()`: Starts a job if it does not already exist; otherwise, it triggers the existing job. It uses the job and group names to check for the job's existence and to trigger it.\n-   `stopJob()`: Stops and deletes a job based on its name and group. It first interrupts the job and then deletes it from the scheduler.\n-   `updateJob()`: It replaces the old trigger with a new one for the specified job based on the new cron expression.\n\nIn this example, we are using hardcoded CRON expression, the endpoint can be extended to pass the cron expression as a input.\n\n```java\nimport com.stacktips.app.tasks.CsvImportInterruptableJob;\nimport org.quartz.*;\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class QuartzJobService {\n\n    private static final String CRON_EXPRESSION = \"0/5 * * * * ?\";\n    private final Scheduler scheduler;\n\n    public QuartzJobService(Scheduler scheduler) {\n        this.scheduler = scheduler;\n    }\n\n    public void scheduleJob(String jobName, String jobGroup, String triggerName) throws SchedulerException {\n        JobDetail job = JobBuilder.newJob(CsvImportInterruptableJob.class)\n                .withIdentity(jobName, jobGroup)\n                .build();
1\n\n        Trigger trigger = TriggerBuilder.newTrigger()\n                .withIdentity(triggerName, jobGroup)\n                .startNow()\n                .withSchedule(CronScheduleBuilder.cronSchedule(CRON_EXPRESSION))\n                .build();\n\n        scheduler.scheduleJob(job, trigger);\n        if (!scheduler.isStarted()) {\n            scheduler.start();\n        }\n    }\n\n    public void startJob(String jobName, String jobGroup, String triggerName) throws SchedulerException {\n        JobKey jobKey = new JobKey(jobName, jobGroup);\n        if (!scheduler.checkExists(jobKey)) {\n            scheduleJob(jobName, jobGroup, triggerName);\n        } else {\n            scheduler.triggerJob(jobKey);\n        }\n    }\n\n    public void stopJob(String jobName, String jobGroup) throws SchedulerException {\n        JobKey jobKey = new JobKey(jobName, jobGroup);\n        scheduler.interrupt(jobKey);\n        scheduler.deleteJob(jobKey);\n    }\n\n    public void updateJob(String triggerName, String newTriggerName, String jobName, String jobGroup) throws SchedulerException {\n\n        Trigger newTrigger = TriggerBuilder.newTrigger()\n                .withIdentity(triggerName, jobGroup)\n                .startNow()\n                .withSchedule(CronScheduleBuilder.cronSchedule(CRON_EXPRESSION))\n                .build();\n\n        scheduler.rescheduleJob(TriggerKey.triggerKey(newTriggerName, jobGroup), newTrigger);\n        scheduler.deleteJob(JobKey.jobKey(jobName, jobGroup));\n    }\n\n}\n```\n\n### Using Actuator to Manage Quartz Jobs\n\nWith this we are ready to dynamically schedule our Quartz job.\n\n**To Start a Job**\n\n```bash\ncurl --location 'http://localhost:8080/actuator/manage-jobs' \\\n--header 'Content-Type: application/json' \\\n--data '{\n    \"action\":\"start\",\n    \"jobName\":\"csvjob\",\n    \"jobGroup\":\"gbgroup1\"\n}'\n```\n\n**To Stop a Job**\n\n```bash\ncurl --location 'http://localhost:8080/actuator/manage-jobs' \\\n--header 'Content-Type: application/json' \\\n--data '{\n    \"action\":\"stop\",\n    \"jobName\":\"csvjob\",\n    \"jobGroup\":\"gbgroup1\"\n}'\n```\n\n**To Update an Existing Job**\n\n```bash\ncurl --location 'http://localhost:8080/actuator/manage-jobs' \\\n--header 'Content-Type: application/json' \\\n--data '{\n    \"action\":\"start\",\n    \"jobName\":\"csvjob\",\n    \"jobGroup\":\"gbgroup1\"\n}'\n```\n"])</script>
1<script>self.__next_f.push([1,"39:T249f,"])</script>
1<script>self.__next_f.push([1,"\nQuartz Scheduler is an open-source job scheduling library that allows developers to schedule jobs to run at a certain time or based on specific events. This library eliminates the [limitations in the Spring scheduler](https://stacktips.com/articles/task-execution-and-scheduling-in-spring-boot#limitations-of-spring-scheduler).\n\nQuartz allows developers to:\n\n-   Schedule jobs to run at a specific time, or repeat at intervals - Store jobs and their triggers in a database, allowing scheduled jobs to persist between application restarts.\n-   Run in a clustered environment, allowing jobs to be distributed across a cluster of servers for load balancing or redundancy.\n-   Allows transaction management to ensure the jobs are only executed after transactions are successfully committed.\n\n## Using Quartz Scheduler Spring Boot\n\nIn the course of this article, we will cover different aspects of the Quartz Scheduler and integrate it with Spring Boot application.\n\nLet us first create a simple scheduler to import content from a CSV file using basic configurations. The [sample CSV file](https://github.com/StackTipsLab/spring-boot-tutorials/blob/main/quartz-scheduler/src/data/books.csv) containing list of books.\n\n### Quartz Starter Dependency\n\nBefore we begin, we need to add the Quartz starter dependency to our Spring boot application. For Maven add the following dependency to your `pom.xml` file.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-quartz\u003c/artifactId\u003e\n\u003c/dependency\u003e\n```\n\nIf you're using Gradle build tool, you can add the the following to your `build.gradle` file:\n\n```groovy\nimplementation 'org.springframework.boot:spring-boot-starter-quartz'`\n```\n\nThe CSV content maps to the following `Book` model. Please note, I am using [Java17 record](https://stacktips.com/articles/java-17-interview-questions-and-answers#1-what-is-the-records-in-java) for this purpose. If you're using lower version of Java, you can write a simple POJO class.\n\n```java\npublic re
1cord Book(\n        String id,\n        String isbn,\n        String isbn13,\n        String authors,\n        String publicationYear,\n        String title,\n        String languageCode,\n        Double averageRating,\n        String imageUrl) {\n}\n```\n\nTo keep the scope of this article limited to the task scheduler, we will not perform any database operations. Here is how our `ImportService` looks like:\n\n```java\n@Service\npublic class ImportService {\n\n    private static final Logger log = LoggerFactory.getLogger(ImportService.class);\n\n    public void readBooks() throws IOException, CsvException {\n        File file = new File(\"src/data/books.csv\");\n        log.info(\"Importer started!\");\n\n        try (CSVReader csvReader = new CSVReader(new FileReader(file))) {\n            final List\u003cString[]\u003e rows = csvReader.readAll();\n            List\u003cBook\u003e books = rows.stream()\n                    .skip(1)\n                    .map(row -\u003e new Book(row[0], row[1], row[2], row[3], row[4],\n                            row[5], row[6], Double.parseDouble(row[7]), row[8]))\n                    .toList();\n            log.info(\"Imported {} books\", books.size());\n        }\n\n        log.info(\"Importer completed!\");\n    }\n}\n```\n\nThe `ImporterService` is responsible for reading the CSV file, you can extend this service to do whatever logic required for your application.\n\nLet us now dive into Quartz scheduler.\n\n### Creating Quartz Job\n\nDefine a job class that implements the Quartz `Job` interface. This class will contain the logic for reading the CSV file and loading its contents into the database.\n\n```java\npublic class CsvImportJob implements Job {\n\n    private static final Logger log = LoggerFactory.getLogger(CsvImportJob.class);\n    private final ImportService importService;\n\n    public CsvImportJob(ImportService importService) {\n        this.importService = importService;\n    }\n\n    @Override\n    public void execute(JobExecutionContext context) throws JobExecutionException {\n        try {\n            JobDataMap dataMap = context.getJobDetail().getJobDataMap();\n            String param = dataMap.getString(\"arg1\");\n\n            log.info(\"CsvImportJob started with param: {}\", param);\n            importService.readBooks();\n\n        } catch (IOException e) {\n            log.error(\"IOException thrown while running job\", e);\n            throw new RuntimeException(e);\n        } catch (CsvException e) {\n            log.error(\"CsvException thrown while running job\", e);\n            throw new RuntimeException(e);\n        }\n    }\n}\n```\n\n### Cron Based Trigger\n\nNow that we have created the `CsvImportJob`, we can leverage the Spring's configuration and dependency injection capability to trigger the job.\n\nThe `spring-boot-starter-quartz` dependency automatically configures a `SchedulerFactoryBean`.\n\nThe `SchedulerFactoryBean` is a Quartz's standard factory implementation that is responsible for creating a `Scheduler` instance.\n\n```java\n@Configuration\npublic class QuartzConfig {\n\n    @Bean\n    public JobDetail csvImportJob() {\n        return JobBuilder.newJob(CsvImportJob.class)\n                .withIdentity(\"csvImportJob\")\n                .build();\n    }\n\n    @Bean\n    public Trigger csvImportJobTrigger(JobDetail csvImportJob) {\n        return TriggerBuilder.newTrigger()\n                .forJob(csvImportJob)\n                .withIdentity(\"cronTrigger\")\n                .withSchedule(CronScheduleBuilder.cronSchedule(\"0/5 * * * * ?\"))\n                .build();\n    }\n}\n```\n\nThe Quartz `Scheduler` is aware of all `JobDetail` and `Trigger` beans defined in the Spring context and automatically schedules the jobs based on the triggers associated with them.\n\nWe have used cron expression that triggers the job every 5 seconds (`\"0/5 * * * * ?\"`).\n\n### Interval Based Trigger\n\nAlong with the cron trigger, we can also schedule job to start at a specific moment in time, and optionally, repeat it at a specified interval a fixed number of times using the `SimpleScheduleBuilder`.\n\nWhen defining a interval based trigger, we need to specify the start time, repeat interval, and optionally the number of repeats.\n\n```java\n@Bean\n    public Trigger csvImportJobTrigger(JobDetail csvImportJob) {\n        // Initial delay\n        Date afterFiveSeconds = Date.from(LocalDateTime.now().plusSeconds(5)\n                .atZone(ZoneId.systemDefault()).toInstant());\n\n        return TriggerBuilder.newTrigger()\n                .forJob(csvImportJob)\n                .startAt(afterFiveSeconds) // Initial delay\n                .withIdentity(\"simpleTrigger\")\n                .withSchedule(SimpleScheduleBuilder.simpleSchedule()\n                        .withIntervalInSeconds(60)\n                        .repeatForever()
1)\n                .build();\n    }\n```\n\n\u003e \\[!NOTE\\] If you're using the Job interface for tasks, these jobs cannot be interrupted before completion. Once started, these jobs will run to completion unless an unhandled exception occurs.\n\n## Interruptable Jobs in Quartz\n\nThe `InterruptableJob` interface extends the `Job` interface and adds the ability for the job to be interrupted in the middle of execution. This is useful for long-running tasks that might need to be stopped before they complete normally.\n\nTo create an Interruptible Job, we need to implement the `InterruptableJob` interface and implement the `interrupt()` method. The `interrupt()` method is called by the Quartz Scheduler when a user interrupts the Job.\n\n```java\npublic class CsvImportInterruptableJob implements InterruptableJob {\n\n    private static final Logger log = LoggerFactory.getLogger(CsvImportInterruptableJob.class);\n\n    private final ImportService importService;\n\n    public CsvImportInterruptableJob(ImportService importService) {\n        this.importService = importService;\n    }\n\n    private volatile boolean toStop = false;\n\n    @Override\n    public void execute(JobExecutionContext context) throws JobExecutionException {\n        while (!toStop) {\n\n            try {\n                JobDataMap dataMap = context.getJobDetail().getJobDataMap();\n                String param = dataMap.getString(\"param\");\n\n                log.info(\"CsvImportInterruptableJob started with parameter: {}\", param);\n                importService.readBooks();\n\n            } catch (IOException e) {\n                log.error(\"IOException thrown while running job\", e);\n                throw new RuntimeException(e);\n            } catch (CsvException e) {\n                log.error(\"Exception thrown while running job\", e);\n                throw new RuntimeException(e);\n            }\n\n            if (Thread.interrupted()) {\n                // Perform any cleanup tasks and terminate\n                toStop = true;\n            }\n        }\n\n    }\n\n    @Override\n    public void interrupt() throws UnableToInterruptJobException {\n        toStop = true;\n    }\n}\n```\n\nThe `interrupt()` method allows the job to handle interruption requests, such as cleaning up resources or rolling back transactions, before the job stops.\n\nThis article covers the basics of Scheduler using Quartz. In the next article we will cover more advance configurations and dynamic scheduling using Spring Boot actuators.\n\nFor the complete project source code check out the download link.\n\nIf you have any questions, write down in the comment section below. Will be happy to respond, soon as I can.\n"])</script>
1<script>self.__next_f.push([1,"3a:T17ac,"])</script>
1<script>self.__next_f.push([1,"\nThe Spring Boot Actuator provides several endpoints in your application through which you can view the internals of your running application.\n\nThrough the Actuator, you can find out how beans are wired together in the Spring application context, determine what environment properties are available to your application, and get a snapshot of runtime metrics.\n\n### Enable Spring Boot Actuators\n\nTo enable the Actuator endpoints, you need include the `spring-boot-starter-actuator` starter dependency to your project. If you have Gradle based project, you can add the following dependency to your `build.gradle` file.\n\n```groovy\ndependencies {\n  implementation 'org.springframework.boot:spring-boot-starter-actuator\n}\n```\n\nIf you’re using maven, you can include the following dependency on your `pom.xml` file.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-actuator\u003c/artifactId\u003e\n\u003c/dependency\u003e\n```\n\nOnce you have the dependency added to your application, Spring Boot’s auto-configuration will kick in when the application is running and Actuator will be enabled.\n\nRun your application and visit http://localhost:8080/actuator/health\n\n### Actuator Endpoints\n\nSpring Boot includes several built-in endpoints and lets you add your custom actuator endpoints.\n\nHere is the list of available endpoints in Spring Boot:\n\n| Endpoint path | Purpose |\n| --- | --- |\n| /actuator | Returns list of enabled actuator endpoints. |\n| /actuator/health | Reports health metrics for the application, as provided by HealthIndicator implementations. |\n| /actuator/info | Retrieves custom information about the application, as pro- vided by any properties prefixed with info. |\n| /autoconfig | Provides an auto-configuration report describing what auto-configuration conditions passed and failed. |\n| /configprops | Describes how beans have been injected with configuration properties (including default values). |\n| /beans | Describes all beans in the application context and their relationship to each other. |\n| /dump | Retrieves a snapshot dump of thread activity. |\n| /env | Retrieves all environment properties. |\n| /env/{name} | Retrieves a specific environment value by name. |\n| /mappings | Describes all URI paths and how they’re mapped to controllers (including Actuator endpoints). |\n| /metrics | Reports various application metrics such as memory usage and HTTP request counters. |\n| /metrics/{name} | Reports an individual application metric by name. |\n| /shutdown | This is an HTTP POST endpoint. Shuts down the application; requires thatendpoints.shutdown.enabled be set to true. |\n| /trace | Provides basic trace information (timestamp, headers, and so on) for HTTP requests. |\n\n### Enable Actuator Endpoints\n\nYou can enable or disable each individual endpoint and expose them as per your requirement. All disabled endpoints are removed entirely from the application context.\n\nBy default, all endpoints except for `shutdown` are enabled. You can enable a specific endpoints using the `management.endpoint.\u003cendpoint_id\u003e.enabled` property.\n\nFor example, the following example enables the `shutdown` and `info` endpoint\n\n```properties\nmanagement.endpoint.shutdown.enabled=true\nmanagement.endpoint.info.enabled=true\n```\n\n### Exposing Actuator Endpoints\n\nSince endpoints may contain sensitive information about your application, you should carefully consider what endpoint is expose them.\n\nBy default, only the `health` endpoint is exposed over HTTP. To change which endpoints are exposed we can use the `include` and `exclude` property.\n\n```properties\n#Include or exclude specific endpoints. Comma seperated endpoint names\nmanagement.endpoints.web.exposure.exclude=scheduledtasks\nmanagement.endpoints.web.exposure.include=info, health\n\n#Exposes all actuator endpoints\nmanagement.endpoints.web.exposure.include=*\n```\n\n### Endpoint Caching\n\nNote that, the spring boot actuator endpoints automatically cached for read operations that do not take any parameters. To configure the amount of time for which an endpoint caches a response, we can use the following property.\n\n```properties\nmanagement.endpoint.beans.cache.time-to-live=10s\n```\n\n## Implementing Custom Actuator Endpoints\n\nTo create a custom actuator endpoint, we need to create a class with `@Component` in combination with `@Endpoint` annotation.\n\nThe methods can be annotated with `@ReadOperation`, `@WriteOperation`, or `@DeleteOperation` and are automatically exposed over HTTPS.\n\n#### Read Operation\n\nThe following example demonstrates, creating a custom actuator endpoint `/foo-bar` that supports read operation:\n\n```java\n@Component\n@Endpoint(id = \"foo-bar\")\npublic class FeaturesEndpoint {\n\n    @ReadOperation\n    public Map\u003cString, String\u003e readOperation() {\
1n        return Map.of(\"foo\", \"bar\");\n    }\n}\n```\n\nRun your application and you will visit `/actuator/foo-bar` endpoint. It will return the following response:\n\n```json\n{\n    \"foo\": \"bar\"\n}\n```\n\n#### Write Operation\n\nWe can pass the input parameter through the custom actuator endpoints as well using the `@WriteOperation` annotation.\n\n```java\n@Component\n@Endpoint(id = \"foo-bar\")\npublic class FeaturesEndpoint {\n\n    @ReadOperation\n    public Map\u003cString, String\u003e readOperation() {\n        return Map.of(\"foo\", \"bar\");\n    }\n\n    @WriteOperation\n    public Map\u003cString, String\u003e writeOperation(String param1, String param2) {\n        return Map.of(\"param1\", param1, \"param2\", param2);\n    }\n}\n```\n\nNow, we can test the endpoint as follows;\n\n```bash\ncurl --location 'http://localhost:8080/actuator/foo-bar' \\\n--header 'Content-Type: application/json' \\\n--data '{\n    \"param1\": \"Hello\",\n    \"param2\": \"World!\"\n}'\n```\n\n#### Delete Operation\n\nIn conjunction with `@ReadOperation`, `@WriteOperation` we can also use `@DeleteOperation`, which maps to the HTTP DELETE request type.\n\n```java\n@DeleteOperation\npublic Map\u003cString, Boolean\u003e deleteOperation() {\n    return Map.of(\"success\", true);\n}\n```\n\nExample:\n\n```bash\ncurl --location --request DELETE 'http://localhost:8080/actuator/foo-bar'\n```\n"])</script>
1<script>self.__next_f.push([1,"3b:T1305,"])</script>
1<script>self.__next_f.push([1,"\nThe `@ConfigurationProperties` annotation in Spring Boot is used to bind configuration parameters typically from properties or YAML files to a Java class.\n\nBut, did you know you also can validate configuration properties at spring application startup with `@ConfigurationProperties` annotation? Let's dive in!\n\nLet's say we have a Spring boot importer service that imports customer data from a CSV file to the database periodically. For the importer to work we have the following configurations:\n\n```yaml\nimporter:\n  service:\n    filePath: '/nfs/files'\n    fileType: '.xslx'\n    threadPoolSize: 3\n```\n\nThese properties can be mapped to a Java class automatically using `@ConfigurationProperties` annotation as follows:\n\n```java\n@Getter\n@Setter\n@Component\n@ConfigurationProperties(prefix = \"importer.service\")\npublic class ImporterConfig {\n    String filePath;\n    String fileType;\n    int threadPoolSize;\n}\n```\n\nNow let's say, we want to ensure the importer configuration is provided and meets the validation criteria when the application starts. If any of the validation fails, then the application should fail during startup.\n\nFor this validation to work, we need to have a **JSR-380** implementation like **_Hibernate Validator_** on your classpath.\n\n```groovy\nimplementation 'org.springframework.boot:spring-boot-starter-validation'\n```\n\nOnce we have a validator in the classpath, we need to explicitly enable the configuration properties validation using `@Validated` annotation.\n\nFor example,\n\n```java\n@Getter\n@Setter\n@Component\n@Validated\n@ConfigurationProperties(prefix = \"importer.service\")\npublic class ImporterConfig {\n\n    @NotNull\n    String filePath;\n\n    @NotNull\n    @Pattern(regexp = \"\\.csv$|\\.txt$\")\n    String fileType;\n\n    @Positive\n    @Max(10)\n    int threadPoolSize;\n}\n```\n\nThis can validate properties on application startup when used in conjunction with JSR-380 bean validation annotations such as `@Max`, and `@NotNull`. Here are some of the common annotations used for bean validation:\n\n-   @NotNull: specifies that a property must be not null\n-   @NotEmpty: specifies that a property must be not null or not empty\n-   @Size: ensure that a property size is between attributes min and max\n-   @Email: specifies that a property must be a valid email address\n-   @AssertTrue / @AssertFalse: ensure that a property value is true/false\n-   @Positive / @Negative: ensure that a property is positive/negative\n-   @Past / @Future: specifies that the date must be in the past/ future\n-   @Max / @Min: specifies that a property has a value not greater/not smaller than the value attribute\n\nA full list of built-in [validation constraints](https://beanvalidation.org/2.0-jsr380/spec/#builtinconstraints) in JSR 380 can be found here.\n\nNow, Run the application and notice that it will bind these properties from `application.yaml`to the `ImporterConfig` object and validate them at application startup, thus ensuring the application doesn't run with invalid configurations.\n\nIf the validation fails it will result in `BindException` as shown below:\n\n```text\n***************************\nAPPLICATION FAILED TO START\n***************************\n\nDescription:\n\nBinding to target com.stacktips.app.config.ImporterConfig failed:\n\n    Property: importer.service.fileType\n    Value: \".xlsx\"\n    Origin: class path resource [application.yaml] - 8:15\n    Reason: must match \".csv$|.txt$\"\n\nAction:\n\nUpdate your application's configuration\n```\n\nNow you update the `fileType: .csv` and the application will start as expected.\n\n### Considerations for Using Records\n\nStarting with Spring Boot 2.6 and Java 16 you can use record classes with `@ConfigurationProperties`. But there are a few things you need to consider when using records.\n\n```java\n@Validated\n@ConfigurationProperties(prefix = \"importer.service\")\npublic re
1cord ImporterProperties(\n        @NotNull String filePath,\n        @Min(3) int threadPoolSize) {\n}\n```\n\nThe `@Componenet` annotation cannot be used with records. Your IDE will show `annotated with @ConstructorBinding but defined as a Spring component` error.\n\nThis is because the `@Component` annotation is generally used to define a bean that the Spring container will automatically detect and manage. As Java records are immutable, it conflicts with the way Spring manages beans, which involves proxying, intercepting, and potentially altering object states or behaviour.\n\nTo fix this, we need to remove the `@Component` annotation and explicitly define the bean registration. We can either use `@EnableConfigurationProperties` or define `@Bean` annotation in one of the `@Configuration` classes.\n\nFor example:\n\n```java\n@EnableConfigurationProperties(ImporterProperties.class)\n@SpringBootApplication\npublic class MyApplication {\n\n    public static void main(String[] args) {\n       SpringApplication.run(MyApplication.class, args);\n    }\n\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"3c:T22b6,"])</script>
1<script>self.__next_f.push([1,"\nSpring Scheduler is used for running repetitive tasks or to automate tasks that need to run at specific times or at specific intervals. For example such as sending our email newsletters to your customers, generating daily reports, or updating a database.  \n\nIn this crash course, we will cover everything you need to know about Spring Scheduler – including the annotations, examples, and other things to consider.\n\n## Enable Scheduling\n\nTo enable Spring's scheduled task execution capability, just annotate any of your `@Configuration` classes with `@EnableScheduling` annotation.\n\n**Example:**\n\n```java\n@Configuration\n@EnableScheduling\npublic class SchedulerConfig {\n    // Here it goes your configuration\n}\n```\n\n### Cron expression\n\nA Cron expression consists of six sequential fields and is declared as `second, minute, hour, day of month, month, day(s) of week`.\n\n```text\n┌───────────── second (0-59)\n│ ┌───────────── minute (0 - 59)\n│ │ ┌───────────── hour (0 - 23)\n│ │ │ ┌───────────── day of the month (1 - 31)\n│ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)\n│ │ │ │ │ ┌───────────── day of the week (0 - 7)\n│ │ │ │ │ │              (0 or 7 is Sunday or MON-SUN)\n│ │ │ │ │ │\n* * * * * *\n```\n\nRef: [https://crontab.guru/](https://crontab.guru/)\n\nAnd is declared as follows:\n\n```java\n@Slf4j\n@Component\npublic class MyScheduler {\n\n    private static final SimpleDateFormat dateFormat = new SimpleDateFormat(\"HH:mm:ss\");\n\n    @Scheduled(cron = \"*/5 * * * * *\")\n    public void currentTime() {\n        log.info(\"Current Time = {}\", dateFormat.format(new Date()));\n    }\n\n}\n```\n\nWe can also set the timezone as: [https://docs.oracle.com/cd/B13866\\_04/webconf.904/b10877/timezone.htm](https://docs.oracle.com/cd/B13866_04/webconf.904/b10877/timezone.htm)\n\n```java\n@Scheduled(cron=\"* * * * * *\", zone=\"Europe/London\")\n```\n\n### Fixed delay\n\nThe `fixedDelay` property makes sure that there is a delay of n millisecond between the finish time of an execution of a task and the start time of the next execution of the task.\n\n```java\n@Component\npublic class MyScheduler {\n\n    @Scheduled(fixedDelay=5000)\n    public void doSomething() {\n       //This will execute periodically, after the one before finishes\n    }\n\n}\n```\n\nBy default, milliseconds will be used as the time unit for fixed delay, fixed rate, and initial delay values. If you would like to use a different time unit such as seconds or minutes, you can configure this via the `timeUnit` attribute in `@Scheduled`.\n\nFor example, the previous example can also be written as follows.\n\n```java\n@Component\npublic class MyScheduler {\n\n    @Scheduled(fixedDelay=5, timeUnit = TimeUnit.SECONDS)\n    public void doSomething() {\n       //This will execute periodically, after the one before finishes\n    }\n\n}\n```\n\n### Fixed Rate\n\nThe `fixedRate` is used when we want to execute a task periodically at every n millisecond without checking for any previous executions of the task.\n\n```java\n@Component\npublic class MyScheduler {\n\n    @Scheduled(fixedRate=5000)\n    public void doSomething() {\n       //This will execute periodically\n    }\n}\n```\n\nFor both `fixedDelay` and `fixedRate` tasks, you can specify an `intialDelay` by indicating the amount of time to wait before the first execution of the method.\n\n```java\n@Component\npublic class MyScheduler {\n\n    @Scheduled(initailDelay=1000, fixedRate=5000)\n    public void doSomething() {\n      //This will execute periodically\n    }\n}\n```\n\n### Schedule Tasks and Concurrency\n\nSpring Boot uses a `ThreadPoolTaskScheduler` to execute scheduled tasks. By default, this thread pool has a single thread. This means that only one scheduled task can be executed at a time.\n\nIf you need to execute multiple tasks concurrently, then you need to configure the `ThreadPoolTaskScheduler` to have the required thread pool size.\n\n```java\n@Bean\npublic ThreadPoolTaskScheduler threadPoolTaskScheduler() {\n    ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();\n    threadPoolTaskScheduler.setPoolSize(5);\n    return threadPoolTaskScheduler;\n}\n```\n\nAlso, we need to use the `@Async` annotation to mark the scheduled task as asynchronous. This will make Spring Boot execute the tasks in separate threads.\n\n```java\n@Async\n    @Scheduled(fixedDelay = 1000)\n    public void startUsingFixedDelay() {\n        log.info(\"startUsingFixedDelay:: Task started at {}\", DATE_FORMAT.format(new Date()));\n    }\n```\n\n### Aggregate Scheduled annotations\n\nThe `@Schedules` annotation is a container annotation that aggregates several Scheduled annotations.\n\n```java\n@Schedules({\n   @Scheduled(fixedRate = 10000),\n   @Scheduled(cron = \"0 * * * * MON-FRI\")\n})\npublic void doSomething() {\n    //This will execute periodically\n}\n```\n\nPrior to Java 8, a wrapper/container annotation was required to use multiple instances of the same annotation. But Java 8 supports repeatable annotations so wrapper annotation is no longer necessary. Multiple annotations can be used without a wrapper.\n\n```java\n@Scheduled(fixedRate = 10000)\n@Scheduled(cron = \"0 * * * * MON-FRI\")\npublic void doSomethingElse4() {\n    //This will execute periodically\n}
1\n```\n\nThis rule is automatically disabled when the project’s sonar.java.source is lower than 8 as repeating annotations were introduced in Java 8.\n\n## Testing the Scheduler using Awaitility\n\nTesting the scheduler can be a little tricky. We can test this by manually waiting for `x` number of minutes using `Thread.sleep()` , but for complex scenarios, this will be hard to scale.\n\nThis is where we can use a framework like **Awaitility** to wait for a certain condition to be met while running your test. In this case, we want to wait for `1000` milliseconds before we assess the test results.\n\nLet's first add the `awaitility` test dependency on your `build.gradle` file.\n\n```groovy\ntestImplementation 'org.awaitility:awaitility:3.1.2'\n```\n\nNow,\n\n```java\n@SpringJUnitConfig(SchedulerConfig.class)\nclass MySchedulerTest {\n\n    @SpyBean\n    MyScheduler scheduler;\n\n    @Test\n    void givenSleepBy1000ms_whenStartTask1() {\n\n        Awaitility.await()\n                .atMost(1000, TimeUnit.MILLISECONDS)\n                .untilAsserted(() -\u003e {\n                    verify(scheduler, atLeast(1)).startUsingFixedDelay();\n                });\n    }\n\n}\n```\n\n## Task Monitoring:\n\nSpring boot [actuators](https://stacktips.com/courses/spring-boot-for-beginners/working-with-spring-boot-actuators) provides the `/scheduledtasks` endpoint to monitor the list of tasks scheduled and their configurations. To enable this we need to add the actuator starter dependencies.\n\n```groovy\nimplementation 'org.springframework.boot:spring-boot-starter-actuator'\n```\n\nOnce Actuator dependencies is added, we need to explicitly include the `scheduledtasks` endpoint by using the following property\n\n```text\nmanagement.endpoints.web.exposure.include=scheduledtasks\n```\n\n## Did you know?\n\n**What happens if a scheduled task throws an exception?** If any exception is encountered during the scheduled task execution and if it is not handled gracefully using a try-catch block then the Spring Logging Error Handler will handle the exception and log the error details.\n\nThe next instances of that task will continue to execute as per the schedule.\n\n**What happens if a scheduled task takes longer than its scheduled interval?** In the case of a fixed rate, if a scheduled task takes longer than its scheduled interval, the Spring Scheduler will start the next execution of the task immediately after the previous one is completed.\n\nThis can cause tasks to overlap, which may impact performance.\n\n## Limitations of Spring Scheduler\n\n-   **No support for dynamic Scheduling**: The `@Scheduled` annotations are typically configured at application startup and do not support [dynamic scheduling](https://stacktips.com/articles/dynamic-scheduling-in-quartz-with-spring-boot-actuators) without redeploying the application.\n-   **No support for Job Persistence**: It does not offer built-in support for Job persistence, as a result, job recovery in the event of an application restart is not possible.\n-   **No clustering, load balancing**: It does not support clustering and load balancing, The tasks are typically run on a single node.\n-   **Limited control**: It does not allow fine-grained control over managing the tasks. For example, we cannot pause, resume, and unscheduled jobs individually.\n\nSpring Scheduler is sufficient for many simple scheduling tasks, but if you have complex scheduling requirements, job management, and monitoring, then you would need another framework like [Quartz](https://stacktips.com/articles/working-with-quartz-scheduler-in-spring-boot).\n"])</script>
1<script>self.__next_f.push([1,"3d:T23bc,"])</script>
1<script>self.__next_f.push([1,"\nThe `@RestController` annotation in Spring boot is designed to automatically serializes Java objects into JSON or XML, based on the content negotiation strategy defined in your controller.\n\nIt combines the `@Controller` and `@ResponseBody` annotations. It tells Spring that this class is a controller where every method returns a domain object instead of a view.\n\n-   The payload is automatically converted to JSON or XML based on the value defined in the `Accept` header.\n-   Similarly, the response object is automatically converted to JSON or XML-based `Content-type` header defined in your controller configuration.\n\nSpring uses the Jackson library internally so we don't need to serialise or deserialise to convert Java objects manually.\n\nFor example, the following controller class:\n\n-   It has 3 controller methods; two GET endpoints that return the movie data\n-   A POST endpoint that adds a new movie to the MongoDB\n-   By default, the controller class will accept the JSON request and produce the JSON response.\n\n```java\n@RestController\n@RequestMapping(value = \"/api/1.0/movies\")\npublic class MoviesController {\n\n    private final MovieService movieService;\n\n    public MoviesController(MovieService movieService) {\n        this.movieService = movieService;\n    }\n\n    @GetMapping\n    public ResponseEntity\u003cList\u003cMovie\u003e\u003e getMovies() {\n        return ResponseEntity.ok(movieService.getMovies());\n    }\n\n    @PostMapping\n    public Movie createMovie(@RequestBody MovieDto movieDto) {\n        return movieService.createMovie(movieDto);\n    }\n\n    @GetMapping(path = \"/{movieId}\")\n    public Movie getMovie(@PathVariable String movieId) {\n        return movieService.getMovie(movieId);\n    }\n}\n```\n\nLet us change the `MovieController` to accept XML content type in the request body and produce the XML response.\n\n### Jackson XML Dependency\n\nFirst, We need to add [Jackson XML](https://github.com/FasterXML/jackson-dataformat-xml/wiki/Jackson-XML-annotations#jacksonxmlelementwrapper) dependency for reading and writing XML data.\n\nFor the Gradle project, add the following dependency to your `build.gradle` file:\n\n```groovy\nimplementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml'\n```\n\nFor a maven-based project, you can add the following to your `pom.xml` file.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.fasterxml.jackson.dataformat\u003c/groupId\u003e\n    \u003cartifactId\u003ejackson-dataformat-xml\u003c/artifactId\u003e\n\u003c/dependency\u003e\n```\n\nWe need to annotate our controller mapping to match the `application/xml` media type. This is done using the `Content-Type` and `Accept` media type to our controller mapping.\n\nThis can be done by defining the appropriate MediaType using the `produces` and `consumes` property of `RequestMapping` annotation.\n\n```java\n@RestController\n@RequestMapping(value = \"/api/1.0/movies\",\n        consumes = {MediaType.APPLICATION_XML_VALUE}, # Content-Type\n        produces = {MediaType.APPLICATION_XML_VALUE}  # Accept\n)\npublic class MoviesController {\n\n    private final MovieService movieService;\n\n    public MoviesController(MovieService movieService) {\n        this.movieService = movieService;\n    }\n\n    @GetMapping\n    public ResponseEntity\u003cList\u003cMovie\u003e\u003e getMovies() {\n        return ResponseEntity.ok(movieService.getMovies());\n    }\n\n    @PostMapping\n    public Movie createMovie(@RequestBody MovieDto movieDto) {\n        return movieService.createMovie(movieDto);\n    }\n\n    @GetMapping(path = \"/{movieId}\")\n    public Movie getMovie(@PathVariable String movieId) {\n        return movieService.getMovie(movieId);\n    }\n\n}\n```\n\nIn the above code snippet, we have set the `MediaType` configuration to the controller level, which means all controller methods will now consume and produce XML output. We can also do the same to the individual methods by using produces and consumes property on HTTP method mapping annotation.\n\nThat is all, now our controller will handle the XML request and produce the `application/xml` media type. Let us test our `/movies` endpoint\n\n```bash\ncurl --location 'http://localhost:8080/api/1.0/movies' \\\n    --header 'Content-type: application/xml' \\\n    --header 'Accept: application/xml'\n```\n\nNow it will produce XML output\n\n```xml\n\u003cList\u003e\n    \u003citem\u003e\n        \u003cid\u003e65c4092af4ba290f3c55cd06\u003c/id\u003e\n        \u003ctitle\u003eIron Man \u0026amp; Captain America: Heroes United\u003c/title\u003e\n        \u003cheadline\u003eIron Man (Adrian Pasdar) and Captain America (Roger Craig Smith) must prevent Red Skull (Liam O'Brien) and Taskmaster (Clancy Brown) from destroying the world.\u003c/headline\u003e\n        \u003clanguage\u003eEN\u003c/language\u003e\n        \u003cregion\u003eUSA\u003c/region\u003e\n        \u003cactors\u003e\n            \u003cactors\u003eDavid Kaye\u003c/actors\u003e\n            \u003cactors\u003eIan McKellen\u003c/actors\u003e\n            \u003cactors\u003eAdrian Pasdar\u003c/actors\u003e\n        \u003c/actors\u003e\n        \u003cgenres\u003e\n            \u003cgenres\u003eAction\u003c/genres\u003e\n            \u003cgenres\u003eAdventure\u003c/genres\u003e\n            \u003cgenres\u003eSci-fi\u003c/genres\u003e\n        \u003c/genres\u003e\n    \u003c/item\u003e\n    \u003citem\u003e\n        \u003cid\u003e65c4092af4ba290f3c55cd07\u003c/id\u003e\n        \u003ctitle\u003eIron Man \u0026amp; Captain America: Heroes United\u003c/title\u003e\n        \u003cheadline\u003eIron Man (Adrian Pasdar) and Captain America (Roger Craig Smith) must prevent Red Skull (Liam O'Brien) and Taskmaster (Clancy Brown) from destroying the world.\u003c/headline\u003e\n        \u003clanguage\u003eEN\u003c/language\u003e\n        \u003cregion\u003eUSA\u003c/region\u003e\n        \u003cactors\u003e\n            \u003cactors\u003eDavid Kaye\u003c/actors\u003e\n            \u003cactors\u003eIan McKellen\u003c/actors\u003e\n            \u003cactors\u003eAdrian Pasdar\u003c/actors\u003e\n        \u003c/actors\u003e\n        \u003cgenres\u003e\n            \u003cgenres\u003eAction\u003c/genres\u003e\n            \u003cgenres\u003eAdventure\u003c/genres\u003e\n            \u003cgenres\u003eSci-fi\u003c/genres\u003e\n        \u003c/genres\u003e\n    \u003c/item\u003e\n\u003c/List\u003e\n```\n\n### Configure Default Content Negotiation\n\nThe above method works fine but the configuration is now at controller level. The default media type remains JSON for all other controllers.\n\nWe can override this by setting the default content negotiation for all c
1ontrollers thought the project by implementing the `WebMvcConfigurer` configuration.\n\n```java\n@Configuration\npublic class AppConfig implements WebMvcConfigurer {\n\n    @Override\n    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {\n        configurer.defaultContentType(MediaType.APPLICATION_XML);\n    }\n}\n```\n\n### Wrapping XML Response\n\nNotice the above XML response, the result is wrapped inside `\u003cList\u003e\u003citem\u003e\u003citem\u003e\u003c/List\u003e` tag. This is not very pretty.\n\nWe can make the following changes to wrap the response `\u003cmovies\u003e\u003cmovie\u003e\u003c/movie\u003e\u003c/movies\u003e` tag.\n\n-   Create a wrapper class for Movies.\n-   The `@JacksonXmlRootElement` annotation can be used to define the name of the root element used for the root-level object when serialized, which normally uses the name of the type (class).\n-   The `@JacksonXmlElementWrapper` annotation is used to specify XML elements to use for wrapping `List` and `Map` properties.\n-   From the controller, instead of returning `ResponseEntity\u003cList\u003cMovie\u003e\u003e`, we will return the `ResponseEntity\u003cMovies\u003e\u003e` type.\n\n```java\n@Getter\n@Setter\n@RequiredArgsConstructor\n@JacksonXmlRootElement(localName = \"movies\")\npublic class Movies {\n\n    @JacksonXmlProperty(localName = \"movie\")\n    @JacksonXmlElementWrapper(useWrapping = false)\n    private final List\u003cMovie\u003e moviesList;\n\n}\n\n@Getter\n@Setter\n@JacksonXmlRootElement(localName = \"Movie\")\npublic class Movie {\n    private String id;\n    private String title;\n    private String headline;\n    private String language;\n    private String region;\n    private List\u003cString\u003e actors;\n    private List\u003cString\u003e genres;\n}\n```\n\nAnd, update the controller to return the `ResponseEntity\u003cMovies\u003e\u003e` type.\n\n```java\n@GetMapping\npublic ResponseEntity\u003cMovies\u003e getMovies() {\n    Movies movies = new Movies(movieService.getMovies());\n    return ResponseEntity.ok(movies);\n}\n```\n\nNow this will produce,\n\n```xml\n\u003cmovies\u003e\n    \u003cmovie\u003e\n        \u003cid\u003e65c4092af4ba290f3c55cd06\u003c/id\u003e\n        \u003ctitle\u003eIron Man \u0026amp; Captain America: Heroes United\u003c/title\u003e\n        \u003cheadline\u003eIron Man (Adrian Pasdar) and Captain America (Roger Craig Smith) must prevent Red Skull (Liam O'Brien) and Taskmaster (Clancy Brown) from destroying the world.\u003c/headline\u003e\n        \u003clanguage\u003eEN\u003c/language\u003e\n        \u003cregion\u003eUSA\u003c/region\u003e\n        \u003cactors\u003e\n            \u003cactors\u003eDavid Kaye\u003c/actors\u003e\n            \u003cactors\u003eIan McKellen\u003c/actors\u003e\n            \u003cactors\u003eAdrian Pasdar\u003c/actors\u003e\n        \u003c/actors\u003e\n        \u003cgenres\u003e\n            \u003cgenres\u003eAction\u003c/genres\u003e\n            \u003cgenres\u003eAdventure\u003c/genres\u003e\n            \u003cgenres\u003eSci-fi\u003c/genres\u003e\n        \u003c/genres\u003e\n    \u003c/movie\u003e\n    \u003cmovie\u003e\n        \u003cid\u003e65c4092af4ba290f3c55cd07\u003c/id\u003e\n        \u003ctitle\u003eIron Man \u0026amp; Captain America: Heroes United\u003c/title\u003e\n        \u003cheadline\u003eIron Man (Adrian Pasdar) and Captain America (Roger Craig Smith) must prevent Red Skull (Liam O'Brien) and Taskmaster (Clancy Brown) from destroying the world.\u003c/headline\u003e\n        \u003clanguage\u003eEN\u003c/language\u003e\n        \u003cregion\u003eUSA\u003c/region\u003e\n        \u003cactors\u003e\n            \u003cactors\u003eDavid Kaye\u003c/actors\u003e\n            \u003cactors\u003eIan McKellen\u003c/actors\u003e\n            \u003cactors\u003eAdrian Pasdar\u003c/actors\u003e\n        \u003c/actors\u003e\n        \u003cgenres\u003e\n            \u003cgenres\u003eAction\u003c/genres\u003e\n            \u003cgenres\u003eAdventure\u003c/genres\u003e\n            \u003cgenres\u003eSci-fi\u003c/genres\u003e\n        \u003c/genres\u003e\n    \u003c/movie\u003e\n\u003c/movies\u003e\n```\n"])</script>
1<script>self.__next_f.push([1,"3e:Te29,"])</script>
1<script>self.__next_f.push([1,"\nThe `@PathVariable` in spring is used to handle the template variables in the request URI mapping and extract them into method parameter.\n\nFor example, in the following controller the `vehicleId` is a path variable mapped directly to the the `updateModel()` controller method.\n\n```java\n@PostMapping(\"/vehicles/{vehicleId}\")\npublic ResponseEntity updateModel(@PathVariable String vehicleId,\n                @Valid @RequestBody VehicleDto vehicle) throws Exception {\n    // Your implementation goes here\n}\n```\n\nValidation can range from simple checks like ensuring the vehicleId is not null or empty, to more complex validations like checking if it adheres to a specific format or verifying against the database. To validate the `@PathVariable` in a Spring Boot application, we have several options:\n\nHere are some common approaches:\n\n### Basic Non-Null or Non-Empty Validation\n\nWe can use the `@NotNull` or `@NotEmpty` annotations to ensure that the `vehicleId` is not null or empty.\n\n```java\n@PostMapping(\"/vehicles/{vehicleId}\")\npublic ResponseEntity updateModel(@PathVariable @NotEmpty String vehicleId,\n            @Valid @RequestBody VehicleDto vehicle) throws Exception {\n    // Your implementation goes here\n}\n```\n\n### Custom Validation with Regular Expressions\n\nTo validate a specific pattern like a specific length or containing only numbers, you can use the `@Pattern` annotation from the `javax.validation.constraints` package and use the regular expressions.\n\n```java\n@PostMapping(\"/vehicles/{vehicleId}\")\npublic ResponseEntity updateModel(@PathVariable @Pattern(regexp = \"\\d{4,6}\") String vehicleId,\n        @Valid @RequestBody VehicleDto vehicle) throws Exception {\n    // Your implementation goes here\n}\n```\n\nThe regular expressions `\\d{4,6}` allows only numbers between 4 and 6 characters length.\n\n### Using Custom Validator\n\nWe can use the custom validator if we have more complex validations such as checking against a database. For this we can implement the `ConstraintValidator` interface and inside the `isValid` method it should return either true or false based on the business logic.\n\n```java\n@Target({ ElementType.PARAMETER })\n@Retention(RetentionPolicy.RUNTIME)\n@Constraint(validatedBy = VehicleIdValidator.class)\npublic @interface ValidVehicleId {\n\n    String message() default \"Invalid vehicheId\";\n    Class\u003c?\u003e[] groups() default {};\n    Class\u003c? extends Payload\u003e[] payload() default {};\n}\n\npublic class VehicleIdValidator implements ConstraintValidator\u003cValidVehicleId, String\u003e {\n    @Override\n    public boolean isValid(String value, ConstraintValidatorContext context) {\n        // validation logic goes here\n        return true;\n    }\n}\n```\n\nNow here is how we can use the our custom validator in the controller mapping.\n\n```java\n@PostMapping(\"/vehicles/{vehicleId}\")\npublic ResponseEntity updateModel(@PathVariable @ValidVehicleId String vehicleId,\n        @Valid @RequestBody VehicleDto vehicle) throws Exception {\n    // Your implementation goes here\n}\n```\n\n### Manual Validation Inside the Method\n\nIt is recommended to use one of the above method for validating the `@PathVariable`. But otherwise we can also validate manually inside the method implementation and throw custom exceptions if the validation fails..\n\n```java\n@PostMapping(\"/vehicles/{vehicleId}\")\npublic ResponseEntity updateModel(\n        @PathVariable @ValidVehicleId String vehicleId,\n        @Valid @RequestBody VehicleDto vehicle) throws Exception {\n    if (vehicleId == null || vehicleId.isEmpty()) {\n        throw new MyCustomValiationException(\"Vehicle id is invalid\")\n    }\n\n    // Your implementation goes here\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"3f:T2130,"])</script>
1<script>self.__next_f.push([1,"\nParameterized tests allow you to execute a single test multiple times using different parameters. This way we can eliminate the need to write the separate tests for each set of test data.\n\nIn JUnit 5, parameterized tests are supported through the `@ParameterizedTest` annotation. The `@ParameterizedTest` replaces the `@Test` annotation to test methods. With `@ParameterizedTest` we can run the test method from the various data sources including:\n\n1.  `@ValueSource`: Provides a simple array of literal values\n2.  `@EnumSource`: Provides values from a specified enum class.\n3.  `@MethodSource`: References a method that returns a stream of arguments.\n4.  `@CsvSource`: Allows specifying values in a comma-separated format.\n5.  `@CsvFileSource`: Reads values from a CSV file.\n6.  `@ArgumentsSource`: References a custom, reusable arguments provider.\n\nThis article explains the usage of each of these test sources using `@ParameterizedTest` annotation.\n\n### Getting the Required Dependencies\n\nThe ParameterizedTest annotation is not part of the core `junit-jupiter-api` but is in a separate artifact named `junit-jupiter-params`. That is why, for running the JUnit5 parameterized tests, we need to have the `junit-jupiter-params` dependency in our classpath.\n\nIf you are using Maven, we have to add the `junit-jupiter-params` dependency to the pom.xml file to the `test` scope.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.junit.jupiter\u003c/groupId\u003e\n    \u003cartifactId\u003ejunit-jupiter-params\u003c/artifactId\u003e\n    \u003cversion\u003e5.9.3\u003c/version\u003e\n    \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nIf we are using Gradle, you need to add the following to `build.gradle` file\n\n```groovy\ntestImplementation('org.junit.jupiter:junit-jupiter-params:5.9.3')\n```\n\nOnes we have the required dependency, we are good to write our first parameterized test with JUnit 5.\n\n### Using @ValueSource annotation\n\nThe @ValueSource provides a simple array of literal values. It supports all primitive types including shorts, bytes, ints, longs, floats, doubles, chars, booleans, strings and classes.\n\nThe `testWithStrings()` test method in the following code snippet will be executed 3 times with the arguments SUNDAY, MONDAY, and TUESDAY.\n\n```java\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.ValueSource;\nimport static org.junit.jupiter.api.Assertions.assertNotNull;\n\nclass ValueSourceTest {\n\n    @ParameterizedTest\n    @ValueSource(strings = {\"SUNDAY\", \"MONDAY\", \"TUESDAY\"})\n    void testWithStrings(String argument) {\n\n        assertNotNull(argument);\n    }\n}\n```\n\n### Using @EnumSource annotation\n\nThe `@EnumSource` allows us to test a function or a method against all possible values of an enum type.\n\n```java\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.EnumSource;\nimport java.util.EnumSet;\nimport static org.junit.jupiter.api.Assertions.assertNotNull;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\nenum DayOfWeek {\n    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY\n}\n\nclass EnumSourceTest {\n\n    @ParameterizedTest\n    @EnumSource(DayOfWeek.class)\n    void testWithEnumSource(DayOfWeek dayOfWeek) {\n        assertNotNull(dayOfWeek);\n    }\n\n    @ParameterizedTest\n    @EnumSource(value = DayOfWeek.class, names = {\"MONDAY\", \"FRIDAY\"})\n    void testWithEnumSourceIncludeOnlySomeDays(DayOfWeek dayOfWeek) {\n        assertTrue(EnumSet.of(DayOfWeek.MONDAY, DayOfWeek.FRIDAY).contains(dayOfWeek));\n    }\n}\n```\n\n### Using @MethodSource annotation\n\nThe `@MethodSource` annotation allows us to specify a method that provides a stream of arguments. Here is how we can use `@MethodSource` annotations in Junit5.\n\n```java\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.Arguments;\nimport org.junit.jupiter.params.provider.MethodSource;\nimport java.util.stream.Stream;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nclass MethodSourceTest {\n\n    @ParameterizedTest\n    @MethodSource(\"provideStringArgs\")\n    void testWithMethodSource(String week, String weekShort) {\n        assertEquals(weekShort, week.substring(0, 3));\n    }\n\n    static Stream\u003cArguments\u003e provideStringArgs() {\n        return Stream.of(\n                Arguments.of(\"SUNDAY\", \"SUN\"),\n                Arguments.of(\"MONDAY\", \"MON\"),\n                Arguments.of(\"TUESDAY\", \"TUE\")\n        );\n    }\n}\n```\n\n### Using @CsvSource annotation\n\nThe `@CsvSource` annotation allows us to specify a comma-separated list of values. Each line in the `@CsvSource` annotation represents a distinct invocation of the parameterized test method.\n\nHere is how 
1we can use the `@CsvSource` in Junit5.\n\n```java\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.CsvSource;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nclass CsvSourceTest {\n\n    @ParameterizedTest\n    @CsvSource({\n            \"SUNDAY, 6\",\n            \"MONDAY, 6\",\n            \"TUE, 3\",\n            \"'', 0\",\n            \"'HAPPY WEEKEND!', 14\",\n    })\n    void testStringLength(String input, int expectedLength) {\n        assertEquals(expectedLength, input.length());\n    }\n}\n```\n\n### Using @CsvFileSource annotation\n\nThe `@CsvFileSource` annotation in JUnit 5 allows you to use CSV files as a source of parameters for parameterized tests. This is useful for larger datasets or when you want to keep your test data separate from your test code.\n\nHere is how we can use `@CsvFileSource` in Junit5:\n\n```java\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.CsvFileSource;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nclass CsvFileSourceTest {\n\n    @ParameterizedTest\n    @CsvFileSource(resources = \"/data1.csv\")\n    void testWithCsvFileSource1(String day, int length) {\n        assertEquals(length, day.length());\n    }\n\n    @ParameterizedTest\n    @CsvFileSource(resources = \"/data2.csv\", delimiter = ';')\n    void testWithCsvFileSourceDelimiter(String day, int length) {\n        assertEquals(length, day.length());\n    }\n\n    @ParameterizedTest\n    @CsvFileSource(resources = \"/data3.csv\", nullValues = {\"NULL\"})\n    void testWithCsvFileSourceNullValue(String day, int length) {\n        assertEquals(length, day != null ? day.length() : 0);\n    }\n}\n```\n\nThe above code snippet uses the `data.csv` file. It reads the file from the `src/test/resources` directory.\n\n**data1.csv**  \n\n```text\nSUNDAY, 6\nMONDAY, 6\nTUE, 3\nHAPPY WEEKEND!, 14\n```\n\n**data2.csv**\n\n```text\nSUNDAY; 6\nMONDAY; 6\nTUE; 3\nHAPPY WEEKEND!; 14\n```\n\n**data3.csv**\n\n```text\nSUNDAY, 6\nMONDAY, 6\nTUE, 3\nHAPPY WEEKEND!, 14\n , 0\n```\n\nIf your CSV file uses a delimiter other than a comma, you can specify it using the `delimiter` attribute of the `@CsvFileSource` annotation.\n\n```java\n@CsvFileSource(resources = \"/data.csv\", delimiter = ';')\n```\n\nBy default, an empty field in the CSV file is treated as an empty string. If you want to treat them as `null`, specify a `nullValues` attribute.\n\n```java\n@CsvFileSource(resources = \"/data.csv\", nullValues = {\"NULL\"})\n```\n\n### Using @ArgumentsSource annotation\n\nThe `@ArgumentsSource` annotation allows us to specify a custom, reusable source of arguments. It allows you to define a class that implements the `ArgumentsProvider` interface, which can then generate and provide complex argument objects for your tests.\n\nHere is how 
1we can use `@ArgumentsSource` annotation:\n\n```java\nimport org.junit.jupiter.api.extension.ExtensionContext;\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.Arguments;\nimport org.junit.jupiter.params.provider.ArgumentsProvider;\nimport org.junit.jupiter.params.provider.ArgumentsSource;\nimport java.util.stream.Stream;\nimport static org.junit.jupiter.api.Assertions.assertNotNull;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\nclass ArgumentSourceTest {\n\n    @ParameterizedTest\n    @ArgumentsSource(CustomArgumentsProvider.class)\n    void testWithCustomArgumentsSource(String input, int number) {\n        assertNotNull(input);\n        assertTrue(number \u003e 0);\n    }\n}\n\nclass CustomArgumentsProvider implements ArgumentsProvider {\n\n    @Override\n    public Stream\u003c? extends Arguments\u003e provideArguments(ExtensionContext context) {\n        return Stream.of(\n                Arguments.of(\"SUNDAY\", 6),\n                Arguments.of(\"MONDAY\", 6),\n                Arguments.of(\"TUE\", 3),\n                Arguments.of(\"HAPPY WEEKEND!\", 14)\n        );\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"40:T2dd1,"])</script>
1<script>self.__next_f.push([1,"\nThe best way to confirm the reliability and correctness of software applications is to write tests that assert the desired behavior of an application. This post covers how to perform unit and integration testing in Spring Boot.\n\nThe `spring-boot-starter-test` [starter dependency](/courses/spring-boot-for-beginners/introduction-to-spring-boot-framework#spring-boot-starter-dependencies) is required for writing the unit and integration tests in Spring Boot application. The Spring Boot version 3.2.2 `spring-boot-starter-test` includes the following [transitive dependencies](/courses/maven-for-beginners/dependency-management-in-maven#411-transitive-dependency).\n\n-   **Jupiter JUnit5**: The de facto standard for unit testing Java.\n-   **Jayway JsonPath:** A popular Java library used for parsing and querying JSON documents. It is used for navigating through the structure of your JSON data and access specific values or elements.\n-   **Awaitility:** Used for waiting for asynchronous operations to complete without introducing additional logic in your code.\n-   **Hamcrest:** Hamcrest is used for writing expressive and readable assertions in unit tests. It provides a clear and concise way to express what you expect from your code, making your tests easier to understand and maintain.\n-   **Mockito:** Java mocking framework used to create mock objects that simulate the behavior of real objects without actually implementing their functionality. This makes it easier to isolate the code you're testing from external dependencies and write more focused and reliable tests.\n\nLet’s start by creating a [new Spring application](/courses/spring-boot-for-beginners/creating-first-spring-boot-project#create-a-new-spring-boot-project). You can create a Spring boot project either using Spring CLI or using Spring Initializr.\n\nWhen we create a new Spring boot project the `spring-boot-starter-test` dependencies is added by default. If you don't have it already, you can add this manually in your `pom.xml` or `build.gradle` file.\n\nFor maven, add the following to the `\u003cdependencies\u003e` section in your `pom.xml` file\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-test\u003c/artifactId\u003e\n    \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nThe `test` scope defines that the `spring-boot-starter-test` dependency is required during the test compilation and execution phases.\n\nFor gradle,\n\n```groovy\ntestImplementation 'org.springframework.boot:spring-boot-starter-test'\n```\n\nThe Spring Initializr also includes a default test class in the root directory of the test package.\n\n```java\nimport org.junit.jupiter.api.Test;\nimport org.springframework.boot.test.context.SpringBootTest;\n\n@SpringBootTest\nclass MoviesApplicationTests {\n\n    @Test\n    void contextLoads() {\n\n    }\n}\n```\n\nThe `@SpringBootTest` annotation tells Spring Boot to look for a main configuration class (one with `@SpringBootApplication`, for instance) and use that to start the Spring application context.\n\nThe `@Test` annotation a JUnit annotation that will execute the method when the tests starts. A test class can contain one or more test methods. When there are multiple test methods, the order of execution is not fixed. If you want to fix the execution order you can do that using the method name, display name, using order annotation. Checkout this tutorials that explains [how to order test methods](https://stacktips.com/articles/the-order-of-tests-in-junit5).\n\nYou can run this test in your IDE or on the command line using following Maven or Gradle commands.\n\n```bash\n./mvnw test\n```\n\nor\n\n```bash\n./gradlew test\n```\n\n## Simple Test\n\nNow that we have the required test dependency in our project and we have learnt how to execute the test, let us now test the following controller.\n\n```java\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class GreetingController {\n\n    @RequestMapping(\"/\")\n    public String greeting() {\n        return \"Hello, Spring Boot!\";\n    }\n}\n```\n\nLet us now verify if the Spring context is creating the instance of `GreetingsController` with an assertion.\n\n```java\nimport com.stacktips.movies.api.GreetingsController;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\n\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.Matchers.notNullValue;\n\n@SpringBootTest\nclass MoviesApplicationTests {\n\n    @Autowired\n    private GreetingController controller;
1\n\n    @Test\n    void contextLoads() {\n        assertThat(controller, is(notNullValue()));\n    }\n\n}\n```\n\nThe `@Autowired` injects the controller instance before the test methods are run. We have hamcrest which provides `assertThat()` method to assert the not null value.\n\n\u003e \\[!TIP\\] The Spring Test support caches the application context between tests, so that if you have multiple methods in a test case or multiple test cases with the same configuration, they incur the cost of starting the application only once. You can control the cache by using the `@DirtiesContext` annotation.\n\n## Testing the REST API\n\nLet us now write some tests to assert the behavior of your application. For that we will start the application and and listen for a connection (as it would do in production) and then send an HTTP request and assert the response.\n\n```java\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.boot.test.web.client.TestRestTemplate;\nimport org.springframework.boot.test.web.server.LocalServerPort;\n\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\nimport static org.springframework.boot.test.context.SpringBootTest.WebEnvironment;\n\n@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)\nclass GreetingsControllerTest {\n\n    @LocalServerPort\n    private int port;\n\n    @Autowired\n    private TestRestTemplate restTemplate;\n\n    @Test\n    void greetingShouldReturnDefaultMessage() throws Exception {\n        String result = restTemplate\n            .getForObject(\"http://localhost:\" + port + \"/\",  String.class);\n        assertThat(result, is(\"Hello, Spring Boot!\"));\n    }\n\n}\n```\n\nThe `webEnvironment=RANDOM_PORT` to start the server with a random port. This is very useful to avoid conflicts in test environments and the injection of the port with `@LocalServerPort`.\n\nSpring boot test also provides a `TestRestTemplate` for to make http calls from your test.\n\n## Using MockMvc\n\nIn the above approach we have started the server but if we want to tests to only the web layer by without starting a server we can do that using `@WebMvcTest`. For that, we will inject an instance of `MockMvc`. For MockMvc to work we need to need to use the `@AutoConfigureMockMvc` annotation on our test class.\n\nIf we have multiple controllers, we can instantiate specific ones by using the`@WebMvcTest(HomeController.class)` annotation on the class.\n\n```java\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;\nimport org.springframework.test.web.servlet.MockMvc;\n\nimport static org.hamcrest.Matchers.containsString;\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;\nimport static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;\n\n@WebMvcTest(GreetingController.class)\nclass GreetingControllerTest {\n\n    @Autowired\n    MockMvc mockMvc;\n\n    @Test\n    void greetingShouldReturnDefaultMessage() throws Exception {\n        this.mockMvc.perform(get(\"/\"))\n                .andDo(print())\n                .andExpect(status().isOk())\n                .andExpect(content().string(containsString(\"Hello, Spring Boot!\")));\n    }\n\n}\n```\n\nThe test assertion is the same as in the previous case. However, in this test, Spring Boot instantiates only the web layer rather than using the whole spring context.\n\n## Mocking Services\n\nSo far, our `HomeController` is simple and has no dependencies. But we will often have additional services to isolate the business logic into separate classes. For example.\n\n**MovieService**\n\n```java\nimport org.springframework.stereotype.Service;\n\nimport java.util.List;\n\n@Service\npublic class MovieService {\n\n    public List\u003cString\u003e getMovies() {\n        return List.of(\"The Incredibles\", \"Father of the Bride\", \"The Parent Trap\");\n    }\n}\n```\n\nAnd, lets say our MovieController has `/movies` GET endpoint.\n\n```java\nimport com.stacktips.movies.service.MovieService;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport java.util.List;\n\n@RestController\npublic class MovieController {\n\n    private final MovieService movieService;\n\n    public MovieController(MovieService movieService) {\n        this.movieService = movieService;\n    }\n\n    @RequestMapping(\"/movies\")\n    public List\u003cString\u003e getMovies() {\n        return movieService.getMovies();\n    }\n}\n```\n\nIn the above code snippet, Spring automatically injects the `MovieService` dependency into the controller as we have only one constructor defined. If you run the spring boot application and test `/movies` endpoint, it will return the list of movies.\n\n```text\nnilan \u003e curl http://localhost:8080/movies\n[\"The Incredibles\",\"Father of the Bride\",\"The Parent Trap\"]\n```\n\nLet us now create a test for the `MoviesController` and mock the service instance. To mock the Spring bean the `@MockBean` annotation is used.\n\n```java\nimport com.stacktips.movies.service.MovieService;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;\nimport org.springframework.boot.test.mock.mockito.MockBean;\nimport org.springframework.test.web.servlet.MockMvc;\n\nimport java.util.List;\n\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.mockito.Mockito.when;\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;\nimport static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;\n\n@WebMvcTest(MovieController.class)\nclass MovieControllerTest {\n\n    @Autowired\n    private MockMvc mockMvc;\n\n    @MockBean\n    private MovieService movieService;\n\n    @Test\n    void greetingShouldReturnMockResponse() throws Exception {\n        List\u003cString\u003e moviesMock = List.of(\"Sprider Man\", \"X-Man\", \"Iron Man\");\n        when(movieService.getMovies()).thenReturn(moviesMock);\n\n        this.mockMvc.perform(get(\"/movies\"))\n                .andDo(print())\n                .andExpect(status().isOk())\n                .andExpect(jsonPath(\"$[0]\", is(\"Sprider Man\")))\n                .andExpect(jsonPath(\"$[1]\", is(\"X-Man\")))\n                .andExpect(jsonPath(\"$[2]\", is(\"Iron Man\")));\n    }\n\n}\n```\n\nThe `mockMvc.perform` method makes the GET request to the `/movies` endpoint. But this time, instead of getting the results from the service, it returns the mocked response using `Mockito`.\n\nWe are also using the Json path to assert the Json response.\n"])</script>
1<script>self.__next_f.push([1,"41:T13f3,"])</script>
1<script>self.__next_f.push([1,"\nThe `@Test` a JUnit annotation that will execute the method when the tests starts. A test class can contain one or more test methods. When there are multiple test methods, the order of execution is not fixed.\n\nThe `@TestMethodOrder` is a type-level annotation that is used to configure a method orderer for the test methods of the annotated test class or test interface. The `@TestMethodOrder` can be defined in your test class, inherited from parent class or declared on a test interface implemented by a test class.\n\nThe `@TestMethodOrder` offers different ways to order test execution order. We can order by either `DisplayName`, `MethodName`, `Random`, `OrderAnnotation` or based on a custom order.\n\nTitle Please note, the `Alphanumeric` annotation is deprecated and internally uses the `MethodName` order.\n\n### Order Test Methods by MethodName\n\nFollowing code demonstrates how to order test methods based on the MethodName. The same applies for `Random` as well.\n\n```java\nimport org.junit.jupiter.api.MethodOrderer;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.TestMethodOrder;\n\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\n@TestMethodOrder(MethodOrderer.MethodName.class)\nclass MyServiceTests {\n\n    @Test\n    void test1() {\n        assertTrue(true);\n    }\n\n    @Test\n    void test2() {\n        assertTrue(true);\n    }\n\n    @Test\n    void test3() {\n        assertTrue(true);\n    }\n}\n```\n\nPrints:\n\n![](/media/summernote/Order_Test_Methods_by_MethodName.png)  \n\n### Order Test Methods by DisplayName\n\nThe `@DisplayName` is used when the test report is generated. For ordering the test methods by display name we need to specify a custom display name for each test using the `@DisplayName` annotation.\n\n```java\nimport org.junit.jupiter.api.DisplayName;\nimport org.junit.jupiter.api.MethodOrderer;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.TestMethodOrder;\n\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\n@TestMethodOrder(MethodOrderer.DisplayName.class)\nclass MyServiceTests {\n\n    @Test\n    @DisplayName(\"testMethod1\")\n    void test1() {\n        assertTrue(true);\n    }\n\n    @Test\n    @DisplayName(\"testMethod2\")\n    void test2() {\n        assertTrue(true);\n    }\n\n    @Test\n    @DisplayName(\"testMethod3\")\n    void test3() {\n        assertTrue(true);\n    }\n}\n```\n\nPrints:\n\n![](/media/summernote/Order_Test_Methods_by_DisplayName.png)  \n\n### Order Test Methods by OrderAnnotation\n\nTo define the test execution order based on the `OrderAnnotation`, we need to declare `@Order` annotation for each test methods.\n\nPlease note that the `@Order` annotation should be from `org.junit.jupiter.api` package not from the spring framework `org.springframework.core.annotation` package.\n\n```java\nimport org.junit.jupiter.api.MethodOrderer;\nimport org.junit.jupiter.api.Order;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.TestMethodOrder;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\n@TestMethodOrder(MethodOrderer.OrderAnnotation.class)\nclass MyServiceTests {\n\n    @Test\n    @Order(1)\n    void test1() {\n        assertTrue(true);\n    }\n\n    @Test\n    @Order(3)\n    void test2() {\n        assertTrue(true);\n    }\n\n    @Test\n    @Order(2)\n    void test3() {\n        assertTrue(true);\n    }\n}\n```\n\nPrints:\n\n![](/media/summernote/Order_Test_Methods_by_OrderAnnotation.png)\n\n### Defining Custom Order\n\nWe can define custom order by extending the existing method orderers. For example, let us create a custom method order by number of parameters passed to the test. The test with more parameters will be executed first.\n\n```java\nimport java.util.Comparator;\n\nclass ParameterCountOrder implements MethodOrderer {\n    @Override\n    public void orderMethods(MethodOrdererContext context) {\n        Comparator\u003cMethodDescriptor\u003e comparator =\n                Comparator.comparingInt(md1 -\u003e md1.getMethod().getParameterCount());\n        context.getMethodDescriptors()\n                .sort(comparator.reversed());\n    }\n}\n```\n\nNow, let us use the custom `MethodOrderer` we have created above.\n\n```java\nimport org.junit.jupiter.api.DisplayName;
1\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.TestMethodOrder;\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.CsvSource;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\n@TestMethodOrder(ParameterCountOrder.class)\nclass MyServiceTests {\n\n    @Test\n    @DisplayName(\"testMethod1\")\n    void test1() {\n        assertTrue(true);\n    }\n\n    @ParameterizedTest(name = \"{index} ==\u003e product={0}\")\n    @CsvSource({\n            \"iPhone 15\",\n            \"Mx Master 3S\"\n    })\n    @DisplayName(\"testMethod2\")\n    void test2(String product) {\n        assertTrue(true);\n    }\n\n    @DisplayName(\"testMethod3\")\n    @ParameterizedTest(name = \"{index} ==\u003e product={0}, price={1}\")\n    @CsvSource({\n            \"iPhone 15, 999\",\n            \"Mx Master 3S, 89\"\n    })\n    void test3(String product, double price) {\n        assertTrue(true);\n    }\n\n}\n```\n\nPrints:\n\n![](/media/summernote/Order_Test_Methods_by_CustomOrder.png)\n"])</script>
1<script>self.__next_f.push([1,"42:Tc67,"])</script>
1<script>self.__next_f.push([1,"\nGiven a binary search tree, find its minimum depth.\n\nIn a Binary Search Tree(BST), each node has at most two children, and the left child of a node contains values less than the node's value, and the right child contains values greater than the node's value. The depth of a node in a tree is the length of the path from the root node to that particular node. The depth of the root node is always 0, and the depth increases by 1 as you move down the tree towards the leaves.\n\nFollowing example depicts the representation of BST.\n\n![](/media/summernote/Binary_search_tree_example.png)  \n\nIn the above BST:\n\n-   The depth of the node with value 8 is 0.\n-   The depth of the node with value 3 is 1.\n-   The depth of the node with value 10 is 1.\n-   The depth of the node with value 1 is 2.\n-   The depth of the node with value 6 is 2.\n-   The depth of the node with value 14 is 2.\n\nThe minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.\n\n### Java implementation\n\n```java\nclass TreeNode {\n    int val;\n    TreeNode left;\n    TreeNode right;\n\n    TreeNode(int val) {\n        this.val = val;\n    }\n}\n\npublic class BinarySearchTreeDepth {\n    public int minDepth(TreeNode root) {\n        if (root == null) {\n            return 0;\n        }\n        LinkedList\u003cTreeNode\u003e nodes = new LinkedList\u003c\u003e();\n        LinkedList\u003cInteger\u003e counts = new LinkedList\u003c\u003e();\n        nodes.add(root);\n        counts.add(1);\n        while (!nodes.isEmpty()) {\n            TreeNode curr = nodes.remove();\n            int count = counts.remove();\n            if (curr.left != null) {\n                nodes.add(curr.left);\n                counts.add(count + 1);\n            }\n            if (curr.right != null) {\n                nodes.add(curr.right);\n                counts.add(count + 1);\n            }\n            if (curr.left == null \u0026\u0026 curr.right == null) {\n                return count;\n            }\n        }\n        return 0;\n    }\n}\n```\n\nLet us now write some unit tests to cover all scenarios like empty tree, tree with single node and a tree with depth 2.\n\n```java\n@Test\npublic void testMinDepth() {\n    // Create a binary tree: 1 -\u003e 2 -\u003e 4 (leaf)\n    //                         \\\n    //                          3 (leaf)\n    TreeNode root = new TreeNode(1);\n    root.left = new TreeNode(2);\n    root.right = new TreeNode(3);\n    root.left.left = new TreeNode(4);\n\n    // Create an instance of BSTDepth\n    BinarySearchTreeDepth bstDepth = new BinarySearchTreeDepth();\n\n    // Test the minDepth method\n    int result = bstDepth.minDepth(root);\n\n    // The minimum depth in this case is 2\n    assertEquals(2, result);\n}\n\n@Test\npublic void testMinDepthEmptyTree() {\n    BinarySearchTreeDepth bstDepth = new BinarySearchTreeDepth();\n    int result = bstDepth.minDepth(null);\n\n    // The minimum depth of an empty tree is 0\n    assertEquals(0, result);\n}\n\n@Test\npublic void testMinDepthSingleNodeTree() {\n    TreeNode root = new TreeNode(1);\n    BinarySearchTreeDepth bstDepth = new BinarySearchTreeDepth();\n    int result = bstDepth.minDepth(root);\n\n    // The minimum depth of a single-node tree is 1\n    assertEquals(1, result);\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"43:Te68,"])</script>
1<script>self.__next_f.push([1,"\nGiven a singly linked list where elements are sorted in ascending order, convert it to a height balanced Binary Search Tree (BST).\n\nTo convert a sorted singly linked list to a height-balanced Binary Search Tree (BST), we will use the recursive approach. The key idea is to find the middle element of the linked list, make it the root of the BST, and then recursively do the same for the left and right halves of the linked list.\n\n#### Java implementation\n\n```java\nclass ListNode {\n    int val;\n    ListNode next;\n\n    ListNode(int val) {\n        this.val = val;\n    }\n}\n\nclass TreeNode {\n    int val;\n    TreeNode left;\n    TreeNode right;\n\n    TreeNode(int val) {\n        this.val = val;\n    }\n}\n\npublic class SortedListToBST {\n    private TreeNode sortedListToBST(ListNode head) {\n        if (head == null) {\n            return null;\n        }\n\n        return sortedListToBST(head, null);\n    }\n\n    private TreeNode sortedListToBST(ListNode head, ListNode tail) {\n        if (head == tail) {\n            return null;\n        }\n\n        ListNode slow = head;\n        ListNode fast = head;\n\n        // Using the slow and fast pointers to find the middle element\n        while (fast != tail \u0026\u0026 fast.next != tail) {\n            slow = slow.next;\n            fast = fast.next.next;\n        }\n\n        // The root node with the middle element\n        TreeNode root = new TreeNode(slow.val);\n\n        // Recursively build the left and right subtrees\n        root.left = sortedListToBST(head, slow);\n        root.right = sortedListToBST(slow.next, tail);\n\n        return root;\n    }\n\n    public static void main(String[] args) {\n        // Example usage\n        SortedListToBST converter = new SortedListToBST();\n\n        // Create a sorted linked list\n        ListNode head = new ListNode(-10);\n        head.next = new ListNode(-3);\n        head.next.next = new ListNode(0);\n        head.next.next.next = new ListNode(5);\n        head.next.next.next.next = new ListNode(9);\n\n        // Convert the linked list to a balanced BST\n        TreeNode result = converter.sortedListToBST(head);\n\n        System.out.println(\"Inorder traversal of the resulted BST:\");\n        inorderTraversalBST(result);\n    }\n\n    private static void inorderTraversalBST(TreeNode result) {\n        if (result != null) {\n            inorderTraversalBST(result.left);\n            System.out.print(result.val + \" \");\n            inorderTraversalBST(result.right);\n        }\n    }\n}\n```\n\n**Output**\n\n```text\nInorder traversal of the resulted BST:\n-10 -3 0 5 9\n```\n\n### Complexity Analysis\n\n```text\nTime Complexity: O(n)\nSpace Complexity: O(log n) (call stack) + O(n) (additional space)\n```\n\n#### Time Complexity\n\n-   The time complexity is mainly determined by the recursive method to convert the sorted linked list to a balanced BST. In each recursive call, we perform constant-time operations, such as creating nodes and updating pointers.\n-   The number of recursive calls is proportional to the number of nodes in the linked list.\n-   Therefore, the time complexity is **O(n)**, where **n** is the number of nodes in the linked list.\n\n#### Space Complexity\n\n-   The space complexity is influenced by the space required for the recursive calls on the call stack.\n-   In the worst case, the maximum depth of the recursion is equal to the height of the balanced BST.\n-   The height of a balanced BST constructed from a sorted linked list is approximately `log₂(n)`, where n is the number of nodes.\n-   Therefore, the space complexity of the call stack is `O(log n)`.\n-   There is additional space required for the linked list nodes and the BST nodes. However, these contribute at `most O(n)` to the space complexity.\n"])</script>
1<script>self.__next_f.push([1,"44:Ta12,"])</script>
1<script>self.__next_f.push([1,"\nGiven an input string, reverse the string word by word. For example, for the given string \"the sky is blue\", the program should return \"blue is sky the\".\n\nWe first split the string into a word array, and then iterate through the array and add each element of a new string.\n\n**Note:** String Builder should be used to avoid creating too many Strings. If the string is very long, using String is not scalable since String is immutable and too many objects will be created and garbage collected.\n\n```java\npublic class ReverseWords {\n\n    public static void main(String[] args) {\n        String input = \"the sky is blue\";\n        String result = reverseWords(input);\n        System.out.println(\"Original string: \" + input);\n        System.out.println(\"Reversed words: \" + result);\n    }\n\n    private static String reverseWords(String str) {\n        if (str == null || str.isEmpty()) {\n            return \"\";\n        }\n\n        String[] arr = str.split(\" \");\n        StringBuilder reversed = new StringBuilder();\n        for (int i = arr.length - 1; i \u003e= 0; --i) {\n            if (!arr[i].isEmpty()) {\n                reversed.append(arr[i]).append(\" \");\n            }\n        }\n        return reversed.isEmpty() ? \"\" : reversed.substring(0, reversed.length() - 1);\n    }\n}\n```\n\n**Output**\n\n```text\nOriginal string: the sky is blue\nReversed words: blue is sky the\n```\n\n### Complexity Analysis:\n\n```text\nTime Complexity: O(n + m)\nSpace Complexity: O(m + n)\n```\n\n#### Time Complexity:\n\n-   The `split()` method splits the input string into an array of words based on the space character `(' ')`. It has a time complexity of `O(n)`, where n is the length of the input string.\n-   The subsequent loop that iterates over the array and appends non-empty words to the `StringBuilder` has a time complexity of O(m), where m is the total number of words in the array.\n-   Overall, the time complexity of the reverseWords function is **O(n + m)**, where n is the length of the input string and m is the number of words.\n\n#### Space Complexity:\n\n-   The space complexity is determined by the additional space required to store the array of words (arr) and the StringBuilder (reversed). The space required for the array of words is **O(m)**, where m is the number of words in the input string.\n-   The space required for the `StringBuilder` is proportional to the length of the reversed string, which can be up to `O(n)`, where n is the length of the input string.\n-   Therefore, the overall space complexity is O(m + n), where m is the number of words and n is the length of the input string.\n"])</script>
1<script>self.__next_f.push([1,"45:Ta00,"])</script>
1<script>self.__next_f.push([1,"\n💡\n\n_**Chapter 7- Working with Profiles in Maven**_, delves into managing profiles in Maven to customize the project’s build configuration for different environments or conditions.\n\nMaven allows you to customize a project’s build configuration for different environment or conditions. This can be done through profiles.\n\nProfiles allow you to define a set of configuration options that are activated only under certain conditions, such as a specific environment or build context. Profiles can be defined in a project's pom.xml file, or an external XML file. Here's an example of a profile defined in a `pom.xml` file:\n\n```xml\n\u003cproject\u003e\n  ...\n  \u003cprofiles\u003e\n\n    \u003cprofile\u003e\n      \u003cid\u003edev\u003c/id\u003e\n      \u003cactivation\u003e\n        \u003cactiveByDefault\u003etrue\u003c/activeByDefault\u003e\n      \u003c/activation\u003e\n      \u003cproperties\u003e\n        \u003cdatabase.driver\u003ecom.mysql.jdbc.Driver\u003c/database.driver\u003e\n        \u003cdatabase.url\u003ejdbc:mysql://localhost/devdb\u003c/database.url\u003e\n        \u003cdatabase.username\u003edevuser\u003c/database.username\u003e\n        \u003cdatabase.password\u003edevpass\u003c/database.password\u003e\n      \u003c/properties\u003e\n    \u003c/profile\u003e\n\n    \u003cprofile\u003e\n      \u003cid\u003eprod\u003c/id\u003e\n      \u003cproperties\u003e\n        \u003cdatabase.driver\u003ecom.mysql.jdbc.Driver\u003c/database.driver\u003e\n        \u003cdatabase.url\u003ejdbc:mysql://localhost/proddb\u003c/database.url\u003e\n        \u003cdatabase.username\u003eproduser\u003c/database.username\u003e\n        \u003cdatabase.password\u003eprodpass\u003c/database.password\u003e\n      \u003c/properties\u003e\n    \u003c/profile\u003e\n  \u003c/profiles\u003e\n\n  ...\n\u003c/project\u003e\n```\n\nIn this example, two profiles are defined: `dev` and `prod`. The `dev` profile is active by default and sets the database configuration properties for a development environment. The `prod` profile sets the database configuration properties for a production environment.\n\nTo activate a profile, you can use the `-P` command line option when running Maven. For example, to activate the `prod` profile, you can run the following command:\n\n```bash\nmvn clean install -Pprod\n```\n\nThis will activate the `prod` profile, and use the database configuration properties defined in that profile.\n\nIn addition to property settings, profiles can also define other configuration options such as plugin configurations, build profiles, and more. By using profiles, you can create a flexible and customizable build configuration that can be tailored to different environments and situations.\n\n## Wrap up\n\nThe Maven course is an essential training program for Java developers to create robust, maintainable, and scalable Java applications. Hope this course helps you to to learn maven build process for your next Java application.\n"])</script>
1<script>self.__next_f.push([1,"46:T5fd,"])</script>
1<script>self.__next_f.push([1,"\nHere are some of the most popular Maven commands that every Java developer must know:\n\n`mvn clean`: This command is used to clean the project's target directory, which contains the compiled classes and generated artifacts. It removes all files generated during the build process.\n\n`mvn compile`: This command is used to compile the source code of the project.\n\n`mvn test`: This command is used to run the tests for the project.\n\n`mvn package`: This command is used to create an executable JAR or WAR file of the project.\n\n`mvn install`: This command is used to install the project's JAR or WAR file into the local Maven repository.\n\n`mvn deploy`: This command is used to deploy the project's JAR or WAR file to a remote Maven repository.\n\n`mvn dependency:tree`: This command is used to display the project's dependency tree, showing all the dependencies and their transitive dependencies.\n\n`mvn help`: This command is used to display the Maven help information, including the available commands and their descriptions.\n\n`mvn archetype:generate`: This command is used to generate a new Maven project based on a specified project template, also known as an archetype.\n\n`mvn site`: This command is used to generate the project's documentation site, including reports on code quality, test results, and more.\n\nThese are just a few of the most popular Maven commands, but there are many more available.\n\nBy using these commands, you can easily build, test, and deploy your Java projects, and manage their dependencies and documentation.\n"])</script>
1<script>self.__next_f.push([1,"47:T1704,"])</script>
1<script>self.__next_f.push([1,"\n💡\n\n_**Chapter 5**_**,** _Local, Central, and Remote Maven Repository_, walks you through the various repository types and how they can be configured in the settings.xml file. It also covers the order maven attempts to resolve the dependency from different repositories.\n\nMaven uses a centralised repository of software libraries called the Maven Repository to manage and download project dependencies. The Maven Repository is divided into three types: Local, Central, and Remote.\n\n## 3.1 Local Maven Repository\n\nThe local repository is a directory on the developer's machine where all the dependencies for a specific project are stored. When a developer builds a project, Maven checks for the required dependencies in the local repository. If the dependency is not available, it is downloaded from a remote repository and stored in the local repository for future use. This reduces the build time when you build your project very often.\n\nThe local repository in Maven is usually located in the user's home directory under the .m2 folder.\n\n### 3.1.1 Change the Local Maven Repository Path\n\nHowever, you can change the path to the local repository by modifying the **settings.xml** file, which is in the **conf** directory of your Maven installation.\n\nHere are the steps to change the Local Maven Repository path:\n\n1.  Locate the XML file in the **conf** directory of your Maven installation.\n\n2.  Open the XML file in a text editor.\n\n3.  Search for the `\u003clocalRepository\u003e` tag in the file. If the tag is not present, you can add it to the file.\n\n4.  Modify the value of the \u003clocalRepository\u003e tag to the desired location. For example, if you want to change the local repository to a folder named my-local-repo in the `D:\\\\drive`, the tag's value would be `\u003clocalRepository\u003eD:\\\\my-local-repo\u003c/localRepository\u003e`.\n\n5.  Save the changes to the XML file.\n\nOnce you have saved the changes to the settings.xml file, the new location will be used for all future Maven builds. Any dependencies that were previously downloaded to the old local repository will not be automatically moved to the new location, so you may need to copy them manually if required.\n\n## 3.2 Central Maven Repository\n\nThe Central Repository is the default remote repository used by Maven. It contains a vast collection of open-source libraries and dependencies, making it a one-stop shop for most projects. When Maven needs to download a dependency, it first looks in the local repository and then in the Central Repository.\n\nThe **central maven repository** is managed by the Apache community. There are almost all Java libraries that exist in it. You can browse it at [https://repo1.maven.org/maven2/](https://repo1.maven.org/maven2/).\n\nWhen building a project, if it cannot find any dependent jars in the local Maven repository it will search in the central Maven repository and download those jars if found. You can also search for an artifact at [http://search.maven.org](http://search.maven.org/) if you want to download the artifact’s pom or jars.\n\n## 3.3 Remote Maven Repository\n\nA remote repository is a repository of dependencies located on a remote server, typically managed by a third-party organization. Maven can be configured to use multiple remote repositories, and dependencies can be downloaded from these repositories as needed. Developers can also publish their artifacts to a remote repository for use by other projects.\n\nHere's an example of how to use a remote Maven repository in a Java project:\n\n1.  Open your project's XML file in a text editor.\n\n2.  Add a new `\u003crepositories\u003e` section to the file, if it doesn't exist already. For example:\n\n```xml\n\u003crepositories\u003e\n    \u003crepository\u003e\n        \u003cid\u003ecentral\u003c/id\u003e\n        \u003cname\u003eCentral Repository\u003c/name\u003e\n        \u003curl\u003e\u003chttps://repo.maven.apache.org/maven2\u003e\u003c/url\u003e\n    \u003c/repository\u003e\n    \u003crepository\u003e\n        \u003cid\u003ejcenter\u003c/id\u003e\n        \u003cname\u003eJCenter\u003c/name\u003e\n        \u003curl\u003e\u003chttps://jcenter.bintray.com\u003e\u003c/url\u003e\n    \u003c/repository\u003e\n\u003c/repositories\u003e\n```\n\nIn this example, we have added two remote repositories - the Central Repository and JCenter. The
1se repositories are identified by a unique ID, which is used to reference them in the project's dependencies.\n\n3.  Now you can add dependencies to your project that are hosted in these remote repositories. For example:\n\n```xml\n\u003cdependencies\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003ejunit\u003c/groupId\u003e\n    \u003cartifactId\u003ejunit\u003c/artifactId\u003e\n    \u003cversion\u003e4.13.2\u003c/version\u003e\n    \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.google.guava\u003c/groupId\u003e\n    \u003cartifactId\u003eguava\u003c/artifactId\u003e\n    \u003cversion\u003e30.1.1-jre\u003c/version\u003e\n\u003c/dependency\u003e\n\u003c/dependencies\u003e\n```\n\nIn this example, we are adding two dependencies to the project - JUnit and Guava. JUnit is hosted in the Central Repository, while Guava is hosted in JCenter.\n\n## 3.4 Order of Dependency Search in Maven\n\nThe order in which Maven searches for dependencies in the local and remote repositories is as follows:\n\n1.  First, Maven looks for the dependency in the local repository. If the dependency is not found, it proceeds to the next step.\n\n2.  Next, Maven looks at the remote repositories in the order they are defined in the XML file. If the dependency is found in a remote repository, it is downloaded and stored in the local repository for future use.\n\n3.  If the dependency is not found in any of the remote repositories, Maven will report a build error.\n\nSo, in summary, the dependency search order in Maven is first the local repository, followed by the remote repositories in the order they are defined in the `pom.xml` file.\n\nIn summary, the local repository is where Maven stores project-specific dependencies, while the remote repository is where Maven can retrieve dependencies from third-party organizations. The central repository is the default remote repository used by Maven, which provides access to a vast collection of open-source libraries and dependencies.\n"])</script>
1<script>self.__next_f.push([1,"48:T2bfc,"])</script>
1<script>self.__next_f.push([1,"\n💡\n\n_**Chapter 4**_**,** _Dependency Management in Maven_, this chapter discusses one of the most important concepts of dependency management, direct and transitive dependencies, and discusses various maven scopes.\n\nOne of the key features of Maven is its dependency management system, which allows you to declare the external libraries and other projects that your project depends on. Maven just not support dependencies for a single project, but it can manage the dependencies for multi-module projects by maintaining a high degree of control and stability.\n\n## 4.1 Dependency Management\n\nIn Maven, a project is a collection of source code, build scripts, configuration files, and resources that are organized into a standard directory structure. The project directory contains a file called pom.xml, which is the **Project Object Model (POM)** that defines the project's dependencies, build settings, and other configuration details.\n\nMaven uses the `pom.xml` file to manage dependencies, and it provides several benefits, including:\n\n-   **Automatic download** and caching of dependencies from remote repositories.\n\n-   **Transitive dependency** resolution, which means that Maven can automatically download and include the dependencies of your dependencies.\n\n-   **Dependency conflict resolution**, which means that Maven can automatically resolve conflicts when multiple dependencies require different versions of the same library.\n\n-   **Consistent version management** means that you can specify a range of acceptable versions for a dependency, and Maven will automatically select the highest compatible version.\n\nTo declare a dependency in Maven, you simply add a dependency tag to the pom.xml file, specifying the group ID, Artifact ID, and version of the library that you want to use. For example, the following code declares a dependency on the Apache Commons Lang and jUnit library.\n\n```xml\n\u003cproject xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\"\u003e\n  \u003cmodelVersion\u003e4.0.0\u003c/modelVersion\u003e\n  \u003cgroupId\u003ecom.stacktips\u003c/groupId\u003e\n  \u003cartifactId\u003emaven-hello-world\u003c/artifactId\u003e\n  \u003cpackaging\u003ejar\u003c/packaging\u003e\n  \u003cversion\u003e1.0-SNAPSHOT\u003c/version\u003e\n  \u003cname\u003emaven-hello-world\u003c/name\u003e\n  \u003curl\u003ehttp://maven.apache.org\u003c/url\u003e\n  \u003cdependencies\u003e\n\n    \u003cdependency\u003e\n      \u003cgroupId\u003ejunit\u003c/groupId\u003e\n      \u003cartifactId\u003ejunit\u003c/artifactId\u003e\n      \u003cversion\u003e3.8.1\u003c/version\u003e\n      \u003cscope\u003etest\u003c/scope\u003e\n    \u003c/dependency\u003e\n\n    \u003cdependency\u003e\n      \u003cgroupId\u003eorg.apache.commons\u003c/groupId\u003e\n      \u003cartifactId\u003ecommons-lang3\u003c/artifactId\u003e\n      \u003cversion\u003e3.12.0\u003c/version\u003e\n    \u003c/dependency\u003e\n\n  \u003c/dependencies\u003e\n\u003c/project\u003e\n```\n\nWhen you build the project using Maven, it will automatically download the `commons-lang3-3.12.0.jar` file from the remote repository and include it in your project's **classpath**.\n\n### 4.1.1 Transitive Dependency\n\nThere are primary two types of dependencies: direct dependency and transitive dependencies. Direct dependencies are the packages that are defined in your dependency descriptor or pom.xml file.\n\nTransitive dependencies are the direct dependencies of your direct dependencies. For example, in the following figure, package A depends directly on B and D; they are called direct dependencies. However, package B depends on package C, and though you have not included it directly in your project, you will need that for package B to work correctly. The package C is considered a transitive dependency for package A.\n\n[![](/media/summernote/Chapter_4-_Dependency_Management_in_Maven.png)](https://media.stacktips.com/media/uploads/summernote/Chapter_4-_Dependency_Management_in_Maven.png)\n\nFigure 4.2 Direct and Transitive Dependencies Maven\n\n**Automatic Transitive Dependencies resolution:** Maven has an inbuilt feature that automatically resolves the Transitive Dependencies for your project. What that means is that, if your project is dependent on some libraries and those libraries are dependent on other libraries, you only specify your project’s dependencies, and Maven takes care of other dependencies.\n\n**Cyclic dependency:** There is no limit to the levels that dependencies can be gathered from and will only cause a problem if cyclic dependency is discovered. If your project depends on A and A depends on C, and C depends on B and B depends on A.\n\n**Dependency Mediation:** When multiple versions of a package are encountered, you can always guarantee a version by declaring it explicitly in the project’s POM. If two depen
1dency versions are at the same depth in the dependency tree, the order in the declaration that counts, the first declaration wins.\n\n**Excluded Dependencies:** If Project X depends on project Y, and project Y depends on project Z, project X can explicitly exclude project Z as a dependency using the exclusion element.\n\nOverall, Maven's project and dependency management features make it easy to create and manage complex Java projects, while minimising the amount of manual configuration and maintenance required.\n\n### 4.1.2 Dependency Scope\n\nThe Dependency scope controls when and where a dependency is included in your project. It is used to restrict the transitivity of a dependency, whether a dependency's dependencies are also included or not. There are 6 scopes available:\n\n-   `compile` - This is the default scope. The dependencies defined with this scope are available in all (compilation, testing, runtime) **classpaths** of a project.\n\n-   `provided` - This is used when JDK or the runtime environment such as the servlet container is going to provide a dependency at runtime. These dependencies are not packaged with your application.\n\n-   `runtime` - This scope indicates that the dependency is not required for compilation but is needed at runtime.\n\n-   `test` - This scope indicates the dependency is required during the test compilation and execution phases.\n\n-   `system` - This scope is like provided except that you must explicitly provide a JAR file and not looked up in the repository.\n\n-   `import` - This is used inside a `dependencymanagement` It indicates that the specified POM should be replaced with the dependencies in that POM’s `dependencymanagement` section.\n\nFor specifying the scope in pom.xml file we can use the syntax as follows:\n\n```xml\n\u003cdependencies\u003e\n  \u003cdependency\u003e\n    \u003cgroupId\u003eorg.apache.logging.log4j\u003c/groupId\u003e\n    \u003cartifactId\u003elog4j-core\u003c/artifactId\u003e\n    \u003cversion\u003e2.19.0\u003c/version\u003e\n    \u003cscope\u003eruntime\u003c/scope\u003e\n  \u003c/dependency\u003e\n  \u003cdependency\u003e\n    \u003cgroupId\u003ejunit\u003c/groupId\u003e\n    \u003cartifactId\u003ejunit\u003c/artifactId\u003e\n    \u003cversion\u003e4.13.2\u003c/version\u003e\n    \u003cscope\u003etest\u003c/scope\u003e\n  \u003c/dependency\u003e\n\u003c/dependencies\u003e\n```\n\nSystem dependencies are specified with systemPath under system scope, and they are always available and are not looked up in the repository. Here is how you can use system scope.\n\n```xml\n\u003cdependencies\u003e\n  \u003cdependency\u003e\n    \u003cgroupId\u003ecom.provider\u003c/groupId\u003e\n    \u003cartifactId\u003eartifact-id\u003c/artifactId\u003e\n    \u003cversion\u003e1.0.0\u003c/version\u003e\n    \u003cscope\u003esystem\u003c/scope\u003e\n    \u003csystemPath\u003e${home}/lib/external-lib-1.0.0.jar\u003c/systemPath\u003e\n  \u003c/dependency\u003e\n\u003c/dependencies\u003e\n```\n\n## 4.2 Maven Properties\n\nProperties in Maven can be used to simplify the configuration of your project, making it more maintainable, and reducing the amount of duplicated code.\n\nFor example, you can create a property defining the version of a commonly used library, and then use that property throughout your pom.xml file. If you need to update the library version in the future, you can simply change the property value, rather than updating it in multiple places all over the `pom.xml` file.\n\nThe properties in Maven are defined using the `\u003cproperties\u003e` element and are referenced using the `${property}` syntax.\n\nHere's an example of how to define and use a property in a pom.xml file:\n\n```xml\n\u003cproject\u003e\n  \u003cgroupId\u003ecom.stacktips\u003c/groupId\u003e\n  \u003cartifactId\u003eyour-artifact-id\u003c/artifactId\u003e\n  \u003cversion\u003e1.0.0\u003c/version\u003e\n  \u003cproperties\u003e\n    \u003cjunit.version\u003e4.13.2\u003c/junit.version\u003e\n  \u003c/properties\u003e\n  \u003cdependencies\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003ejunit\u003c/groupId\u003e\n        \u003cartifactId\u003ejunit\u003c/artifactId\u003e\n        \u003cversion\u003e${junit.version}\u003c/version\u003e\n        \u003cscope\u003etest\u003c/scope\u003e\n    \u003c/dependency\u003e\n  \u003c/dependencies\u003e\n\u003c/project\u003e\n```\n\nIn this example, the `junit.version` property is defined in the `\u003cproperties\u003e` element, and is given the value 4.13.2. Later in the file, the `${junit.version}` syntax is used to reference the property value as the version number for the JUnit dependency.\n\n## 4.3 Build Element in Maven\n\nThe build element in Maven is used to define the build process for a project. It contains a set of configuration options that control how the project is compiled, tested, and packaged. The Maven project we have generated in the previous chapter has a very straightforward structure and dependencies.\n\nMaven uses default build configuration and provides a sensible default for simple Java projects. Hence, you don’t see the `\u003cbuild\u003e` element inside our pom.xml file.\n\nHowever, as the complexity increases you will be required to customize your build configurations to maintain consistency in the build process for all developers working on the same project. Here are some of the common elements that can be defined within the build element in Maven:\n\n-   `plugins`: Maven plugins are used to extend the build process with additional functionality. The plugins element is used to configure the plugins that should be used for this project.\n\n-   The `sourceDirectory` and `testSourceDirectory`: These elements specify the location of the source code and test code directories for the project.\n\n-   The resources and `testResources`, elements specify additional resources that should be included in the project, such as configuration files or data files.\n\n-   The plugins element is used to configure the plugins that should be used for this project. Plugins can be used for a variety of tasks, such as running tests, generating documentation, or creating executable JAR files.\n\n-   The extensions element is used to specify Maven extensions, which are used to modify or enhance the build process. Extensions are like plugins, but they are loaded before the plugins and can modify the behavior of the core Maven system.\n\nHere's an example of a build element in a pom.xml file:\n\n```xml\n\u003cbuild\u003e\n  \u003csourceDirectory\u003esrc/main/java\u003c/sourceDirectory\u003e\n  \u003ctestSourceDirectory\u003esrc/test/java\u003c/testSourceDirectory\u003e\n  \u003cresources\u003e\n    \u003cresource\u003e\n      \u003cdirectory\u003esrc/main/resources\u003c/directory\u003e\n    \u003c/resource\u003e\n  \u003c/resources\u003e\n  \u003ctestResources\u003e\n    \u003ctestResource\u003e\n      \u003cdirectory\u003esrc/test/resources\u003c/directory\u003e\n    \u003c/testResource\u003e\n  \u003c/testResources\u003e\n  \u003cplugins\u003e\n    \u003cplugin\u003e\n      \u003cgroupId\u003eorg.apache.maven.plugins\u003c/groupId\u003e\n      \u003cartifactId\u003emaven-compiler-plugin\u003c/artifactId\u003e\n      \u003cversion\u003e3.8.1\u003c/version\u003e\n      \u003cconfiguration\u003e\n        \u003csource\u003e1.8\u003c/source\u003e\n        \u003ctarget\u003e1.8\u003c/target\u003e\n      \u003c/configuration\u003e\n    \u003c/plugin\u003e\n  \u003c/plugins\u003e\n\u003c/build\u003e\n```\n\nIn this example, the build element is used to define the source code and test code directories, as well as the resources and test resources directories. Additionally, the maven-compiler-plugin is configured with a specific source and target version.\n"])</script>
1<script>self.__next_f.push([1,"49:T22a4,"])</script>
1<script>self.__next_f.push([1,"\n💡\n\n_**Chapter 3**_**,** _Creating Java Project using Maven_, walks you through a step-by-step process to create a Maven project using the Maven command line utility and discusses building and running Java applications. It also discusses briefly about the maven build life cycle.\n\nMaven has several archetypes predefined, you can use any of those archetypes and build a basic project in a few seconds. In this chapter, we will use the maven-archetype-quickstart, archetype to create a basic Java project with maven directories conventions.\n\n## 3.1 Creating a Maven Project\n\nBefore you create a Java project using the maven command line, first create a new directory for your project. For example, create a directory called **\"maven-hello-world”**\n\n```bash\nmkdir maven-hello-world\n```\n\nNavigate to the newly created directory in your terminal:\n\n```bash\ncd maven-hello-world\n```\n\nWe can generate a maven project from the terminal using the `mvn archetype:generate` command. This command generates a new Maven project based on the template or archetype selected. For example, in this case we will use the `maven-archetype-quickstart` archetype to generate a simple Java project.\n\n```bash\nmvn archetype:generate\n     -DgroupId=com.stacktips\n     -DartifactId=maven-hello-world\n     -DarchetypeArtifactId=maven-archetype-quickstart\n     -DinteractiveMode=false\n```\n\nYou don’t have to remember each of the parameters provided above. Just use the `interactiveMode=true`, so that Maven asks for all the required parameters.\n\n[![](/media/summernote/creating-maven-project.png)](https://media.stacktips.com/media/uploads/summernote/creating-maven-project.png)\n\nFigure 3.1 - creating java project using Maven command line\n\nIn this command, the groupId and `artifactId` are the unique identifiers for your project. The `archetypeArtifactId` specifies the archetype to use, which in this case is the `maven-archetype-quickstart` archetype, which creates a simple Java project with a main class.\n\n## 3.2 Building the Maven Project\n\nYou can build your project in a shell environment but is better to work inside of a Java IDE such as IntelliJ, Eclipse, or VS Code. An Integrated **Development Environment (IDE)** is a tool that helps to streamline the coding, debugging, and project management for developers. It offers features like code editing, refactoring, debugging, integrated terminal, and many other features to support application development.\n\nEclipse and VS Code have good support for Java development, but IntelliJ is one of the strong contenders with a wide range of features to boost Java developer productivity. Throughout this book, we will use the IntelliJ code editor for working with the Maven project.\n\nIntelliJ offers two versions of the IDE, IntelliJ IDEA Community (Free) and IntelliJ Ultimate (Licensed). A few of the features are limited only to the Ultimate edition, but the Free community version is sufficient for Java development.\n\nIf you haven’t installed it, you can follow the official installation guide to download and install for your Operating System: [https://www.jetbrains.com/idea/download/](https://www.jetbrains.com/idea/download/)\n\nWhen the project is opened in IntelliJ, the project will be recognized by the IDE as a maven project and all the dependencies will be resolved and added to the **“classpath”** automatically. The following screenshot depicts the project structure created by the above command.\n\n[![](/media/summernote/mave-java-project-structure.png)](https://media.stacktips.com/media/uploads/summernote/mave-java-project-structure.png)\n\nFigure 3.2 Maven Java project structure\n\nThe dependencies and maven configuration are defined inside the maven configuration file pom.xml, pom means **Project Object Model**.\n\nNavigate to the project directory and build the project using the `mvn package` command.\n\n```bash\nmvn package\n```\n\nThis will compile the project, run the tests, package will generate JAR/WAR as per the build configuration defined in the POM file. You can see a console output as follows:\n\n```text\n[INFO] Scanning for projects...\n[INFO] \n[INFO] ------------------\u003c com.stacktips:maven-hello-world \u003e-------------------\n[INFO] Building maven-hello-world 1.0-SNAPSHOT\n[INFO]   from pom.xml\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO] \n[INFO] --- resources:3.3.1:resources (default-resources) @ maven-hello-world ---\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /Users/nilanchal.panigrahy/Documents/github/StackTipsLab/maven-beginners-guide/maven-hello-world/src/main/resources\n[INFO] \n[INFO] --- compiler:3.11.0:compile (default-compile) @ maven-hello-world ---\n[INFO] Nothing to compile - all classes are up to date\n[INFO] \n[INFO] --- resources:3.3.1:testResources (default-testResources) @ maven-hello-world ---\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /Users/nilanchal.panigrahy/Documents/github/StackTipsLab/maven-beginners-guide/maven-hello-world/src/test/resources\n[INFO] \n[INFO] --- compiler:3.11.0:testCompile (default-testCompile) @ maven-hello-world ---\n[INFO] Nothing to compile - all classes are up to date\n[INFO] \n[INFO] --- surefire:3.2.2:test (default-test) @ maven-hello-world ---\n[INFO] Using auto detected provider org.apache.maven.surefire.junit.JUnit3Provider\n[INFO] \n[INFO] -------------------------------------------------------\n[INFO]  T E S T S\n[INFO] -------------------------------------------------------\n[INFO] Running com.stacktips.AppTest\n[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.012 s -- in com.stacktips.AppTest\n[INFO] \n[INFO] Results:\n[INFO] \n[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n[INFO] \n[INFO] \n[INFO] --- jar:3.3.0:jar (default-jar) @ maven-hello-world ---\n[INFO] Building jar: /Users/nilanchal.panigrahy/Documents/github/StackTipsLab/maven-beginners-guide/maven-hello-world/target/maven-hello-world-1.0-SNAPSHOT.jar\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time:  1.629 s\n[INFO] Finished at: 2024-01-06T20:02:48Z\n[INFO] ------------------------------------------------------------------------\n```\n\nRun the project: You can run the project using the java -cp target/my-app-1.0-SNAPSHOT.jar com.example.app.App command. This will execute the main method in the App class.\n\n```bash\njava -cp target/maven-hello-world-1.0-SNAPSHOT.jar com.stacktips.App\n```\n\nCongratulations! You have created and built your first Java project using the Maven command line!\n\n## 3.3 Maven Build Lifecycle\n\nMaven build lifecycles are a series of phases that define the build process of a Maven project. There are three build lifecycles in Maven:\n\n-   **default**: This is the main build lifecycle in Maven. It includes the following phases: `validate`, `compile`, `test`, `package`, `verify`, and install. These phases are executed in order when you run the maven command with no arguments.\n\n-   **clean**: This lifecycle is used to clean the build directory of a project. It includes the following phases: `pre-clean`, `clean`, and `post-clean`.\n\n-   **site**: This lifecycle is used to generate project documentation. It includes the following phases: `pre-site`, `site`, `post-site`, `site-deploy`. The site-deploy phase is optional and is used to deploy the generated documentation to a web server.\n\nEach lifecycle c
1onsists of a set of phases, which are executed in order. When you run a specific phase, all previous phases in that lifecycle are also executed. For example, when you run the package phase in the default lifecycle, the validate, compile, and test phases are also executed.\n\n[![](/media/summernote/dependencies-Page-2.drawio.png)](https://media.stacktips.com/media/uploads/summernote/dependencies-Page-2.drawio.png)\n\nFigure 3.3 Maven build lifecycle\n\nHere's a brief description of each phase in the default lifecycle:\n\n-   **validate:** It validates the project is correct and all necessary information is available.\n\n-   **compile:** It compiles the source code of the project.\n\n-   **test:** It tests the compiled source code using a suitable unit testing framework.\n\n-   **package:** It takes the compiled code and packages it in its distributable format, such as a JAR file.\n\n-   **verify:** To run any checks to verify the package is valid and meets quality criteria.\n\n-   **install:** To install the package into the local repository, for use as a dependency in other projects.\n\n-   **deploy:** To copy the final package to the remote repository for sharing with other developers and projects.\n"])</script>
1<script>self.__next_f.push([1,"4a:T2df1,"])</script>
1<script>self.__next_f.push([1,"\n💡\n\n_**Chapter 2**_, _Installing and Configuring Maven_, discusses the prerequisites for using Maven, and guides through the Maven installation process. It also discusses briefly about the Maven ecosystem and the Apache Software License.\n\nMaven is currently distributed in several formats for your convenience. This chapter contains instructions for installing Maven for different platforms. If you are interested in the details of your Maven installation, this entire chapter will give you an overview of what you’ve installed and the Apache Software License.\n\n## 2.1 Prerequisites\n\nAs Maven is a Java tool, before proceeding with using Maven you need to ensure the Java JDK is installed in your computer. At the time of writing this e-book, the latest stable Java release of Java is JDK 17.\n\nYou have two choices when it comes to installing Java. You either use the Oracle JDK or Open JDK. Oracle JDK offers all the features of Open JDK, plus some proprietary features and commercial support from Oracle. The Open JDK is the open-source version of Java, and it is free to use for both personal and commercial projects.\n\nThere are many different distributions of OpenJDK available, some of the popular distributions are Amazon Corretto, Microsoft JDK, Azul Zulu, Red Hat OpenJDK, etc. You can install any of the OpenJDK distributions for working with Maven, but before you do, It is recommended that you read and understand the Licence agreements and terms of use from these distributors.\n\nFor installation, we have many different approaches, we can install Java using a package manager such as Homebrew or SDKMan. Alternatively, we can use the manual installation process.\n\nThis chapter covers the Java installation process using the SDKMan and Homebrew. For installation in Windows, we have a section with relevant links.\n\n### 2.1.1 Installing Java JDK using SDKMan\n\nSDKMan is a command line utility used for installing and managing multiple versions of the SDKs. This works for MacOS and Linux, Windows WSL. The SDKMan simplifies the installation, management, and switching between different versions of Java SDK effortlessly.\n\n💡\n\nIf you don’t have SDKMan installed, follow the official installation guide from [https://sdkman.io/install](https://sdkman.io/install) to install the SDKMan package manager. Once installed, you can continue with this chapter.\n\nBefore we install let us first get the list of available Java versions. You can do that using the following command:\n\n```bash\nsdk list java\n```\n\nThis will return a list of all available Java versions.\n\n[![](/media/summernote/install_java_in_mac_using_homebrew-min.png)](https://media.stacktips.com/media/uploads/summernote/install_java_in_mac_using_homebrew-min.png)\n\nFigure 2.1 - List of available Java versions\n\nYou can filter a specific Java version using the **grep** command.\n\n```bash\nsdk list java | grep 17\n```\n\nTo install a specific version, you need to use the distribution identifier.\n\n```bash\nsdk install java 21-amzn\n```\n\nTo check the list of installed Java versions\n\n```bash\nsdk list java | grep installed\n```\n\nTo use specific versions of Java\n\n```bash\nsdk use java 21-amzn\n```\n\nCheck if you have Java installed using the following command.\n\n```bash\njava --version\n```\n\n### 2.1.2 Installing Java JDK using Homebrew\n\nHomebrew is a free and open-source software package manager that simplifies the installation of software on MacOS (and supports Linux systems to some extent). Think of it like a one-stop shop for accessing tools and applications you might need for development, server management, homebrew experiments, or just general use.\n\n💡\n\nIf you don’t have Homebrew installed, follow the official installation guide from [https://sdkman.io/install](https://sdkman.io/install) to install the Homebrew package manager. Once installed, you can continue with this chapter.\n\nType brew search `openjdk` to find all available Java-related formulas.\n\n```bash\n$ brew search openjdk\n==\u003e Formulae\nopenjdk ✔         openjdk@11        openjdk@17 ✔     openjdk@8\n\n==\u003e Casks\nadoptopenjdk       homebrew/cask-versions/adoptopenjdk8\nmicrosoft-openjdk  homebrew/cask-versions/microsoft-openjdk11\nopenkey\n```\n\nTo show the formula details, you can use the brew info command. The Java formula always contains the latest OpenJDK version; at the time of writing, the latest is JDK 17.\n\nThe openjdk@17 formula contains the Java 17LTS version.\n\n```bash\n$ brew info openjdk@17\n==\u003e openjdk@17: stable 17.0.4.1 (bottled) [keg-only]\nDevelopment kit for the Java programming language\nhttps://
1openjdk.java.net/\n/usr/local/Cellar/openjdk@17/17.0.4.1_1 (639 files, 305.6MB)\n  Poured from bottle on 2023-09-25 at 00:00:57\nFrom: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/[email protected]\nLicense: GPL-2.0-only with Classpath-exception-2.0\n==\u003e Dependencies\nBuild: autoconf ✘\n==\u003e Requirements\nBuild: Xcode ✔\n==\u003e Caveats\nFor the system Java wrappers to find this JDK, symlink it with\n  sudo ln -sfn /usr/local/opt/openjdk@17/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-17.jdk\n\nopenjdk@17 is keg-only, which means it was not symlinked into /usr/local,\nbecause this is an alternate version of another formula.\n\nIf you need to have openjdk@17 first in your PATH, run:\n  echo 'export PATH=\"/usr/local/opt/openjdk@17/bin:$PATH\"' \u003e\u003e ~/.zshrc\n\nFor compilers to find openjdk@17 you may need to set:\n  export CPPFLAGS=\"-I/usr/local/opt/openjdk@17/include\"\n\n==\u003e Analytics\ninstall: 30,649 (30 days), 82,462 (90 days), 154,946 (365 days)\ninstall-on-request: 20,080 (30 days), 52,615 (90 days), 88,978 (365 days)\nbuild-error: 65 (30 days)\n```\n\nTo install the Open JDK 17, you can type the following command.\n\n```bash\nbrew install openjdk@17\n```\n\nCheck if you have Java installed using the following command.\n\n```bash\njava --version\n```\n\n### 2.1.3 Install Java in Windows OS\n\nThere are several choices for installing Java on Windows OS; we can install using the graphical PKG and MSI installers, or through package managers WinGet, Homebrew, apt, and yum.\n\nReferee the official refer the official Installation guide. [https://learn.microsoft.com/en-us/java/openjdk/install](https://learn.microsoft.com/en-us/java/openjdk/install)\n\nTo ensure that Java is installed correctly, open a Command Prompt or PowerShell window and enter the following command.\n\n```bash\njava -version\n```\n\n## 2.2 Install Maven on Windows\n\nThis section will drive you thought the steps to install and configure Maven on Windows Operating System.\n\n-   Download Maven from the official website: [https://maven.apache.org/download.cgi](https://maven.apache.org/download.cgi). Choose the latest binary zip archive for Windows and download it to your preferred directory. When downloading Maven, make sure you choose the latest version of Apache Maven from the website. The latest version of Maven at the time of this writing is Maven 3.9.x.\n\n![](/media/summernote/Download_maven_versions.png)  \n\n[![](/media/Chapter%202-Installing%20and%20Configuring%20Maven%20ce901c071a9c4038820947bb4648204c/Screenshot_2024-01-05_at_16.37.19.png)](Chapter%202-Installing%20and%20Configuring%20Maven%20ce901c071a9c4038820947bb4648204c/Screenshot_2024-01-05_at_16.37.19.png)\n\nFigure 2.2 - Download maven versions\n\n-   Extract the downloaded zip file to a directory on your system. For example, you could extract it to the \"**C:\\\\Program Files**\" directory.\n\n-   Set the environment variables for Maven. Open the Start menu and search for \"**Environment Variables**\". Click on \"**Edit the system environment variables**\".\n\n-   In the System Properties window, click on the \"**Environment Variables**\" button.\n\n-   Under the System Variables section, click on \"New\" to create a new variable. Set the variable name as MAVEN\\_HOME and the variable value as the path to your Maven installation directory. For example, **\"C:\\\\Program Files\\\\apache-maven-3.9.0\".**\n\n-   Next, find the \"Path\" variable under System Variables and click \"**Edit**\".\n\n-   In the Edit environment variable window, click \"**New**\" and add the path to the \"bin\" directory within your Maven installation directory. For example, **\"C:\\\\Program Files\\\\apache-maven-3.9.0\\\\bin\".**\n\n-   Click \"**OK**\" on all the windows to save the changes.\n\n-   Open a new command prompt window and run the command `mvn -version` to verify that Maven is installed correctly. You should see the version of Maven printed on the console.\n\n```bash\nmvn -version\n```\n\n## 2.3 Install Maven on MacOS using Homebrew\n\nTo install and configure Maven on MacOS, you can follow these steps:\n\n1.  Open the Terminal on your Mac.\n\n2.  Install the Homebrew package manager by running the following command in the terminal. This step is required only if Homebrew is not installed on your machine.\n\n```bash\n/bin/bash -c \"$(curl -fsSL \u003chttps://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh\u003e)\"\n```\n\n3.  Install Maven by running the following command in the terminal:\n\n```bash\nbrew install maven\n```\n\n4.  Verify that Maven has been installed by running the following command in the terminal:\n\n```bash\nmvn -version\n```\n\n5.  Set the environment variables for Maven by adding the following lines to the **.bash\\_profile** file in your home directory:\n\n```bash\nexport M2_HOME=/usr/local/Cellar/maven/{VERSION}/libexec\nexport PATH=$PATH:$M2_HOME/bin\n```\n\nReplace `{VERSION}` with the actual version of Maven that you installed.\n\n6.  Reload the .bas
1h\\_profile file by running the following command in the terminal:\n\n```bash\nsource ~/.bash_profile\n```\n\n7.  Verify that Maven has been configured correctly by running the following command in the terminal:\n\n```bash\necho $M2_HOME\n```\n\nYou should see the path to your Maven installation printed on the console.\n\nCongratulations, you have successfully installed and configured Maven on your MacOS system!\n\n## 2.4 Testing a Maven Installation\n\nOnce Maven is installed, you can verify if it is installed properly by running `mvn -v` from the command line. If Maven has been installed, you should see something resembling the following output:\n\n```bash\n~ mvn -version\nApache Maven 3.9.6 (bc0240f3c744dd6b6ec2920b3cd08dcc295161ae)\nMaven home: /opt/homebrew/Cellar/maven/3.9.6/libexec\nJava version: 17.0.8, vendor: Microsoft, runtime: /Users/nilan /.sdkman/candidates/java/17.0.8-ms\nDefault locale: en_GB, platform encoding: UTF-8\nOS name: \"mac os x\", version: \"14.1.2\", arch: \"aarch64\", family: \"mac\"\n```\n\nIf you do not see this output and your operating system cannot find the maven command, make sure that your PATH and M2\\_HOME environment variables have been properly set.\n\n## 2.5 Getting Help with Maven\n\nThis book is not a comprehensive reference for Maven but just a starting point. The core of Maven is very simple, however the real work in Maven happens in the plugins, and there are tons of plugins available for you to use. Should you encounter any problem with Maven or have any Maven plugin-related issues; you can search for answers from the official Maven website [http://maven.apache.org](http://maven.apache.org/).\n\n## 2.6 The Apache Software License\n\nApache Maven is released under the Apache Software License, Version 2.0. If you want to read this license, you can read ${M2\\_HOME}/LICENSE.txt or read this license on the Open-Source Initiative’s website at [https://opensource.org/license/apache-2-0/.](https://opensource.org/license/apache-2-0/)\n\nThere’s a good chance that, if you are reading this book, you are not a lawyer. If you are wondering what the Apache License, Version 2.0 means, the Apache Software Foundation has assembled a very helpful Frequently Asked Questions (FAQ) page about the license available at [https://www.apache.org/foundation/license-faq.html](https://www.apache.org/foundation/license-faq.html).\n"])</script>
1<script>self.__next_f.push([1,"4b:T1362,"])</script>
1<script>self.__next_f.push([1,"\nMaven is a popular build automation tool used primarily for Java projects. It is designed to manage a project's build process, including the compilation, packaging, and deployment of software components, as well as managing dependencies and generating reports.  \n\nMaven provides a structured and standardized approach to building Java applications, making it easier for developers to manage the project dependencies. It uses a declarative approach to project configuration and uses an XML file called a pom.xml _(Project Object Model)._ Maven will automatically download any required dependencies from a central repository, compile the code, and create a packaged executable (**JAR** or **WAR** file) for deployment.\n\nIn summary, Maven is a build automation tool that simplifies the process of building and managing Java projects. It provides a standard way of handling dependencies and project configuration, which makes it easier for developers to manage and maintain their code.\n\n## Why Use Maven?\n\nMaven was originally started as an attempt to allow developer to simplify the build process and to comprehend the complete state of a development effort in the shortest period. Maven provides several benefits, including:\n\n-   **Easy build automation:** Maven automates the build process, including compiling the code, running tests, and packaging the application into a distributable format.\n-   **Dependency management:** Maven makes it easy to manage dependencies for your project, including downloading and including libraries from remote repositories.\n-   **Consistent project structure:** Maven provides a standard project structure that makes it easy to organize your code and resources.\n-   **Plugin system:** Maven has a powerful plugin system that can be used to extend the functionality of the build process, such as generating documentation or deploying the application to a server.\n-   **Easy project setup:** Maven provides archetypes that can be used to quickly set up a new project with a predefined structure and dependencies.\n-   **Reproducible builds:** Maven provides a way to create reproducible builds, which means that the build process is consistent across different machines and environments.\n-   **Integration with IDEs:** Maven integrates with popular Java IDEs, such as Eclipse and IntelliJ, making it easy to import and work with Maven projects.\n\nOverall, Maven can help improve the productivity of developers and make it easier to manage complex Java projects by automating common tasks and providing a standardized way to structure and build projects.\n\n## Project Object Model\n\nThe pom.xml file is used to define the project's configuration, including its dependencies, plugins, and other settings. The POM file is typically stored in the project's root directory.\n\n### Project Identifiers in Maven\n\nIn Maven, a project is identified by three main identifiers (also known as coordinates):\n\n-   **Group Id:** A unique identifier for the group or organization that the project belongs to. Typically, this is a reversed domain name, such as com.example.\n-   **Artifact Id:** A unique identifier for the project itself. This is the name that identifies the project and is used to generate the name of the JAR file.\n-   **Version:** A version number that identifies a specific release of the project. Versions are typically formatted as three or four numbers separated by periods, such as 1.0 or 1.0.1.\n\nTogether, these three identifiers form the project's GAV (Group, Artifact, Version) coordinates, which uniquely identify the project and its releases. In addition to the GAV coordinates, there are also other identifiers that can be used in Maven, including:\n\n-   **Packaging:** The type of artifact that the project produces, such as a **JAR (Java archive)**, **WAR (Web archive)**, or **EAR (Enterprise archive)** file.\n-   **Classifier:** A string that is used to distinguish between different versions of an artifact. For example, you could have multiple versions of a JAR file that are classified as \"**sources**\" or \"**javadoc**\".\n\nJAR (Java Archive) files are used to package and distribute standalone Java applications. They contain a set of classes, resources, and other files that are required to run the application. JAR files are typically self-contained, meaning that they do not require any additional dependencies to be installed on the system where they are run.\n\nWAR (Web Archive) files are a specific type of JAR file that is used to package and distribute web applications. They contain all the files that are required to run the web application, including the Java classes, web pages, static resources, and deployment descriptor files. WAR files are typically deployed to a web server, where they are run in a servlet container.\n\nBy using these identifiers, Maven can manage dependencies between projects, download and cache dependencies from remote repositories, and automate the build and deployment process.\n"])</script>
1<script>self.__next_f.push([1,"4c:T181e,"])</script>
1<script>self.__next_f.push([1,"\n_What is Project Lombok? Have you used this magical library? With the new Java Records feature, you might wonder if Lombok is still relevant. Let's weigh the pros and cons and see if this is suitable for you._\n\n## What is Project Lombok?\n\nProject Lombok is a popular Java library, used to remove the boilerplate code with the intent to save development time.\n\nIt replaces the boilerplate code such as getters, setters, constructors, toString, equals, and builders with a set of annotations. This means less code, saves time, and reduces verbosity, making your codebase cleaner, readable, and more maintainable.\n\nIt also includes utilities such as `delombok` checking null values and `@Slf4j` for logging support.\n\nFor example, traditionally a class declaration looks something like this;\n\n```java\npublic class Car {\n    private String model;\n    private int year;\n    private String fuelType;\n\n    public Car() {\n    }\n\n    public Car(String model, int year, String fuelType) {\n        this.model = model;\n        this.year = year;\n        this.fuelType = fuelType;\n    }\n\n    @Override\n    public boolean equals(Object o) {\n        if (this == o) return true;\n        if (o == null || getClass() != o.getClass()) return false;\n        Car car = (Car) o;\n        return year == car.year \u0026\u0026 Objects.equals(model, car.model) \u0026\u0026 Objects.equals(fuelType, car.fuelType);\n    }\n\n    @Override\n    public String toString() {\n        return \"Car{\" +\n                \"model='\" + model + '\\'' +\n                \", year=\" + year +\n                \", fuelType='\" + fuelType + '\\'' +\n                '}';\n    }\n\n    @Override\n    public int hashCode() {\n        return Objects.hash(model, year, fuelType);\n    }\n\n    public String getModel() {\n        return model;\n    }\n\n    public void setModel(String model) {\n        this.model = model;\n    }\n\n    public int getYear() {\n        return year;\n    }\n\n    public void setYear(int year) {\n        this.year = year;\n    }\n\n    public String getFuelType() {\n        return fuelType;\n    }\n\n    public void setFuelType(String fuelType) {\n        this.fuelType = fuelType;\n    }\n}\n```\n\nBut with Lombok, we can write the same code using a bunch of annotations.\n\n```java\n@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@ToString\n@EqualsAndHashCode\npublic class Car {\n    String model;\n    int year;\n    String fuelType;\n}\n```\n\nAlternatively, you can also replace all the above annotations with just one `@Data` annotation.\n\n### How Lombok Works?\n\nIt works by using an annotation processor to modify the abstract syntax tree (AST) of your code during compilation. The annotation processor reads annotations defined in your class and adds required methods to the AST.\n\nThe compiler then uses the modified AST to produce the bytecode.\n\n### Lombok Annotations\n\n| @Getter, @Setter | Generates getters and setter methods for the field. |\n| --- | --- |\n| @NoArgsConstructor, @AllArgsConstructor, @RequiredArgsConstructor | Generates constructors for your class |\n| @Builder | Provides a builder pattern interface for the annotated class. |\n| @Data | Equivalent to adding the annotations @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode to your class |\n| @Value | Makes the class instances immutable |\n| @NonNull | Null check |\n| @SneakyThrows | Could be added to a method that throws a checked exception |\n| @ToString | Generates a toString() method |\n| @EqualsAndHashCode | Generates an .equals(..) and a .hashCode() methods |\n\nCheck out the official documentation for all Lombok annotations and their usage. [https://t.co/HoiMNzPm4k](https://t.co/HoiMNzPm4k)  \n\n## Things to consider\n\nWhile it promotes simplicity and clean code, it does too much magic in the background, and for newbie developers, it can be quite confusing.\n\n### Find usage problem\n\nWhen using Lombok you don't see the generated getter, setter, constructor, builder methods, etc. So, if you want to want to find out where these methods are being used in your project, you can't do this without being dependent on IDE plugins.\n\n### Misuse of @Builder\n\nWith Lombok, a builder is so easy to create that even when a class has only two parameters the developers prefer to use @Builder instead of a constructor or a static constructor method. Doing so makes it more harm than good.\n\n### The @Value annotation and final class\n\nThe `@Value` annotations make the class Final. It is basically the immutable variant of `@Data` annotation.\n\nAll fields are made private and final by default and this does not generate any setter methods. If you want to make your class extendable, then you cannot use the `@Value` annotation.\n\n```java\n@Value\npublic class Car {\n    String model;\n    int year;\n    String fuelType;\n}\n```\n\nThe same behavior for a class can be achievable natively in Java using Java 16 records. With records, you can define the data fields in one line of code, instead of having to define a constructor and getter/setter methods for each field in a class.\n\nRecords also have a built-in `equals()` and `hashCode()` method and they are _**immutable**_ by default. It makes your code shorter, easier to read, and less prone to errors.\n\n```java\npublic re
1cord Car(String model, int year, String fuelType) {\n\n}\n```\n\nWith the inclusion of records in Java, one would wonder if you need Lombok at all.\n\n### Using @Data on Entities\n\nYou need to use the `@Data` annotation very cautiously. It can cause serious serialization issues with ORMs like Hibernate and serializer engines like Gson.\n\nDo yourself a favor and read this article:\n\nhttps://thorben-janssen.com/lombok-hibernate-how-to-avoid-common-pitfalls/  \n\n## The Verdict\n\nLombok is just one tool in the toolbox. You need to understand the trade-offs and consider team expertise before considering this. Lombok makes a lot of sense in Greenfield and small projects to get off the ground. Introducing larger projects has mixed benefits at best.\n\nIf you using an IDE such as IntelliJ, it is pretty easy to generate these boilerplate codes, and enabling the code folding can help to make your code more readable.\n\nUnless you know what you're doing, I suggest holding back on your temptation to use Lombok.\n"])</script>
1<script>self.__next_f.push([1,"4d:T1668,"])</script>
1<script>self.__next_f.push([1,"\nMy personal journey in tech blogging has been a roller coaster ride. I have been blogging ever since I entered the IT industry as a new entrant in 2008. It was driven by the passion for learning new technology and exploring stuff that is contrary to my regular day-to-day job.  \n\nSo when I was working as an Android application developer, in my personal time I was trying to learn J2EE and Apache Struts. And, I love taking notes along the way while doing small and simple POCs.\n\nAt that time there was no application like Notion, so I decided to create a website using Google Blogspot and started capturing all my notes there. Those notes mainly served as a bookmark, so I could refresh my memory whenever I wanted.\n\nSlowly, I started to like writing detailed tutorials and sharing my knowledge which some of my friends, and colleagues loved to read. And that is how I was introduced to blogging. But, I never wanted to be a full-time blogger. I never believed I had that spark, which would make me living out of it. That made me a passive blogger.\n\n## 7 Blogging Mistakes I wish I had Known Before\n\nOver the years, I've had my fair share of experiences as a passive blogger, and through trial and error, I've learned valuable lessons that I wish I had known earlier.\n\nIn this blog post, I'll share these insights with you, in the hope that they'll help you on your own blogging journey.\n\nThis post is probably too long for you. You don't need to spend all your time reading this unless you really want to hear my story.\n\nLet’s cut to the chase:\n\n-   Content is the king, but consistency is the key to success!\n-   Building a distribution channel is more important than building a great site.\n-   You don't need a perfect domain or perfect site design. No one gives a shit about your domain name or site design as long as you have the X factor in your content.\n-   Understand your niche. Don't try to be a jack of all, you may appear as a jackass.\n-   SEO is the secret weapon. The earlier you realize the better for your site growth.\n-   Engagements are more important than having a larger number of subscribers/followers.\n-   Social media can help you to create the hype but a simple mistake can fuck up your whole strategy. So use it cautiously.\n\n**Only, for not-so-busy people:**\n\nNothing new here, but I expand on these above topics.\n\n### 1. Content is the King, but Consistency is the Key\n\nGreat content is essential for any successful blog, this is a must-have. However, consistency is equally important. You need to strike the right balance between quality and quantity.\n\nAs a lone worrier, I used to dedicate a few hours over a weekend to produce 2/3 articles for my blog. But I never realized that we need to be consistent in publishing stories. I used to publish 3/4 articles in a day and then nothing for the rest of the month.\n\nPublishing many articles a day, makes your readers overwhelmed with content so it is very unlikely that all your stories will be read by everyone. But publishing a story on a regular interval, let’s say every Sunday, will definitely drive more engagement, and your readers will love to spend a few minutes reading a story per week.\n\n### 2. Building a Distribution Channel is Equally Important as Bu
1ilding a Great Site\n\nGreat content is like a hidden treasure, it is worth only when discovered by your readers. Without having an effective distribution strategy no one will ever find what you write.\n\nYou need to plan your distribution strategy including content syndication, building email lists, social media groups, etc.\n\n### 3. You Don't Need a Perfect Domain or Perfect Site Design\n\nMany aspiring bloggers get caught up in the quest for the perfect domain name or website design. While these factors are important, they are not as critical as the quality and uniqueness of your content.\n\n### 4. Understand Your Niche\n\nTrying to cover too many topics can dilute your blog's identity and make you appear unfocused. Find out why it's crucial to understand your niche and become an authority in it.\n\n### 5. SEO is the Secret Weapon\n\nSearch Engine Optimization (SEO) can be a game-changer for your blog's growth and to drive organic traffic to your blog. While SEO strategy might sound easy when you Google these topics, there is a vast amount of science behind it.\n\nSome of these include:\n\n-   Having a catchy page title (not clickbait) and page description.\n-   Maintain a structural hierarchy of your content on the page\n-   Canonical and SEO-friendly page links\n-   Backlinks and building trustworthiness\n-   Page loading speed\n-   Image and video annotations and structured content markup\n-   Submit the site to search engines\n\nThese are just a few of these SEO strategies to start with.\n\n### 6. Engagements are More Important than a Subscribers Count\n\nIt's not just about the numbers. Don't always throw your stuff, expand your social posts to other stuff including a photo from your pub night or day out with your kids. People love to connect with humans more than a BOT?.\n\nEngaging with your audience, building a community, and nurturing relationships can be more valuable than having a massive but passive following.\n\n### 7. Social Media: Hype and Caution\n\nSocial media can be a double-edged sword. Learn how to leverage its potential to create excitement around your blog while avoiding common pitfalls that can harm your strategy.\n\n### In Summary,\n\nI am not a very successful blogger. I never made direct money out of my blogging. However, blogging enabled me to expand my horizons and build connections. Using my blogging connections I have published books, built projects, and earned sufficient money to call out “My Blogging Journey has been Worthwhile!”.\n\nHappy blogging!\n"])</script>
1<script>self.__next_f.push([1,"4e:T12c1,"])</script>
1<script>self.__next_f.push([1,"\nOne of the key features of the Spring Boot framework is the built-in support for embedded servers. It includes support for embedded Tomcat, Jetty and Undertow servers. This means you don’t need any external web servers and no need to deploy WAR files anymore.\n\nThe embedded Tomcat server is available through the `spring-boot-starter-web` dependency.\n\nHowever, if you want Jetty or Undertow servers then you can include `spring-boot-starter-jetty` or `spring-boot-starter-undertow` dependencies.\n\nThis article explains how to replace the default embedded Tomcat with Jetty or Undertow servers.\n\n## Replace Tomcat with the Jetty in Spring Boot\n\nTo use the embedded Jetty server instead of Tomcat, you need to exclude the `spring-boot-starter-tomcat` from `spring-boot-starter-web` and include the `spring-boot-starter-jetty` dependency.\n\nAlso, you will need to exclude the default added spring-boot-starter-tomcat dependency.\n\n### For Spring Boot Version 2.x.x\n\nFor **Gradle**, make the following changes to your `build.gradle` file.\n\n```groovy\ndependencies {\n    implementation('org.springframework.boot:spring-boot-starter-web') {\n        exclude group:'org.springframework.boot', module:'spring-boot-starter-tomcat'\n    }\n    implementation 'org.springframework.boot:spring-boot-starter-jetty'\n}\n```\n\nIf you’re using **Maven** build tools, you need to add this to your `pom.xml` file.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-web\u003c/artifactId\u003e\n    \u003cexclusions\u003e\n        \u003cexclusion\u003e\n            \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n            \u003cartifactId\u003espring-boot-starter-tomcat\u003c/artifactId\u003e\n        \u003c/exclusion\u003e\n    \u003c/exclusions\u003e\n\u003c/dependency\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-jetty\u003c/artifactId\u003e\n\u003c/dependency\u003e\n```\n\n### For Spring Boot Version 3.x.x\n\nThe above configuration works for Spring Boot version 2.x, but it will throw the following error if you’re using the latest Spring Boot version 3.x.\n\n```text\njava.lang.ClassNotFoundException: jakarta.servlet.http.HttpSessionContext\nwith Spring Boot 3 and Jetty server\n```\n\nThis is because Jetty does not yet support Servlet 6.0. To use Jetty with Spring Boot 3.0, you will have to downgrade the Servlet API to 5.0. You can use the `jakarta-servlet.version` property to do so.\n\nRef: [Spring-Boot-3.0-Migration-Guide](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide#jetty)\n\n```groovy\next['jakarta-servlet.version'] = '5.0.0'\ndependencies {\n    implementation('org.springframework.boot:spring-boot-starter-web')\n    implementation 'org.springframework.boot:spring-boot-starter-jetty'\n    modules {\n        module(\"org.springframework.boot:spring-boot-starter-tomcat\") {\n            replacedBy(\"org.springframework.boot:spring-boot-starter-jetty\")\n        }\n    }\n}\n```\n\nIf you’re using **Maven** build tools, you need to add this to your `pom.xml` file.\n\n```xml\n\u003cproperties\u003e\n    \u003cjava.version\u003e17\u003c/java.version\u003e\n    \u003cjakarta-servlet.version\u003e5.0.0\u003c/jakarta-servlet.version\u003e\n\u003c/properties\u003e\n\n\u003cdependencies\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n        \u003cartifactId\u003espring-boot-starter-web\u003c/artifactId\u003e\n        \u003cexclusions\u003e\n            \u003cexclusion\u003e\n                \u003cartifactId\u003espring-boot-starter-tomcat\u003c/artifactId\u003e\n                \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n            \u003c/exclusion\u003e\n        \u003c/exclusions\u003e\n    \u003c/dependency\u003e\n\n    \u003cdependency\u003e\n        \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n        \u003cartifactId\u003espring-boot-starter-jetty\u003c/artifactId\u003e\n    \u003c/dependency\u003e\n\u003c/dependencies\u003e\n```\n\n## Replace Tomcat with Undertow in Spring Boot\n\nTo use Undertow instead of Tomcat, first, you need to exclude the spring-boot-starter-tomcat from spring-boot-starter-web. Then you should add the undertow starter as shown here.\n\nFor **Gradle**, make the following changes to your `build.gradle` file.\n\n```groovy\ndependencies {\n    implementation('org.springframework.boot:spring-boot-starter-web') {\n        exclude group:'org.springframework.boot', module:'spring-boot-starter-tomcat'\n    }\n    implementation 'org.springframework.boot:spring-boot-starter-undertow'\n}\n```\n\nIf you’re using **Maven** build tools, you need to add this to your `pom.xml` file.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-web\u003c/artifactId\u003e\n    \u003cexclusions\u003e\n        \u003cexclusion\u003e\n            \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n            \u003cartifactId\u003espring-boot-starter-tomcat\u003c/artifactId\u003e\n        \u003c/exclusion\u003e\n    \u003c/exclusions\u003e\n\u003c/dependency\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-undertow\u003c/artifactId\u003e\n\u003c/dependency\u003e\n```\n"])</script>
1<script>self.__next_f.push([1,"4f:T28d5,"])</script>
1<script>self.__next_f.push([1,"\nSingleton design pattern belongs to the creational family of patterns that governs the object instantiation process. It ensures at most one instance of a class is ever created throughout the lifecycle of your application.\n\nHere are some of the real-time use cases of the singleton class:\n\n-   **Project Configuration:** Project configurations are read and loaded into memory once and used multiple times throughout the application lifecycle.\n-   **Application Log:** The Logger object will be used globally everywhere in your application. It must be initialized once and used everywhere.\n-   **Analytics and Reporting:** If you are using some kind of data Analytics or tracking service, then, you must design them to be singleton so that they are initialized once and used everywhere.\n\n![](/media/summernote/singleton-design-pattern_1_6HU1DL5.jpg)\n\nNotice that the `Singleton` class has a private static instance variable named `instance`. The default constructor of the `Singleton` class is made private to prevent other classes from instantiating it.\n\nThe `getInstance()` method is declared in the static scope to make the technique accessible globally. The `getInstance()` method returns the singleton object.\n\n## Implementing the Singleton Class\n\nTo declare a class as singleton, you have to:\n\n-   The default constructor must be private. A private constructor prevents the direct instantiation of the object from other classes.\n-   Create a public static `getInstance()` method. A member declared as static can be accessed without creating an object using the new operator. This method returns the instance of the singleton class.\n-   Lazy initialization is preferable to create an object on first use.\n\n### Singleton with Lazy Initialization\n\nHere's how we can create a singleton class using lazy initialization\n\n```java\nclass Singleton {\n    private static Singleton instance;\n\n    private Singleton() {\n    }\n\n    public static Singleton getInstance() {\n        if (instance == null) {\n            instance = new Singleton();\n        }\n        return instance;\n    }\n\n    public void method1() {\n        System.out.println(\"Hurray! I am method1 from Singleton!\");\n    }\n}\n```\n\nLet us now test the singleton initialization:\n\n```java\nSingleton object = new Singleton();\nobject.method1();\n```\n\nThe above code will result in a compilation error. As the default constructor is made private, you are not allowed to create instances using a `new` keyword. However, we can use the `getInstance()` method to get the instance of the Singleton class.\n\n```java\nSingleton object = Singleton.getInstance();\nobject.method1();\n```\n\nThis is how we create a Singleton class using lazy initialization. The `getInstance()` method instantiates the class for the first use.\n\n### Singleton and Thread Safety\n\nNotice that the `getInstance()` method is not thread-safe. Two instances of the Singleton class will be created if the `getInstance()` is called simultaneously by two threads.\n\nThis issue can be avoided by making the `getInstance()` method `synchronized`. This way we force every thread to wait for its turn before it executes. i.e. no two threads can be entered into the `getInstance()` method at the same time.\n\n```java\npublic static synchronized Singleton getInstance() {\n    if (instance == null) {\n        instance = new Singleton();\n    }\n  return instance;\n}\n```\n\nThe above implementation will answer the thread safety problem. However, the `synchronized` methods are expensive and can have a serious performance hit.\n\nWe can optimize this using the `synchronization` block.\n\n```java\npublic static Singleton getInstance() {\n    if (instance == null) {\n        synchronized (Singleton.class) {\n                if (instance == null) {\n                    instance = new Singleton();\n                }\n            }\n        }\n    return instance;\n}\n```\n\n### Singleton with Early Initialization\n\nUsing early initialization we will initialize upfront before your class is loaded. This way you don’t need to check for synchronization as it is initialized before being used ever.\n\n```java\nclass Singleton {\n    private static Singleton instance = new Singleton();\n\n    private Singleton() {\n    }\n\n    public static Singleton getInstance() {\n        return instance;\n    }\n\n    public void method1() {\n        System.out.println(\"Hurray! I am method1 from Singleton!\");\n    }\n}\n```\n\n## Singleton and Object Cloning\n\nJava allows you to create a copy of the object with similar attributes and state from the original object using cloning. To implement cloning, we have to implement `java.lang.Cloneable` interface and override `clone()` method from the `Object` class.\n\nIt is a good idea to prevent cloning in a singleton class.\n\nTo disallow cloning in your singleton class, we can override the clone method and explicitly throw the `CloneNotSupportedException` exception.\n\n```java\nclass Singleton implements Cloneable {\n    private static Singleton instance;\n\n    private Singleton() {\n    }\n\n    public static synchronized Singleton getInstance() {\n        if (instance == null) {\n            synchronized (Singleton.class) {\n                if (instance == null) {\n                    instance = new Singleton();\n                }\n            }\n        }\n        return instance;\n    }\n\n    @Override\n    public Object clone() throws CloneNotSupportedException {\n        throw new CloneNotSupportedException();\n    }\n\n    public void method1() {\n        System.out.println(\"Hurray! I am method1 from Singleton!\");\n    }\n}\n```\n\n## Singleton and Serialization\n\nSerialization in Java allows to conversion of the state of an object into a stream of bytes so that it can easily be stored into a file or transferred via network. Once the object is serialized, you can deserialize it, back to the object from the byte stream.\n\nIf a singleton class is meant to be serialized, it will end up creating duplicate objects. Let us have a look at the example below,\n\n```java\nimport java.io.Serializable;\n\nclass Singleton implements Cloneable, Serializable {\n    private static final long serialVersionUID = 1L;\n    private static Singleton instance;\n    private int value;\n\n    private Singleton() {\n    }\n\n    public static synchronized Singleton getInstance() {\n        if (instance == null) {\n            synchronized (Singleton.class) {\n                if (instance == null) {\n                    instance = new Singleton();\n                }\n            }\n        }\n        return instance;\n    }\n\n    @Override\n    public Object clone() throws CloneNotSupportedException {\n        throw new CloneNotSupportedException();\n    }\n\n    public void method1() {\n        System.out.println(\"Hurray! I am method1 from Singleton!\");\n    }\n\n    public int getValue() {\n        return value;\n    }\n\n    public void setValue(int value) {\n        this.value = value;\n    }\n}\n```\n\nIn this example, the Singleton class is implementing the `java.io.Serializable` interface, which means the state of its object can be persisted.\n\nNow, let us save the object into a file and then retrieve it later.\n\n```java\npublic static void main(String[] args) {\n    Singleton instanceOne = Singleton.getInstance();\n    instanceOne.setValue(10);\n\n    try {\n        FileOutputStream fos = new FileOutputStream(\"filename.txt\")\n        ObjectOutput out = new ObjectOutputStream(fos);\n        out.writeObject(instanceOne);\n        out.close();\n        instanceOne.setValue(20);\n\n        FileInputStream fis = new FileInputStream(\"filename.txt\")\n        ObjectInput in = new ObjectInputStream(fis);\n        Singleton instanceTwo = (Singleton) in.readObject();\n        in.close();\n\n        System.out.println(\"instanceOne:\" + instanceOne.getValue());\n        System.out.println(\"instanceTwo:\" + instanceTwo.getValue());\n    } catch (Exception e) {\n        e.printStackTrace();\n    }\n}\n```\n\nThis will print different values, which means that they are two different objects. Here we are violating the singleton principle.\n\nTo solve this issue, we need to include the `readResolve()` method in our `Singleton` class. This method will be invoked before the object is deserialized and here we will call the `getInstance()` method to return the same object after deserialization.\n\n```java\nclass Singleton implements Cloneable, Serializable {\n    private static final long serialVersionUID = 1L;\n    private static Singleton instance;\n    private int value;\n\n    private Singleton() {\n    }\n\n    public static synchronized Singleton getInstance() {\n        if (instance == null) {\n            synchronized (Singleton.class) {\n                if (instance == null) {\n                    instance = new Singleton();\n                }\n            }\n        }\n        return instance;\n    }\n\n  protected Object readResolve() {\n     return getInstance();\n  }\n\n    @Override\n    public Object clone() throws CloneNotSupportedException {\n        throw new CloneNotSupportedException();\n    }\n\n    public void method1() {\n        System.out.println(\"Hurray! I am method1 from Singleton!\");\n    }\n\n    public int getValue() {\n        return value;\n    }\n\n    public void setValue(int value) {\n        this.value = value;\n    }\n}\n```\n\n## Noteworthy\n\n-   Singleton classes are used sparingly. Do not think of this pattern, unless you know 
1what you are doing. As the object is created in the global scope, this is riskier in resource-constrained platforms.\n-   Beware of object cloning. Double-check and block the object’s clone method\n-   Careful when multiple threads access the singleton class\n-   Careful of multiple class loaders they can break your singleton\n-   Implement strict type if your singleton class is serialized\n\n## Practice Question\n\nDesign a Rate Limiter class that limits the number of requests an API can receive within a given time frame. The Rate Limiter should be implemented as a Singleton to ensure that only one instance is used throughout the system.  \n  \n**Hint:**  \n\n-   RateLimiter Initializes the rate limiter object. Each user is allowed a maximum of 3 requests per minute.\n-   Create a method \\`allowRequest(int timestamp, int userId)\\` that returns true if the request from the given userId is allowed at the given timestamp, otherwise returns false.\n\nExplain using the Java Scanner library to accept user input for the user ID, automatically generate a timestamp, and interact with our RateLimiter class. The main method will print \"Hello\" if the request from the user is accepted.\n"])</script>
1<script>self.__next_f.push([1,"50:T5e14,"])</script>
1<script>self.__next_f.push([1,"\nCloud computing technology allows companies to access and utilize computing resources and services over the internet, often referred to as “the cloud”.\n\nInstead of owning and managing physical servers and data centres, cloud computing allows users to rent or lease computing resources, such as virtual machines, storage, databases, and more, from cloud service providers.\n\nThis model offers several benefits, including scalability, flexibility, cost-efficiency, and the ability to access resources from anywhere with an internet connection.\n\nSome of the major cloud providers in the industry are:\n\n1.  Amazon Web Services (AWS)  \n    \n2.  Microsoft Azure\n3.  Google Cloud Platform (GCP)\n\nThis post is about the quick guide to CLF-C01 AWS Certified Cloud Practitioner Practice exam notes, hence we will cover the introduction to all the services provided by AWS.\n\nAWS, a subsidiary of Amazon.com, is the largest and most widely adopted cloud provider. It offers a comprehensive suite of cloud computing services, including computing power, storage, databases, machine learning, analytics, and more.\n\n## Advantages of Cloud Computing\n\n-   **Variable vs. capital expenses:** AWS offers you the pay-as-you-go pricing model hence as a business there are no capital expenses to get started your business on the cloud.\n-   **Economics of scale:
1** When the business expands, companies need to invest a huge amount of money to scale the on-premise setup. However, in the cloud, you can leverage economies of scale and benefit from having the shared Infrastructure, lower hardware costs, and efficient resource utilization which results in cost-effectiveness in scaling your application.\n-   **Stop guessing capacity:** Cloud providers offer auto scaling, so you do not need to plan in advance and guess the resource/compute requirements for your business.\n-   **Increase speed and Agility:** As the cloud requires less investment in the initial setup and other aspects such as maintenance, patching, security and compliance is taken care of by the cloud providers, business need to focus only on the business differentiators and application development without worrying about infrastructure.\n-   **Go global in minutes:** Cloud providers have data centres in multiple geographic regions, allowing users to deploy applications and services closer to their target audience for reduced latency.\n-   **Deployment Flexibility:** AWS offers different deployment models including all in-cloud and hybrid deployment.\n\n## AWS Infrastructure\n\n-   AWS provides a highly available technology infrastructure platform with multiple locations worldwide. These locations are composed of regions and Availability Zones.\n-   Each region is a separate geographic area. Each region has multiple, isolated locations known as Availability Zones.\n-   AWS enables the placement of resources and data in multiple locations. Resources aren’t replicated across regions unless organizations choose to do so.\n-   Each region is completely independent and is designed to be completely isolated from the other regions. This achieves the greatest possible fault tolerance and stability.\n-   Each Availability Zone is also isolated, but the Availability Zones in a region are connected through low-latency links.\n\n**Accessing the Platform**\n\n-   AWS Management Console\n-   AWS Command Line Interface (CLI)\n-   AWS Software Development Kits (SDKs)\n\n## Compute and Networking Services\n\nAWS offers a wide range of compute and networking services to support various computing workloads and networking requirements.  \n\n### Amazon Elastic Compute Cloud (Amazon EC2)\n\n-   Amazon EC2 is a web service that provides resizable **computing capacity** in the cloud. It allows organizations to obtain and configure virtual servers in Amazon’s data centres and to harness those resources to build and host software systems.\n-   It allows selecting from a variety of operating systems and resource configurations (memory, CPU, storage, and so on) that are optimal for the application profile of each workload.\n-   Amazon EC2 presents a true virtual computing environment, allowing organizations to launch compute resources with a variety of operating systems, load them with custom applications, and manage network access permissions while maintaining complete control.\n\n### AWS Lambda\n\n-   AWS Lambda is a zero-administration computing platform that runs your code for you on the AWS Cloud.\n-   AWS Lambda runs your back-end code on its own AWS compute fleet of Amazon EC2 instances across multiple Availability Zones in a region, which provides the high availability, security, performance, and scalability of the AWS infrastructure.\n\n### Auto Scaling\n\nAuto Scaling is well suited both to applications that have stable demand patterns and to applications that experience hourly, daily, or weekly variability in usage.\n\n### Elastic Load Balancing\n\nElastic Load Balancing automatically distributes incoming application traffic across multiple Amazon EC2 instances in the cloud.\n\nIt enables organizations to achieve greater levels of fault tolerance in their applications, seamlessly providing the required amount of load-balancing capacity needed to distribute application traffic.\n\n### AWS Elastic Beanstalk\n\nAWS Elastic Beanstalk is the fastest and simplest way to get a web application up and running on AWS. Developers can simply upload their application code, and the service automatically handles all the details, such as resource provisioning, load balancing, Auto Scaling, and monitoring.\n\nIt provides support for a variety of platforms, including PHP, Java, Python, Ruby, Node.js, .NET, and Go. With AWS Elastic Beanstalk, organizations retain full control over the AWS resources powering the application and can access the underlying resources at any time.\n\n### Amazon Virtual Private Cloud (Amazon VPC)\n\nAmazon Virtual Private Cloud (Amazon VPC) lets organizations provision a logically isolated section of the AWS Cloud where they can launch AWS resources in a virtual network that they define.\n\nOrganizations have complete control over the virtual environment, including selection of the IP address range, creation of subnets, and configuration of route tables and network gateways. In addition, organizations can extend their corporate data centre networks to AWS by using hardware or software virtual private network (VPN) connections or dedicated circuits by using AWS Direct Connect.\n\n### AWS Direct Connect\n\nAWS Direct Connect allows organizations to establish a dedicated network connection from their data centre to AWS. Using AWS Direct Connect, organizations can establish private connectivity between AWS and their data centre, office, or colocation environment, which in many cases can reduce network costs, increase bandwidth throughput, and provide a more consistent network experience than Internet-based VPN connections.\n\n### Amazon Route 53\n\nAmazon Route 53 is a highly available and scalable Domain Name System (DNS) web service. It provides a reliable and cost-effective way to route end users to Internet applications by translating human readable names, such as www.example.com, into the numeric IP addresses, such as 192.0.2.1, that computers use to connect to each other.\n\nAmazon Route 53 also serves as a domain registrar, allowing you to purchase and manage domains directly from AWS.\n\n## Storage and Content Delivery\n\nAWS provides a variety of services to meet your storage needs, such as Amazon Simple Storage Service, Amazon CloudFront, and Amazon Elastic Block Store.\n\n### Amazon Simple Storage Service (Amazon S3)\n\n-   Amazon Simple Storage Service (Amazon S3) provides developers and IT teams with highly durable and scalable object storage that **handles virtually unlimited amounts** of data and large numbers of concurrent users.\n-   Can be used to store any number of objects of any type, such as HTML pages, source code files, image files, and encrypted data, and access them using HTTP-based protocols.\n-   Amazon S3 provides cost-effective object storage for a wide variety of use cases, including backup and recovery, nearline archives, big data analytics, disaster recovery, cloud applications, and content distribution.\n\n### Amazon Glacier\n\n-   Amazon Glacier is a secure, durable, and extremely low-cost storage service for data archiving and long-term backup.\n-   To keep costs low for customers, Amazon Glacier is optimized for infrequently accessed data where a retrieval time of several hours is suitable.\n-   Amazon S3 integrates closely with Amazon Glacier to allow organisations to choose the right storage tier for their workloads.\n\n### Amazon Elastic Block Store (Amazon EBS)\n\n-   Amazon Elastic Block Store (Amazon EBS) provides persistent block-level storage volumes for use with Amazon EC2 instances.\n-   Each Amazon EBS volume is automatically replicated within its Availability Zone to protect organizations from component failure, offering high availability and durability.\n-   By delivering consistent and low-latency performance, Amazon EBS provides the disk storage needed to run a wide variety of workloads.\n\n### AWS Storage Gateway\n\n-   AWS Storage Gateway is a service connecting an on-premises software appliance with cloud-based storage to provide seamless and secure integration between an organization’s on-premises IT environment and the AWS storage infrastru
1cture.\n-   The service supports industry-standard storage protocols that work with existing applications.\n-   It provides low-latency performance by maintaining a cache of frequently accessed data on-premises while securely storing all of your data encrypted in Amazon S3 or Amazon Glacier.\n\n### Amazon CloudFront\n\n-   Amazon CloudFront is a content delivery web service.\n-   It integrates with other AWS Cloud services to give developers and businesses an easy way to distribute content to users across the world with low latency, high data transfer speeds, and no minimum usage commitments.\n-   Amazon CloudFront can be used to deliver your entire website, including dynamic, static, streaming, and interactive content, using a global network of edge locations. Requests for content are automatically routed to the nearest edge location, so content is delivered with the best possible performance to end users around the globe.\n\n## Database Services\n\nAWS provides a comprehensive set of database services to meet a wide range of application requirements, from simple web applications to complex, enterprise-level systems.  \n  \nThese AWS database services are designed to be scalable, highly available, and fully managed, allowing you to focus on building and running your applications while AWS takes care of the database infrastructure.  \n  \nHere are some of the key AWS database services:  \n\n### Amazon Relational Database Service (Amazon RDS)\n\n-   A fully managed relational database with support for many popular open-source and commercial database engines.\n-   It’s a cost-efficient service that allows organizations to launch secure, highly available, fault-tolerant, production-ready databases in minutes.\n-   Because Amazon RDS manages time-consuming administration tasks, including backups, software patching, monitoring, scaling, and replication, organizational resources can focus on revenue-generating applications and business instead of mundane operational tasks.\n\n### Amazon DynamoDB\n\n-   Amazon DynamoDB is a fast and flexible **NoSQL databas**e service for all applications that need consistent, single-digit millisecond latency at any scale.\n-   It is a fully managed database and supports both document and key/value data models.\n-   Its flexible data model and reliable performance make it a great fit for mobile, web, gaming, ad-tech, Internet of Things, and many other applications.\n\n### Amazon Redshift\n\n-   Amazon Redshift is a fast, fully managed, petabyte-scale data warehouse service that makes it simple and cost-effective to analyze structured data.\n-   Amazon Redshift provides a standard SQL interface that lets organizations use existing business intelligence tools.\n-   By leveraging columnar storage technology that improves I/O efficiency and parallelizing queries across multiple nodes, Amazon Redshift is able to deliver fast query performance.\n-   The Amazon Redshift architecture allows organizations to automate most of the common administrative tasks associated with provisioning, configuring, and monitoring a cloud data warehouse.\n\n### Amazon ElastiCache\n\n-   Amazon ElastiCache is a web service that simplifies the deployment, operation, and scaling of **an in-memory cach**e in the cloud.\n-   The service improves the performance of web applications by allowing organizations to retrieve information from fast, managed, in-memory caches, instead of relying entirely on slower, disk-based databases.\n-   Amazon ElastiCache supports Memcached and Redis cache engines.\n\n## Cloud Management Tools\n\nAWS offers a variety of cloud management tools and services that help organizations efficiently manage their AWS resources, monitor performance, automate tasks, and ensure security and compliance.\n\nHere are some key AWS cloud management tools and services:  \n\n### AWS Management Console:\n\nThe AWS Management Console is a web-based interface that allows users to interact with and manage their AWS resources through a graphical user interface (GUI). It provides a user-friendly way to access and control AWS services.  \n\n### AWS Command Line Interface (CLI):\n\nThe AWS CLI is a command-line tool that allows users to interact with AWS services through text commands. It provides a powerful and scriptable way to manage AWS resources and automate tasks.  \n\n### AWS Organizations:\n\nAWS Organizations is a service for managing multiple AWS accounts within an organization. It enables central management of billing, access control, and resource sharing across accounts.  \n\n### AWS Systems Manager:\n\nAWS Systems Manager provides a unified interface for managing AWS resources and applications. It offers features for inventory management, patch management, automation, and more.\n\n### Amazon CloudWatch\n\n-   Amazon CloudWatch is a **monitoring service** for AWS Cloud resources and the applications running on AWS.\n-   It allows organizations to **collect and track metrics, collect and monitor log files, and set alarms**.\n-   By leveraging Amazon CloudWatch, organizations can gain system-wide visibility into resource utilization, application performance, and operational health.\n\n### AWS CloudFormation\n\n-   AWS CloudFormation gives developers and systems administrators an effective way to create and manage a collection of related AWS resources, provisioning and updating them in an orderly and predictable fashion.\n-   AWS CloudFormation defines a JSON-based templating language that can be used to describe all the AWS resources that are necessary for a 
1workload.\n-   Templates can be submitted to AWS CloudFormation and the service will take care of provisioning and configuring those resources in appropriate order.\n\n![](/media/summernote/aws-cloud-formation.png)\n\n### AWS CloudTrail\n\n-   AWS CloudTrail is a web service that records AWS API calls for an account and delivers log files for audit and review.\n-   The recorded information includes the identity of the API caller, the time of the API call, the source IP address of the API caller, the request parameters, and the response elements returned by the service.\n\n### AWS Config\n\n-   AWS Config is a fully managed service that provides organizations with an AWS resource inventory, configuration history, and configuration change notifications to enable security and governance.\n-   With AWS Config, organizations can discover existing AWS resources, export an inventory of their AWS resources with all configuration details, and determine how a resource was configured at any point in time.\n-   These capabilities enable compliance auditing, security analysis, resource change tracking, and troubleshooting.\n\n### AWS Service Catalog:\n\nAWS Service Catalog allows organizations to create and manage catalogs of approved AWS resources and services for use within their organization. It helps enforce compliance and governance.  \n\n## Security and Identity Management\n\nAWS offers a robust set of security and identity management services to help users and organizations protect their AWS resources and data. These services are designed to enforce access control, enhance security, and ensure compliance with industry standards and regulations.  \n\n### AWS Identity and Access Management (IAM)\n\n-   AWS Identity and Access Management (IAM) enables organizations to securely control access to AWS Cloud services and resources for their users.\n-   Using IAM, organizations can create and manage AWS users and groups and use permissions to allow and deny their access to AWS resources.\n\n### AWS Key Management Service (KMS)\n\n-   AWS Key Management Service (KMS) is a managed service that makes it easy for organizations to create and control the encryption keys used to encrypt their data and uses\n-   Hardware Security Modules (HSMs) to protect the security of your keys. AWS KMS is integrated with several other AWS Cloud services to help protect data stored with these services.\n\n### AWS Directory Service\n\n-   AWS Directory Service allows organizations to set up and run Microsoft Active Directory on the AWS Cloud or connect their AWS resources with an existing on-premises Microsoft Active Directory.\n-   Organizations can use it to manage users and groups, provide single sign-on to applications and services, create and apply Group Policies, domain join Amazon EC2 instances, and simplify the deployment and management of cloud-based Linux and Microsoft Windows workloads.\n\n### AWS Certificate Manager\n\n-   AWS Certificate Manager is a service that lets organizations easily provision, manage, and deploy Secure Sockets Layer/Transport Layer Security (SSL/TLS) certificates for use with AWS Cloud services. It removes the time-consuming manual process of purchasing, uploading, and renewing SSL/TLS certificates.\n-   With AWS Certificate Manager, organizations can quickly request a certificate, deploy it on AWS resources such as Elastic Load Balancing or Amazon CloudFront distributions, and let AWS Certificate Manager handle certificate renewals.\n\n### AWS Web Application Firewall (WAF)\n\n-   AWS Web Application Firewall (WAF) helps protect web applications from common attacks and exploits that could affect application availability, compromise security, or consume excessive resources.\n-   AWS WAF gives organizations control over which traffic to allow or block to their web applications by defining customizable web security rules.\n\n## Application Services\n\nAWS offers a variety of application services that enable developers to build, deploy, and scale applications quickly and easily.  \n\n### Amazon API Gateway\n\n-   Amazon API Gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale.\n-   Organizations can create an API that acts as a “front door” for applications to access data, business logic, or functionality from back-end services, such as workloads running on Amazon EC2, code running on AWS Lambda, or any web application.\n-   Amazon API Gateway handles all the tasks involved in accepting and processing up to hundreds of thousands of concurrent API calls, including traffic management, authorization and access control, monitoring, and API version management.\n\n### Amazon Elastic Transcoder\n\n-   Amazon Elastic Transcoder is media transcoding in the cloud.\n-   It is designed to be a highly scalable and cost-effective way for developers and businesses to convert (or transcode) media files from their source formats into versions that will play back on devices like smartphones, tablets, and PCs.\n\n### Amazon Simple Notification Service (Amazon SNS)\n\n-   Amazon Simple Notification Service (Amazon SNS) is a web service that c
1oordinates and manages the delivery or sending of messages to recipients.\n-   In Amazon SNS, there are two types of clients—**publishers and subscribers—also referred to as producers and consumers**. Publishers communicate **asynchronously** with subscribers by producing and sending a message to a topic, which is a logical access point and communication channel.\n-   Subscribers consume or receive the message or notification over one of the supported protocols when they are subscribed to the topic.\n\n### Amazon Simple Email Service (Amazon SES)\n\n-   Amazon Simple Email Service (Amazon SES) is a cost-effective email service that organizations can use to send transactional emails, marketing messages, or any other type of content to their customers.\n-   Amazon SES can also be used to receive messages and deliver them to an Amazon S3 bucket, call custom code via an AWS Lambda function, or publish notifications to Amazon SNS.\n\n### Amazon Simple Workflow Service (Amazon SWF)\n\n-   Amazon Simple Workflow Service (Amazon SWF) helps developers build, run, and scale background jobs that have parallel or sequential steps.\n-   Amazon SWF can be thought of as a fully managed state tracker and task coordinator on the cloud.\n-   In common architectural patterns, if your application’s steps take more than 500 milliseconds to complete, it is vitally important to track the state of processing and to provide the ability to recover or retry if a task fails. Amazon SWF helps organizations achieve this reliability.\n\n### Amazon Simple Queue Service (Amazon SQS)\n\n-   Amazon Simple Queue Service (Amazon SQS) is a fast, reliable, scalable, fully managed **message queuing service.**\n-   Amazon SQS makes it simple and cost-effective to decouple the components of a cloud application.\n-   With Amazon SQS, organizations can transmit any volume of data, at any level of throughput, without losing messages or requiring other services to be always available.\n\n## Cloud Object Storage - Amazon S3\n\nCommon use cases for Amazon S3 storage include:\n\n-   Backup and archive for on-premises or cloud data\n-   Content, media, and software storage and distribution Big data analytics\n-   Static website hosting\
1n-   Cloud-native mobile and Internet application hosting\n-   Disaster recovery\n\nS3 offers 3 storage classes\n\n-   Standard\n-   Infrequent Access\n-   archive\n\nCan use lifecycle policy to automatically migrate the data to the appropriate storage class.\n\nGlacier is used for archived data storage or for storing cold data.\n\n### s3 Bucket\n\nA _bucket_ is a container (web folder) for objects (files) stored in Amazon S3. Every Amazon S3 the object is contained in a bucket.\n\nYour bucket names must be unique across all AWS accounts, much like Domain Name System (DNS) domain names, not just within your own account.\n\nBucket names can contain up to 63 lowercase letters, numbers, hyphens, and periods.\n\nYou can create and use multiple buckets; you can have up to 100 per account by default.\n\nEven though the namespace for Amazon S3 buckets is global, each Amazon S3 bucket is created in a specific region that you choose.\n\n### Objects\n\n_Objects_ are the entities or files stored in Amazon S3 buckets. An object can store virtually any kind of data in any format. Objects can range in size from 0 bytes up to 5TB, and a single bucket can store an unlimited number of objects. This means that Amazon S3 can store a virtually unlimited amount of data.\n\n### Durability and Availability\n\nAmazon S3 standard storage is designed for 99.999999999% durability and 99.99% availability of objects over a given year. Amazon S3 achieves high durability by automatically storing data redundantly on multiple devices in multiple facilities within a region.\n\nIf you need to store non-critical or easily reproducible derived data (such as image thumbnails) that doesn’t require this high level of durability, you can choose to use Reduced Redundancy Storage (RRS) at a lower cost. RRS offers 99.99% durability with a lower cost of storage than traditional Amazon S3 storage.\n"])</script>
1<script>self.__next_f.push([1,"51:T3aaf,"])</script>
1<script>self.__next_f.push([1,"\n## Introduction to Spring Boot\n\nSpring Boot is a popular, open-source, enterprise-level framework for creating standalone, production-grade applications that run on the Java Virtual Machine (JVM).\n\nIt requires minimal to zero configuration and is easy to get started. It is a widely popular choice among Java developers for developing Microservices, REST APIs and Web applications.\n\nSpring Boot is built on top of the popular Spring Framework and it inherits all Enterprise Java features like [Dependency Injection (DI)](/articles/dependency-injection-in-spring-boot) or Inversion of Control (IoC), Transaction Management, Validation, Data binding and many more.\n\nSpring Boot was created by Pivotal (now part of Broadcom) and was first released in **April 2014** to eliminate the boilerplate configuration that made getting started with the Spring Framework difficult. Since then, it has become the de facto standard for building Java applications. \n\nThe current major version, **Spring Boot 3**, requires **Java 17** or later and migrated the framework to the `jakarta.*` namespace (from `javax.*`) as part of the move to Jakarta EE.\n\nHere's a glimpse of what a Spring Boot application looks like. Don't worry about understanding every line yet — we'll set one up from scratch in [Chapter 3 - Setting Up Your First Spring Boot Project](/articles/setting-up-your-first-spring-boot-project) and break down exactly what's happening in [Chapter 4 - Understanding Spring Boot Project Structure](/articles/understanding-spring-boot-project-structure).\n\n```java\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class HelloSpringApplication {\n\n    public static void main(String[] args) {\n        SpringApplication.run(HelloSpringApplication.class, args);\n    }\n}\n```\n\nThat's it — no XML, no external server, no boilerplate. This one class, combined with the starter dependencies you choose, is enough to start a fully working application.\n\n## Why do we need Spring Boot when we have Spring Framework?\n\nHere are some of the features that make a strong case for choosing Spring Boot as opposed to Spring Framework:\n\n**Minimal configuration:**\nWhile the Spring Framework is a powerhouse with many built-in production-ready features, it requires **complex configurations**. We need to create XML or Java-based configurations to enable different features of the Spring Framework.\n\nOn the other hand, Spring Boot takes an opinionated approach. It reduces development time and increases developer productivity. Spring Boot provides many default configurations for commonly used tasks and requires minimal configurations.\n\n**Automatic dependency resolution**\nIn Spring, developers need to manage dependencies manually, which can sometimes lead to version conflicts and other incompatibility issues. However, Spring Boot comes with starter packages which resolve all transitive dependencies automatically and you don't need to worry about version incompatibility issues.\n\n**Embedded Servers**\nApplications developed with the Spring Framework require an external application server like Tomcat or JBoss for the deployment. But Spring Boot comes with embedded servers.\n\n**Microservice Ready**\nWhile we can use Spring Framework to build microservices, it doesn't provide any specific tools or features to support Microservices architecture. On the other hand, Spring Boot is well equipped for Microservices.\n\n## What can we use Spring Boot for?\n\nSpring Boot is ideal for building a variety of applications, including:\n\n-   Development of stand-alone applications\n-   Web applications\n-   RESTful APIs\n-   Backend services to generate nightly reports or process large volumes of data\n-   Command line applications\n-   Event-driven, loosely coupled Microservices\n-   Serverless applications\n\n## Key Features of Spring Boot\n\nHere are some of the key features of the Spring Boot framework:\n\n1.  Auto-configuration\n2.  Dependency Injection (DI)\n3.  Spring Boot Starter Dependencies\n4.  Embedded Server\n5.  Production-ready features\n\nThe first two features (auto-configuration and Dependency Injection) are inherited from the Spring Framework.\n\n### 1. Auto Configuration\n\nAuto-configuration allows you to simplify the setup and configuration of Spring applications. It makes it easier to create production-ready applications with minimal effort.\n\nIt automatically configures the application and provides a set of defaults based on the dependencies present in the classpath. When we include certain types of dependencies in our Spring Boot project, the framework automatically configures the beans and components to provide a set of defaults.\n\nFor example, when you start the Spring Boot application with the `spring-boot-starter-data-jpa` dependency, it will scan through the classpath and identify the `JpaAutoConfiguration` class which is responsible for automatically configuring JPA components. It configures a `DataSource` bean, and an `EntityManagerFactory` bean for you to work with JPA.\n\nWe can provide the data source configuration using the following configuration properties.\n\n```properties\nspring.datasource.url=jdbc:mysql://localhost:3306/your_database\nspring.datasource.username=myuser\nspring.datasource.password=mypassword\nspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver\n```\n\nHere's how that auto-configuration flow works when JPA starter is added to the classpath:\n\n```mermaid\ngraph LR\n    A[Add spring-boot-starter-data-jpa] --\u003e B[Spring Boot scans the classpath]\n    B --\u003e C[JpaAutoConfiguration class detected]\n    C --\u003e D[DataSource bean configured]\n    C --\u003e E[EntityManagerFactory bean configured]\n```\n\nAuto-configuration helps developers reduce the number of errors caused due to misconfiguration and makes them more productive.\n\n### 2. Dependency Injection\n\nDependency Injection (DI) is one of the core features of the Spring Framework. This allows developers to write loosely coupled code that is easy to maintain and test.\n\nDI is a software design pattern used in object-oriented programming, where the dependencies of a class are provided by an external entity rather than being created within the class itself. In other words, instead of a class creating the object of its dependencies, those dependencies are \"injected\" into the class from outside.\n\nAs Spring Boot is built on top of the Spring Framework, it inherits all the Spring capabilities including Dependency Injection.\n\nWe will cover Dependency Injection in more detail in [Chapter 5 - Dependency Injection in Spring Boot\n](/articles/dependency-injection-in-spring-boot).\n\n### 3. Spring Boot Starter Dependencies\n\nWhile developing production-grade applications, we often require multiple external libraries. For example, if you want to implement logging, you would require the **Logback** or **Log4J** dependency.\n\nThere are generally 2 types of dependencies:\n\n-   **Direct Dependency:** These are dependencies defined in your `pom.xml` or `build.gradle` file under the `dependencies` section.\n-   **Transitive Dependency:** These are dependencies that are the dependencies of your direct dependencies.\n\nTraditionally, managing application dependencies involved downloading JAR files and manually including them in your project. However, using build tools like **Gradle** and **Maven**, this process has become significantly easier. That said, these tools do not fully address the issue of version compatibility among dependencies.\n\nFor example, let's say our application uses **Library1** and **Library2**, we need to include both libraries manually in our dependency descriptor ( `pom.xml` or `build.gradle`) file. We need to ensure, that both the library versions are compatible with each other.\n\nAs the application grows, the number of dependencies will grow and managing those dependencies manually becomes very cumbersome and error-prone.\n\nThis is where the **Spring Boot starter packages** come to the rescue. Spring Boot provides several Spring Boot starter packages to address this problem.\n\n\u003e _Starter dependencies are a set of convenient dependency descriptors that we can use to bootstrap our Spring boot applications. They contain a lot of pre-defined dependencies with a supported set of transitive dependencies._\n\nFor example, if we add the `spring-boot-starter-web` dependency to our `pom.xml` file then it will download `spring-boot-starter-tomcat` as the direct dependency and with that, it will also download the other transitive dependencies like `tomcat-embedded-core` and `tomcat-embedded-el` and `tomcat-embedded-websocket` dependency.\n\nThe starter dependencies guarantee that all **direct** and **transitive** dependencies remain compatible with one another. This allows developers to concentrate solely on application development without the burden of manually managing version compatibility.\n\nSpring Boot starter packages follow a similar naming pattern, e.g. `spring-boot-starter-{XYZ}
1`, where XYZ denotes a particular type of library.\n\nHere are some of the popular Spring Boot starter packages:\n\n| Starter Package | Description |\n| --- | --- |\n| spring-boot-starter-web | It is used for building web applications, including RESTful applications using Spring MVC. It uses Tomcat as the default embedded container. |\n| spring-boot-starter-activemq | It is used in JMS messaging using Apache ActiveMQ. |\n| spring-boot-starter-actuator | Provides production-ready features such as health checks, monitoring, and other application management features. |\n| spring-boot-starter-batch | It is used for the Spring Batch. |\n| spring-boot-starter-cache | It is used for Spring Framework's caching support. |\n| spring-boot-starter-data-jpa | It is used for Spring Data JPA with Hibernate. |\n| spring-boot-starter-data-mongodb | It is used for MongoDB document-oriented database and Spring Data MongoDB. |\n| spring-boot-starter-security | It is used to add Spring Security to your application for authentication and authorization. |\n| spring-boot-starter-test | It is used for testing Spring Boot applications, and includes JUnit, Mockito, and Spring Test. |\n\nThe easiest way to bootstrap a new Spring Boot project with the starters you need is [Spring Initializr](https://start.spring.io/) — a web-based tool where you can pick your build tool, language, Spring Boot version, and starter dependencies, and then download a ready-to-import project. Most IDEs, including IntelliJ IDEA, Eclipse, and VS Code, also have Spring Initializr support built in.\n\nAlternatively, if you have the Spring CLI installed, you can get the comprehensive list of Spring Boot starters using the following command.\n\n```bash\nspring init --list\n```\n\n### 4. Embedded Servers\n\nTraditionally, deploying Spring-based applications requires the creation of a deployable WAR (Web Application Archive) file, which is then deployed to an external servlet container such as Tomcat or JBoss. It is important to note that WAR files cannot be run as standalone applications and we can only use them as components of another application, like a servlet container or an application server.\n\nIn contrast, Spring Boot applications are designed to be standalone. They offer built-in support for embedded servers, including Tomcat, Jetty, and Undertow. This feature eliminates the need for external web servers, making Spring Boot applications suitable for deployment within containerized environments.\n\nBy default, Spring Boot utilizes Tomcat as its embedded server, which can be accessed through the **spring-boot-starter-web** dependency.\n\nFor those who prefer to use the **Jetty** or **Undertow** server instead of **Tomcat**, it is possible to include the spring-boot-starter-jetty or spring-boot-starter-undertow dependencies, respectively.\n\nFollow this tutorial that explains the step-by-step configuration required to [replace the embedded Tomcat server with Jetty or Undertow](/articles/replace-tomcat-with-jetty-or-undertow-in-spring-boot).\n\n### 5. Production Ready Features\n\nSpring Boot Framework includes some of the production-ready features such as metrics, health checks, external configuration management, validation, and error handling.\n\nIt can also integrate with various enterprise technologies such as RMI, JPA, JMS, AMQP, etc.\n\n-   RMI\n-   Hibernate\n-   WebSocket API ([JSR 356](https://www.jcp.org/en/jsr/detail?id=356))\n-   AMQP - Advanced Message Queuing Protocol\n-   Java Web Services\n-   JPA ([JSR 338](https://jcp.org/en/jsr/detail?id=338)) - Java Persistence API\n-   JMS\n-   Actuators\n-   Validators\n\nSpring also provides a Model-View-Controller (MVC) framework that simplifies the development of web applications by separating the presentation layer from the business logic.\n\nIt also provides several tools and frameworks for testing applications, including the Spring Test Framework and the Spring MVC Test Framework.\n\n## Spring Boot vs. Spring: Which one to choose?\n\nBoth Spring and Spring Boot are widely appreciated frameworks in the Java community. Ultimately, the best framework for you will depend on your specific requirements.\n\nThe following table summarizes the difference between the two frameworks, which can help you as a guiding principle to choose one over the other.\n\n| Features | Spring | Spring Boot |\
1n| --- | --- | --- |\n| Source type | It is an open-source framework. | It is built on top of a Spring framework. It inherits everything Spring has to offer. |\n| Core features | Dependency injection, Spring IOC container, Integration with Java EE frameworks | Auto-configuration, Spring Boot Starters, Embedded servers |\n| Deployment | Requires application server. The deployment descriptor is required. | Embedded servers are provided. The deployment descriptor is not required. |\n| Use cases | For large-scale enterprise applications where fine-grained control of specific configurations and dependencies is crucial. | Good for rapid application development. Best suited for developing Microservices |\n| Setup time | Requires complex configuration and can take more time to set up. | Faster to set up, and requires minimal configuration. |\n\nSpring Boot is a great choice to get started with Spring development without having to worry about the complexities of the Spring Framework. Once you understand Spring better, you can decide if you need the additional features and flexibility of the Spring Framework.\n\n## Summary\n\nIn this chapter, we introduced Spring Boot — what it is, why it exists alongside the Spring Framework, and the kinds of applications you can build with it. We also looked at its key features: auto-configuration, Dependency Injection, starter dependencies, embedded servers, and production-ready features, and compared Spring Boot with the Spring Framework to help you decide which one fits your use case.\n\nIn the next chapter, we'll walk through the [prerequisites and tooling](/articles/prerequisites-for-spring-boot-development) you need before writing your first Spring Boot application.\n"])</script>
1<script>self.__next_f.push([1,"52:T2a21,"])</script>
1<script>self.__next_f.push([1,"\n## Introduction to Interceptors\n\nSpring Interceptors are used to intercept client requests before they are handled by the controller. They can also be used to intercept the response before the response is sent back to the client.\n\nInterceptors are part of the Spring Web MVC framework and provide a way to add pre/post-processing logic to your application's request-response lifecycle.\n\n### Realtime Use Cases of Interceptors\n\nSome of the the common use cases for interceptors include tasks, such as:\n\n-   **Logging:** Interceptors can be used to log HTTP requests and responses. This can be useful for debugging or tracking the performance of an application.\n\n-   **Security:** Interceptors can be used to enforce security policies. For example, an interceptor could be used to check that a user is authenticated before allowing them to access a resource.\n\n-   **Caching:** Interceptors can be used to cache HTTP requests and responses. This can improve the performance of an application by reducing the number of times that requests need to be made to the underlying resources.\n\n-   **Transformation:** Interceptors can be used to transform HTTP requests and responses. For example, an interceptor could be used to convert JSON requests to XML responses.\n\n### Spring Request/Response Life-Cycle\n\n![](/media/https://sgp1.digitaloceanspaces.com/stacktips/media/uploads/summernote/spring-request-response-lifecycle.png)  \n\nIn a typical Spring Boot application flow, when the client sends an HTTP request to a specific endpoint(URL), the request is first received by the web server (e.g., Apache Tomcat or Jetty) and then forwarded to the Spring Boot application.\n\nThe Dispatcher Servlet is the entry point for incoming requests in the Spring Boot application. Once the DispatcherServlet receives the request, it consults the HandlerMapping. The HandlerMapping is responsible for determining which controller should process the incoming request based on the URL mapping defined within your controller.\n\n### Filters vs Interceptors\n\nSimilar to Interceptors, you can also use Servlet filters to intercept the request/response in Spring Boot. But Filters are part of the Servlet API and operate at a lower level.\n\nFilters are not specific to the Spring framework. However, you can still use Servlet filters in a Spring application because the Spring framework itself is built on top of the Servlet API.\n\nOkay then, how do I decide which one to use?\n\n-   If the task is specifically related to Spring MVC and requires access to the Spring application context, then interceptors are more suitable.\n\n-   If the task is not tied to Spring MVC and can be handled at the Servlet level, a filter might be a more straightforward and flexible option.\n\n## Creating Interceptor in Spring Boot\n\nTo create an interceptor in Spring Boot, you typically create a class that implements the `**HandlerInterceptor**` interface.\n\nThe `**HandlerInterceptor**` interface has three methods:\n\n1.  `**preHandle()**`: The preHandle() method is the most important method in the HandlerInterceptor. This method is executed before the actual controller method is called. It returns a boolean value indicating whether the request should continue to the controller or be stopped.\n\n2.  `**postHandle()**`: This method is executed after the controller method is called but before the response is sent to the client. It allows you to modify the model and view before rendering the response. You can use this method to perform any tasks that you need to do after the request has been handled. For example, you could use the `postHandle()` method to add additional information to the response, or to log the response.\n\n3.  `**afterCompletion()**`: This method is executed after the response has been sent to the client. This method is called even if an exception was thrown during the processing of the request. It's useful for cleanup or resource release tasks.\n\n### Create a Spring Boot REST API\n\nFor the demonstration purpose, we will implement a Spring boot REST API with the following endpoints:\n\n-   GET /products/list\n\n-   POST /products/new that accepts the following JSON payload.\n\n```json\n{\n   \"id\": \"100\",\n   \"name\": \"iPhone 12\",\n   \"price: 1200.00\n}\n```\n\nFirst, let us generate a new Spring Boot project using a Spring Initializer and add the `spring-starter-web` and `lombook` dependencies.\n\n#### The Product Model\n\nLet us create a new file `Product.java` and add the following code:\n\n```java\npublic class Product {\n\n    Long id;\n    String name;\n    Double price;\n\n    public Product(Long id, String name, Double price) {\n        this.id = id;\n        this.name = name;\n        this.price = price;\n    }\n}\n```\n\n#### The Product Controller\n\nNow, let us add a controller class `ProductController.java` and define the endpoint mappings:\n\n```java\n@RestController\n@RequestMapping(value = \"/products\",\n        produces = {MediaType.APPLICATION_JSON_VALUE})\npublic class ProductController {\n\n    @GetMapping(value=\"/list\")\n    public ResponseEntity\u003cList\u003cProduct\u003e\u003e getProducts() {\n        List\u003cProduct\u003e products = List.of(\n                new Product(1001L, \"iPhone 12\", 1200.0),\n                new Product(1002L, \"iPhone 14\", 300.0)\n        );\n\n        return ResponseEntity.ok(products);\n    }\n\n    @PostMapping(value=\"/new\")\n    public ResponseEntity\u003cProduct\u003e createProduct(\n                @RequestBody Product product)throws URISyntaxException {\n        return ResponseEntity.ok(product).build();\n    }\n\n}\n```\n\nRun your Spring Boot application now and verify if both endpoints are working.\n\n## Implementing Interceptor in Spring Boot\n\nNow that we have our Spring Boot application running let us now create an interceptor to print the logs when a request is made to our controller.\n\nTo create a interceptor in Spring boot, let us now create a new class `LogHandlerInterceptor`and implement `HandlerInterceptor` interface.\n\n```java\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.web.servlet.HandlerInterceptor;\nimport org.springframework.web.servlet.ModelAndView;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n@Slf4j\npublic class LogHandlerInterceptor implements HandlerInterceptor {\n\n    @Override\n    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {\n      log.info(\"LogHandlerInterceptor::preHandle()\");\n      return true;\n    }\n\n    @Override\n    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {\n        log.info(\"LogHandlerInterceptor::postHandle()\");\n    }\n\n    @Override\n    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {\n        log.info(\"LogHandlerInterceptor::afterCompletion()\");\n    }\n}\n```\n\n## Registering the Logger Interceptor\n\nOnce you have created your custom interceptor, you need to register it with the Spring Boot application using `**WebMvcConfigurer**` configuration:\n\n```java\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.servlet.config.annotation.InterceptorRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\n\n@Configuration\npublic class WebConfig implements WebMvcConfigurer {\n\n    @Override\n    public void addInterceptors(InterceptorRegistry registry) {\n        registry.addInterceptor(new LogHandlerInterceptor());\n    }\n}\n```\n\nWith this configuration, your interceptor will be invoked for each incoming request, and you can implement your custom logic in the interceptor's methods accordingly.\n\n## Interceptor to Check Basic Authentication\n\nLet us now add another interceptor to perform the basic authentication check. This interceptor will be invoked only for `/products/new` endpoint and it will do the basic authentication check before allowing access to the controller.\n\nFor this example, we will hardcode a username and password to verify the credentials passed by the user.\n\n```java\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.web.servlet.HandlerInterceptor;\nimport org.springframework.web.servlet.ModelAndView;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Base64;\n\n@Slf4j\npublic class BasicAuthInterceptor implements HandlerInterceptor {\n    private static final Str
1ing USERNAME = \"admin\";\n    private static final String PASSWORD = \"admin\";\n\n    @Override\n    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {\n        log.info(\"BasicAuthInterceptor::preHandle()\");\n\n        String authHeader = request.getHeader(\"Authorization\");\n        if (authHeader != null \u0026\u0026 authHeader.startsWith(\"Basic \")) {\n\n            String base64Credentials = authHeader.substring(\"Basic \".length());\n            byte[] decodedCredentials = Base64.getDecoder().decode(base64Credentials);\n            String credentials = new String(decodedCredentials, StandardCharsets.UTF_8);\n\n            String[] parts = credentials.split(\":\");\n            String username = parts[0];\n            String password = parts[1];\n\n            if (USERNAME.equals(username) \u0026\u0026 PASSWORD.equals(password)) {\n                return true;\n            }\n        }\n\n        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, \"Unauthorized\");\n        return false;\n    }\n\n    @Override\n    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {\n        log.info(\"BasicAuthInterceptor::postHandle()\");\n    }\n\n    @Override\n    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {\n        log.info(\"BasicAuthInterceptor::afterCompletion()\");\n    }\n}\n```\n\nNow, we need to register the BasicAuthInterceptor class by adding it to InterceptorRegistry\n\n```java\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.servlet.config.annotation.InterceptorRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\n\n@Configuration\npublic class WebConfig implements WebMvcConfigurer {\n\n    @Override\n    public void addInterceptors(InterceptorRegistry registry) {\n        registry.addInterceptor(new LogHandlerInterceptor());\n        registry.addInterceptor(new BasicAuthInterceptor())\n                .addPathPatterns(\"/products/new\");\n    }\n}\n```\n\nThe order of execution can be set for the interceptors using the `order()` method.\n\n```java\nregistry.addInterceptor(new LogHandlerInterceptor()).order(1);\n```\n"])</script>
1<script>self.__next_f.push([1,"53:T978,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we'll show you how to set up MongoDB in a Docker container. By containerizing MongoDB, you can quickly deploy and use MongoDB effortlessly for your local development.\n\nHere is a step-by-step guide to setting up MongoDB within a Docker container:\n\n### Install Docker\n\nFirst, make sure you have Docker installed on your machine. If it is not installed, you can download Docker Desktop from the official Docker website. Visit [https://docs.docker.com/engine/install/](https://docs.docker.com/engine/install/) and download the package appropriate for your operating system.\n\n### Pull MongoDB Image\n\nNow, let us pull the official MongoDB Docker image from Docker Hub. To do that, open your terminal and run the following command:\n\n```bash\ndocker pull mongo\n```\n\n### Run MongoDB Container\n\nNow, run the following command to start MongoDB in a container:\n\n```bash\ndocker run \\\n    -d \\\n    --name mongodb \\\n    -p 27017:27017 \\\n    -e MONGO_INITDB_ROOT_USERNAME={YOUR_USERNAME} \\\n    -e MONGO_INITDB_ROOT_PASSWORD={YOUR_PASSWORD} \\\n    mongo\n```\n\nOptions:\n\n-   The `-d` option is used to run the container in detached mode, meaning the container will run in the background and won't block your terminal.\n\n-   The `--name` option allows you to provide a name for your MongoDB container. I have used `mongodb` here, but you can use anything you want.\n\n-   The `-p` option is used to map the container's port to the host machine's port. The port 27017 on the left-hand side of the colon (`:`) represents the port on the host machine, and the right-hand side is the port of MongoDB. The default MongoDB port is 27017.\n\n-   The default MongoDB username and password can be set using the environment variables `MONGO_INITDB_ROOT_USERNAME` and `MONGO_INITDB_ROOT_PASSWORD`. The environment variables are provided with the `-e` option.\n\nThis command will start a Docker container named \"mongodb\" and map the default MongoDB port 27017 from the container to the same port on your host machine.\n\n### Verify Running MongoDB Container\n\nYou can check if the container is running by executing the command:\n\n```bash\ndocker ps\n```\n\nIt should display a list of running containers, and you should see the \"mongodb\" container in the list.\n\n### Stop MongoDB Container\n\nTo stop a MongoDB Docker container, you can use the following command:\n\n```bash\ndocker stop mongodb\n```\n\nTo start MongoDB again:\n\n```bash\ndocker start mongodb\n```\n"])</script>
1<script>self.__next_f.push([1,"54:T59a,"])</script>
1<script>self.__next_f.push([1,"\nIn a Spring Boot application, the context path represents the base URL for accessing your application. By default, it's set to '/',  \n\nFor example, in the following code snippet\n\n```java\n      @RestController\n@RequestMapping(value = \"/products\")\npublic class ProductController {\n\n    @GetMapping\n    public List\u003cProduct\u003e getProducts() {\n        return ResponseEntity.ok(productService.getProducts());\n    }\n\n    @GetMapping(value = \"/{productId}\")\n    public Product getProduct(@PathVariable(value = \"id\") Long id) {\n            //Your service logic goes here..\n      return product;\n    }\n```\n\nTo test this locally, we need to hit\n\n```text\nhttp://localhost:8080/products\nhttp://localhost:8080/products/{productId}\n```\n\nBut sometimes you might want to change the path to make it more meaningful or to avoid conflicts. So, how do we do that?”\n\nTo change the context path, you need to add the following property to your `application.properties` file.\n\n```text\n      server.servlet.context-path=/api/1.0\n```\n\nAlternatively, if you're using the application.yaml file, you can do this\n\n```yaml\nserver:\n   servlet:\n     context-path: '/api/1.0'\n```\n\n`   Now with this, you run your application and you will be able to access the endpoints with a new URL  ```       http://localhhost:8080/api/1.0/products http://localhhost:8080/api/1.0/products/{productId}      ```  I hope this helps! Let me know if you have any other questions.   `\n"])</script>
1<script>self.__next_f.push([1,"55:T2450,"])</script>
1<script>self.__next_f.push([1,"\nThis article will explore how to create and customize a CardView in Flutter. In this tutorial, we will dive into the basics of creating a CardView and explore various customization options available in Flutter.\n\nA `CardView` is a rectangular panel with slightly rounded corners, usually containing the content and the action about a single subject.\n\nTo learn more about the CardView UX guidelines and design principles, you can visit the official Google material design 3 website [https://m3.material.io/](https://m3.material.io/).\n\nNow without further delay, let us jump straight into the implementation.\n\n## **Creating a Basic Flutter App**\n\nLet us start by creating a simple Flutter project.\n\n```dart\nimport 'package:flutter/material.dart';\n\nclass CardViewExample extends StatefulWidget {\n const CardViewExample({super.key});\n\n @override\n State\u003cCardViewExample\u003e createState() {\n   return CardViewExampleState();\n }\n}\n\nclass CardViewExampleState extends State\u003cCardViewExample\u
1003e {\n\n @override\n Widget build(BuildContext context) {\n\n   return Scaffold(\n       appBar: AppBar(\n         backgroundColor: Colors.green.shade600,\n         title: const Text('CardView',\n             style: TextStyle(\n               color: Colors.white,\n               fontWeight: FontWeight.normal,\n             )),\n       ),\n\n       body: const Center(\n         child: Text(\"Hello World!\"),\n       ));\n }\n}\n```\n\nIn Flutter, a Scaffold is a widget that provides a basic Material Design layout structure. It is a container that can contain other widgets, such as an AppBar, a body, and a floating action button. The Scaffold also provides APIs for showing drawers, snack bars, and bottom sheets.\n\nIn the code snippet above the page body contains a Text widget aligned to the centre of page.\n\n## **Creating a CardView**\n\nLet us now add a basic CardView widget.\n\n```dart\nbody: const Card(\n  margin: EdgeInsets.all(20),\n  child: Text('Apple iPhone 14 Pro Max, 2021 128 GB',\n    style: TextStyle(\n      fontSize: 24,\n      color: Colors.black87,\n      height: 1.3,\n      fontWeight: FontWeight.bold,\n    ),\n  ),\n)\n```\n\nThe above code creates a Card widget with a margin of 20 pixels and a Text widget as its child. The text content displays \"Apple iPhone 14 Pro Max, 2021 128 GB\" with specific visual styles applied, including font size, color, line height, and font weight.\n\nLet us now add another text view ‘subtitle’ to the card.\n\nThe CardView in Flutter can contain only one direct child. Hence, If we want to have multiple child views, we need to wrap them inside a Column widget.\n\n```dart\nColumn(\n  mainAxisSize: MainAxisSize.min,\n  crossAxisAlignment: CrossAxisAlignment.stretch,\n  children: [\n    Text(\n      \"Apple iPhone 14 Pro Max\",\n      maxLines: 3,\n      style: TextStyle(\n        fontSize: 24,\n        color: Colors.white,\n        height: 1.3,\n        fontWeight: FontWeight.bold,\n      ),\n    ),\n    Text(\n        'Powerful A14 Bionic chip, 5G capability, and a stunning Super',\n        maxLines: 3,\n        style: TextStyle(\n          fontSize: 20,\n          color: Colors.white70,\n          height: 1.3,\n          fontWeight: FontWeight.w500,\n        ))\n  ])\n```\n\n* * *\n\nThe CardView now has two text fields, one for the title and another for the subtitle. However, it still doesn’t look great as there is no inner padding around the CardView and also no padding between the title and subtitle.\n\n## **Apply Padding to CardView Elements**\n\nTo add the padding around the CardView, we need to wrap the `Column` widget inside a `Padding` widget.\n\n```dart\nPadding(\n    padding: EdgeInsets.all(20),\n    child: Column(\n        mainAxisSize: MainAxisSize.min,\n        crossAxisAlignment: CrossAxisAlignment.stretch,\n        children: [\n          Text(\n            \"Apple iPhone 14 Pro Max\",\n            maxLines: 3,\n            style: TextStyle(\n              fontSize: 24,\n              color: Colors.white,\n              height: 1.3,\n              fontWeight: FontWeight.bold,\n            ),\n          ),\n          SizedBox(\n            height: 10,\n          ),\n          Text(\n              'Powerful A14 Bionic chip, 5G capability, and a stunning Super Retina XDR display.',\n              maxLines: 3,\n              style: TextStyle(\n                fontSize: 20,\n                color: Colors.white70,\n                height: 1.3,\n                fontWeight: FontWeight.w500,\n              ))\n        ])\n)\n```\n\nYou may notice another thing in the code snippet above. We have added a `SizedBox` widget between two Text components to allow some space between them.\n\n## **Adding Image to CardView**\n\nLet us use the `FadeInImage` widget to load the image from the URL into the Flutter card widget.\n\nThe `FadeInImage` is a Flutter widget that displays an image with a placeholder while the image is loading. Once the image is loaded, the placeholder is faded out and the image is faded in.\n\nThis is quite a nice and handy feature for images that take a long time to load.\n\n```dart\nFadeInImage(\n  fit: BoxFit.cover,\n  height: 180,\n  width: double.infinity,\n  placeholder: AssetImage('assets/images/loading.gif'),\n  image: NetworkImage(\n      'https://images.unsplash.com/photo-1556656793-08538906a9f8'),\n),\n```\n\n## **Styling Card Widget in Flutter**\n\nThe Card widget in Flutter provides a number of customizations out of the box. Here are some of the properties that allow different customization options\n\n-   **elevation:** This property controls the amount of shadow that is cast by the card. The higher the elevation, the darker the shadow will be.\n\n-   **shape:** This property determines the shape of the card. The default shape is a rounded rectangle, but you can also use a square, circle, or other shape.\n\n-   **color:** This property sets the background color of the card.\n\n-   **border:** This property allows you to add a border to the card. You can specify the color, width, and style of the border.\n\n-   **clipBehavior:** This property controls how the card is clipped when it is overflowed by its content. The default `clipBehavior` is Clip.antiAlias, which means that the card will be clipped smoothly. You can also use Clip.hardEdge to clip the card with a sharp edge.\n\n-   **child:** This property is used to set the child widget that will be displayed inside the card.\n\nHere is an example of how to customize a Card widget in Flutter:\n\n```dart\nimport 'package:flutter/material.dart';\n\nclass CardViewExample extends StatefulWidget {\n  const CardViewExample({super.key});
1\n\n  @override\n  State\u003cCardViewExample\u003e createState() {\n    return CardViewExampleState();\n  }\n}\n\nclass CardViewExampleState extends State\u003cCardViewExample\u003e {\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n        appBar: AppBar(\n          backgroundColor: Colors.green.shade600,\n          title: const Text('CardView',\n              style: TextStyle(\n                color: Colors.white,\n                fontWeight: FontWeight.normal,\n              )),\n        ),\n        body: Card(\n            elevation: 30,\n            margin: const EdgeInsets.all(20),\n            color: Colors.green.shade600,\n            shape: RoundedRectangleBorder(\n              borderRadius: const BorderRadius.all(Radius.circular(30)),\n              side: BorderSide(color: Colors.yellow.shade800, width: 2)\n            ),\n            clipBehavior: Clip.antiAlias,\n            child: const Column(\n                mainAxisSize: MainAxisSize.min,\n                crossAxisAlignment: CrossAxisAlignment.stretch,\n                children: [\n                  FadeInImage(\n                    fit: BoxFit.cover,\n                    height: 180,\n                    width: double.infinity,\n                    placeholder: AssetImage('assets/images/loading.gif'),\n                    image: NetworkImage(\n                        'https://images.unsplash.com/photo-1556656793-08538906a9f8'),\n                  ),\n                  Padding(\n                      padding: EdgeInsets.all(20),\n                      child: Column(\n                          mainAxisSize: MainAxisSize.min,\n                          crossAxisAlignment: CrossAxisAlignment.stretch,\n                          children: [\n                            Text(\n                              \"Apple iPhone 14 Pro Max\",\n                              maxLines: 3,\n                              style: TextStyle(\n                                fontSize: 24,\n                                color: Colors.white,\n                                height: 1.3,\n                                fontWeight: FontWeight.bold,\n                              ),\n                            ),\n                            SizedBox(\n                              height: 10,\n                            ),\n                            Text(\n                                'Powerful A14 Bionic chip, 5G capability, and a stunning Super Retina XDR display.',\n                                maxLines: 3,\n                                style: TextStyle(\n                                  fontSize: 20,\n                                  color: Colors.white70,\n                                  height: 1.3,\n                                  fontWeight: FontWeight.w500,\n                                ))\n                          ]))\n                ])));\n  }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"56:Td45,"])</script>
1<script>self.__next_f.push([1,"\nThe Floating Action Button (FAB) represents the critical user action on that screen. This widget looks like a round button floating in the bottom right corner of the screen and hence it is very accessible and within the reach of the users.\n\n### Creating a Floating Action Button\n\nThe `FloatingActionButton` widget class in Flutter can be used to create a floating button. The following code shows how to create a simple floating button in Flutter.\n\n```dart\nimport 'package:flutter/material.dart';\n\nvoid main() {\n  runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      home: Scaffold(\n        floatingActionButton: FloatingActionButton(\n          child: const Icon(Icons.format_size_sharp, color: Colors.white),\n          onPressed: () {\n            // Do something\n          },\n        ),\n      ),\n\n    );\n  }\n}\n```\n\n![](/media/https://sgp1.digitaloceanspaces.com/stacktips/media/uploads/summernote/regular-floating-action-button.png)  \n\n### Customize the Floating Action Button\n\nThe `FloatingActionButton` widget has a number of properties that can be used to customize its appearance and behavior. For example, we can use the `backgroundColor` property to set the button background colour and the `onPressed` property to set a callback that is executed when the button is pressed.\n\n```dart\nfloatingActionButton: FloatingActionButton(\n  tooltip: \"Settings\",\n  backgroundColor: Colors.cyan.shade800,\n  foregroundColor: Colors.white,\n  elevation: 5,\n  shape: RoundedRectangleBorder(\n    borderRadius: BorderRadius.circular(18),\n  ),\n  onPressed: () {\n    // Do something here.\n  },\n  child: const Icon(Icons.format_size_sharp, color: Colors.white),\n),\n```\n\n### Displaying Icon and label on the floating action button\n\n```dart\nfloatingActionButton: FloatingActionButton.extended(\n  tooltip: \"Settings\",\n  backgroundColor: Colors.cyan.shade800,\n  foregroundColor: Colors.white,\n  elevation: 5,\n  shape: RoundedRectangleBorder(\n    borderRadius: BorderRadius.circular(18),\n  ),\n  onPressed: () {\n    // Do something here.\n  },\n  icon: const Icon(Icons.format_size_sharp, color: Colors.white),\n  label: const Text(\"Settings\"),\n),\n```\n\n![](/media/https://sgp1.digitaloceanspaces.com/stacktips/media/uploads/summernote/floating-action-button-with-label.png)  \n\n### Small Floating Action Button\n\n```dart\nfloatingActionButton: FloatingActionButton.small(\n  tooltip: \"Settings\",\n  backgroundColor: Colors.cyan.shade800,\n  foregroundColor: Colors.white,\n  elevation: 5,\n  shape: RoundedRectangleBorder(\n    borderRadius: BorderRadius.circular(18),\n  ),\n  onPressed: () {\n    // Do something here.\n  },\n  child: const Icon(Icons.format_size_sharp, color: Colors.white),\n),\n```\n\n![](/media/https://sgp1.digitaloceanspaces.com/stacktips/media/uploads/summernote/small-floating-action-button.png)\n\n### Large Floating Action Button\n\n```dart\nfloatingActionButton: FloatingActionButton.large(\n  tooltip: \"Settings\",\n  backgroundColor: Colors.cyan.shade800,\n  foregroundColor: Colors.white,\n  elevation: 5,\n  shape: RoundedRectangleBorder(\n    borderRadius: BorderRadius.circular(18),\n  ),\n  onPressed: () {\n    // Do something here.\n  },\n  child: const Icon(Icons.format_size_sharp, color: Colors.white),\n),\n```\n\n![](/media/https://sgp1.digitaloceanspaces.com/stacktips/media/uploads/summernote/large-floating-action-button.png)\n"])</script>
1<script>self.__next_f.push([1,"57:T2338,"])</script>
1<script>self.__next_f.push([1,"\nThis article will walk you through the process of creating a multi-select grid view in Flutter. In this example, we will create a page that displays a list of products in a two-column layout and allows users to select or deselect items. The HTTP package will be used to retrieve the product list from the Restful API.\n\nThe list of products will be fetched from `https://fakestoreapi.com/products/category/electronics` API and here is how the JSON response is returned:\n\n```json\n[\n    {\n        \"id\": 9,\n        \"title\": \"WD 2TB Elements Portable External Hard Drive - USB 3.0 \",\n        \"price\": 64,\n        \"description\": \"USB 3.0 and USB 2.0 Compatibility Fast data transfers \",\n        \"category\": \"electronics\",\n        \"image\": \"https://fakestoreapi.com/img/61IBBVJvSDL._AC_SY879_.jpg\",\n    },\n    {\n        \"id\": 10,\n        \"title\": \"SanDisk SSD PLUS 1TB Internal SSD - SATA III 6 Gb/s\",\n        \"price\": 109,\n        \"description\": \"Easy upgrade for faster boot-up, shutdown...\",\n        \"category\": \"electronics\",\n        \"image\": \"https://fakestoreapi.com/img/61U7T1koQqL._AC_SX679_.jpg\",\n    }\n]\n```\n\n## Step 1: Setting up the Project\n\nLet’s get started! First, create a new Flutter project and add the following dependencies to the `pubspec.yaml` file\n\n```yaml\ndependencies:\n  flutter:\n    sdk: flutter\n  http: ^0.13.5\n```\n\nNote that, we have added the `http: ^0.13.5` dependency to the `pubspec.yaml` file. This package will be used to make HTTP API calls.\n\n## Step 2: Defining the Model Classes\n\nWe need to create two models for this example. One to hold the product details returned from the API and the other to hold the selected state.\n\nHere is what the `Product` model class looks like:\n\n```dart\nclass Product {\n  final int id;\n  final String title;\n  final num price;\n  final String category;\n  final String description;\n  final String image;\n\n  Product(\n      {required this.id,\n      required this.title,\n      required this.price,\n      required this.category,\n      required this.description,\n      required this.image});\n\n  factory Product.fromJson(Map\u003cString, dynamic\u003e json) {\n    return Product(\n      id: json['id'],\n      title: json['title'],\n      price: json['price'],\n      category: json['category'],\n      description: json['description'],\n      image: json['image'],\n    );\n  }\n}\n```\n\nThe `fromJson()` function is a factory constructor that takes a JSON object and returns an object of the specified type. It is used to deserialise product JSON into a `Product` model object.\n\nNow, let us create another model `MultiSelectItem` to represent a selectable item in a multi-select list. It has two properties: `value` and `selected`. The value property is the value of the item, and the selected property is a boolean value that indicates whether the item is selected.\n\n```dart\nclass MultiSelectItem\u003cT\u003e {\n  final T value;\n  bool selected = false;\n\n  MultiSelectItem(this.value);\n\n}\n```\n\n## Step 3: Fetching Products from the API\n\nNow that we have the models defined, let us now focus on fetching API data. For that, we have created a `ProductRepository` class that fetches products from a fake store API. It uses the `http` package to make a GET request to the API endpoint.\n\nThe response is then parsed into a list of `Product` objects using the `fromJson` factory constructor.\n\n```dart\nimport 'package:http/http.dart' as http;\n\nclass ProductRepository {\n\n  Future\u003cList\u003cProduct\u003e\u003e fetchProducts() async {\n    final response = await http.get(Uri.parse(\"https://fakestoreapi.com/products/category/electronics\"));\n\n    if (response.statusCode == 200) {\n      final jsonList = json.decode(response.body) as List\u003cdynamic\u003e;\n      List\u003cProduct\u003e products = jsonList.map((json) =\u003e Product.fromJson(json)).toList();\n      return products;\n    } else {\n      throw Exception('Failed to fetch products');\n    }\n  }\n}\n```\n\n## Step 4: Building the Product Grid Page\n\nThe `ProductsPage` class is a stateful widget that represents the product grid page. It has an `AppBar` and a `GridView`.\n\nThe FutureBuilder widget displays a loading spinner while waiting for the products to be fetched. If an error occurs, an error message is shown. Otherwise, the grid view is displayed with the fetched products.\n\n```dart\nimport 'dart:convert';\n\nimport 'package:flutter/material.dart';\nimport 'package:http/http.dart' as http;\n\nclass ProductsPage extends StatefulWidget {\n  const ProductsPage({super.key});\n\n  @override\n  State\u003cProductsPage\u003e createState() =\u003e ProductsPageState();\n}\n\nclass ProductsPageState extends State\u003cProductsPage\u003e {\n  List\u003cMultiSelectItem\u003cProduct\u003e\u003e listItems = \u003cMultiSelectItem\u003cProduct\u003e\u003e[];\n  final ProductRepository productRepository = ProductRepository();\n  late Future\u003cList\u003cProduct\u003e\u003e _product\n  get selectedCount =\u003e listItems.where((c) =\u003e c.selected == true).length;\n\n  @override\n  void initState() {\n    super.initState();\n    _products = productRepository.fetchProducts();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: AppBar(\n        backgroundColor: Colors.green.shade600,\n        title: const Text('Electronics',\n            style: TextStyle(\n              color: Colors.white,\n              fontFamily: \"Outfit\",\n              fontWeight: FontWeight.normal,\n            )),\n      ),\n      body: FutureBuilder\u003cList\u003cProduct\u003e\u003e(\n        future: _products,\n        builder: (context, snapshot) {\n          if (snapshot.connectionState == ConnectionState.waiting) {\n            return const Center(child: CircularProgressIndicator());\n          } else if (snapshot.hasError) {\n            return const Center(child: Text('An error occurred while fetching products list.'));\n          } else {\n            bool isListInitialized = listItems.isNotEmpty;\n            if (!isListInitialized) {\n              listItems = snapshot.data!.map((e) =\u003e MultiSelectItem(e)).toList();\n            }\n\n            return GridView.builder(\n              itemCount: listItems.length,\n              shrinkWrap: false,\n              padding: const EdgeInsets.all(12),\n              physics: const ScrollPhysics(),\n              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(\n                crossAxisCount: 2,\n                childAspectRatio: (150.0 / 150.0),\n                crossAxisSpacing: 8,\n                mainAxisSpacing: 8,\n              ),\n              itemBuilder: (context, index) {\n                return GestureDetector(\n                  onTap: () {\n                    setState(() {\n                      listItems[index].selected = !listItems[index].selected;\n                    });\n                  },\n                  child: Container(\n                    child: getGridItem(listItems[index], index),\n                  ),\n                );\n              },\n            );\n          }\n        },\n      ),\n      bottomNavigationBar: SizedBox(\n          width: double.infinity,\n          child: Container(\n            alignment: Alignment.center,\n            color: Colors.grey.shade300,\n            height: 84,\n            padding: const EdgeInsets.fromLTRB(16, 16, 16, 16),\n            child: Text(\"$selectedCount items in cart\",\n                style: const TextStyle(\n                  color: Colors.black87,\n                  fontFamily: \"Outfit\",\n                  fontSize: 22,\n                  fontWeight: FontWeight.w600,\n                )),\n          )),\n    );\n  }\n}\n```\n\n## Step 6: Displaying Product Cards\n\nEach item in the grid is displayed as a `Card` widget inside a `Container`. The `Container` has a colour that changes based on the selected state of the item. The `ListTile` widget inside the `Container` displays the product title and an icon indicating whether the product is selected or not.\n\n```dart\nWidget getGridItem(MultiSelectItem item, int index) {\n    Product product = item.value;\n    Color textColor = item.selected ? Colors.white : Colors.black87;\n    Color bgColor = item.selected ? Colors.green.shade500 : Colors.yellow.shade400;\n    Color borderColor = item.selected ? Colors.green.shade800 : Colors.yellow.shade800;\n    Icon icon = item.selected\n        ? const Icon(Icons.remove_shopping_cart_outlined, color: Colors.white)\n        : Icon(Icons.add_shopping_cart_outlined, color: Colors.yellow.shade900);\n\n    return Card(\n      elevation: 3,\n      shape: RoundedRectangleBorder(\n        side: BorderSide(color: borderColor, width: 2),\n      ),\n      child: Container(\n        padding: const EdgeInsets.all(6),\n        color: bgColor,\n        child: ListTile(\n          trailing: icon,\n          title: Text(\n            product.title,\n            maxLines: 6,\n            style: TextStyle(\n              color: textColor,\n              fontFamily: \"Outfit\",\n              fontSize: 18,\n              fontWeight: FontWeight.w600,\n            ),\n          ),\n        ),\n      ),\n    );\n  }\n```\n\nThat is all! Now we have a fully functional multi-selection grid view in Flutter. Feel free to enhance the page with additional features and customize the UI to match your app's design.\n"])</script>
1<script>self.__next_f.push([1,"58:T2437,"])</script>
1<script>self.__next_f.push([1,"\nWebClient is a non-blocking, reactive HTTP client introduced in Spring 5.0, which is the reactive counterpart to the traditional [RestTemplate](/articles/calling-rest-services-using-resttemplate) in Spring Boot. It provides a simplified and intuitive API for making HTTP requests. It is designed to handle both synchronous and asynchronous operations.\n\nIn this article we will see how to use WebClient to integrate with external HTTP/REST services from Spring Boot.\n\nTo use WebClient in a Spring Boot application, follow these steps:\n\n## Adding WebClient Dependency\n\nEnsure you have the necessary dependencies in your project. If you're using Maven, add the following dependency to your `**pom.xml**` file:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-webflux\u003c/artifactId\u003e\n\u003c/dependency\u003e\n```\n\n## Create a WebClient Bean\n\nIn your code, create an instance of `**WebClient**` using the `**WebClient.builder()**` method. You can customize the WebClient instance by setting properties such as timeouts, authentication, SSL configuration, and more.\n\n```java\nWebClient webClient = WebClient.builder()\n    .baseUrl(\"https://api.example.com\")\n    .build();\n```\n\n## Making HTTP Request using WebClient\n\nUse the methods provided by the WebClient instance to make HTTP requests. WebClient offers methods like `**get()**`, `**post()**`, `**put()**`, `**delete()**`, etc., to perform different types of requests. You can chain these methods together to customize the request.\n\n```java\nMono\u003cMyResponse\u003e responseMono = webClient.get()\n    .uri(\"/data/{id}\", id)\n    .retrieve()\n    .bodyToMono(MyResponse.class);\n```\n\n## Using WebClient in Spring Boot\n\nLet us now examine, how to use `WebClient` in real-time to consume the following APIs from the Spring Boot application.\n\n```text\nGET\nhttps://fakestoreapi.com/products - get all products\nhttps://fakestoreapi.com/products/1 - get specific product based on id\n\nPOST\nhttps://fakestoreapi.com/products - add a new product\n\nDELETE\nhttps://fakestoreapi.com/products/1 - get specific product based on id\n```\n\nLet us now declare a domain model for the `Product` object.  \n\n```java\npublic class Product {\n\n    private String image;\n    private double price;\n    private String description;\n    private int id;\n    private String title;\n    private String category;\n\n    //Getter, Setter\n}\n```\n\n### Consuming GET API in WebClient\n\nLet us now create a service class `ProductService` that consumes the Fakestore API endpoints using WebClient.\n\n```java\n@Service\npublic class ProductService {\n\n    private final WebClient webClient;\n\n    public ProductService() {\n        // you may configure the base URL in applcation.properties\n        this.webClient = WebClient.create(\"https://fakestoreapi.com\");\n    }\n\n    public Mono\u003cProduct[]\u003e getProducts() {\n        return webClient.get()\n                .uri(\"/products\")\n                .retrieve()\n                .bodyToMono(Product[].class);\n    }\n\n    public Mono\u003cProduct\u003e getProductById(int productId) {\n        return webClient.get()\n                .uri(\"/products/{id}\", productId)\n                .retrieve()\n                .bodyToMono(Product.class);\n    }\n}\n```\n\nThe `getProducts()` method uses WebClient to make a GET request to the `/products` endpoint. The `retrieve()` method initiates the request and returns a `ClientResponse` object. The `bodyToMono()` method is then used to deserialize the response body into an array of `Product` objects. Finally, the result is returned as a `Mono\u003cProduct[]\u003e`.\n\nNow we can consume the ProductService and call `getProducts()` endpoint to return the list of products as follows:\n\n```java\nMono\u003cProduct[]\u003e productsMono = productService.getProducts();\nproductsMono.subscribe(\n        products -\u003e {\n            //TODO write your logic to handle list of products repose\n        },\n        error -\u003e {\n            // Handle error cases\n            error.printStackTrace();\n        }\n);\n```\n\nSimilarly. we can call `getProductById()` method to return a product specified by Id.\n\n```java\nMono\u003cProduct\u003e productMono = productService.getProductById(1);\nproductMono.subscribe(\n        product -\u003e {\n            //TODO write your logic to handle product response\n        },\n        error -\u003e {\n            // Handle error cases\n            error.printStackTrace();\n        }\n);\n```\n\n### Consuming POST API in WebClient\n\nNow let us expand the `ProductService` class to add support for the `addProduct()` method. This method makes a POST request to the /products endpoint and sends the product information as the request body.\n\n```java\npublic Mono\u003cProduct\u003e addProduct(Product product) {\n    return webClient.post()\n            .uri(\"/products\")\n            .contentType(MediaType.APPLICATION_JSON)\n            .body(BodyInserters.fromValue(product))\n            .retrieve()\n            .bodyToMono(Product.class);\n}\n```\n\nThe post() method is used to initiate the POST request, and the body() method with BodyInserters.fromValue() is used to set the request body with the provided product object. The `contentType()` method sets the request content type to `application/json` to indicate that the request body is in JSON format.\n\nNow, to consume this new endpoint as follows:\n\n```java\nProduct product = new Product();
1\nproduct.setTitle(\"test product\");\nproduct.setPrice(13.5);\nproduct.setDescription(\"lorem ipsum set\");\nproduct.setImage(\"https://i.pravatar.cc\");\nproduct.setCategory(\"electronic\");\nMono\u003cProduct\u003e addedProductMono = productService.addProduct(product);\naddedProductMono.subscribe(\n        addedProduct -\u003e {\n            //TODO Added product\n        },\n        error -\u003e {\n            // Handle error cases\n            error.printStackTrace();\n        }\n);\n```\n\n### Consuming DELETE API in WebClient\n\nNow to delete a product, add the following `deleteProduct()` method to the ProductService.\n\n```java\npublic Mono\u003cVoid\u003e deleteProduct(int productId) {\n    return webClient.method(HttpMethod.DELETE)\n            .uri(\"/products/{id}\", productId)\n            .retrieve()\n            .bodyToMono(Void.class);\n}\n```\n\nTo consume this new endpoint and delete a product, you can use the ProductService as follows:\n\n```java\nMono\u003cVoid\u003e deletedProductMono = productService.deleteProduct(productId);\ndeletedProductMono.subscribe(\n        response -\u003e {\n            // TODO Product deleted successfully\n        },\n        error -\u003e {\n            // Handle error cases\n            error.printStackTrace();\n        }\n);\n```\n\n## Implement Basic Authentication in WebClient\n\nTo implement basic authentication with WebClient, we need to create a custom interceptor class that implements the `ExchangeFilterFunction` interface. The `ExchangeFilterFunction` interface represents a functional contract for intercepting and modifying the exchange between the WebClient and the remote server during an HTTP request/response cycle.\n\nIt allows applying custom logic such as modifying request headers, logging, adding authentication tokens, modifying the request body, handling retries, or performing custom transformations on the response.\n\nLet us create a `BasicAuthInterceptor` class that implements the `ExchangeFilterFunction` interface.\n\n```java\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.MediaType;\nimport org.springframework.web.reactive.function.client.ClientRequest;\nimport org.springframework.web.reactive.function.client.ClientResponse;\nimport org.springframework.web.reactive.function.client.ExchangeFilterFunction;\nimport org.springframework.web.reactive.function.client.ExchangeFunction;\nimport reactor.core.publisher.Mono;\n\nclass BasicAuthInterceptor implements ExchangeFilterFunction {\n    private final String username;\n    private final String password;\n\n    public BasicAuthenticationInterceptor(String username, String password) {\n        this.username = username;\n        this.password = password;\n    }\n\n    @Override\n    public Mono\u003cClientResponse\u003e filter(ClientRequest request, ExchangeFunction next) {\n        HttpHeaders headers = request.headers();\n        headers.setBasicAuth(username, password);\n        headers.setContentType(MediaType.APPLICATION_JSON);\n        return next.exchange(request);\n    }\n}\n```\n\nHere's an example of how you can configure WebClient to use the Interceptor for doing the basic authentication:\n\n```java\nthis.webClient = WebClient.builder()\n        .baseUrl(\"https://fakestoreapi.com\")\n        .filter(new BasicAuthInterceptor(\"username\", \"password\"))\n        .build();\n```\n\nWith this configuration, WebClient will automatically include the basic authentication credentials in the request headers for all requests made using that WebClient instance.\n\n## Passsing X-API-Key Header in WebClient Request\n\nTo pass an `X-API-Key` header in WebClient requests in Spring Boot, you can use the `header()` method provided by the WebClient's `mutate()` function. Here's an example of how you can include the `X-API-Key` header in WebClient requests:\n\n```java\nWebClient webClient = WebClient.builder()\n        .baseUrl(\"https://fakestoreapi.com\")\n        .build();\n\n return webClient.get()\n        .uri(\"/products\")\n        .header(HttpHeaders.AUTHORIZATION, \"X-API-Key: YOUR_API_KEY\")\n        .retrieve()\n        .bodyToMono(Product[].class);\n```\n"])</script>
1<script>self.__next_f.push([1,"59:Ta5c,"])</script>
1<script>self.__next_f.push([1,"\n### 1. How to check if the user instance is admin Django permissions?\n\nThe `is_superuser` property in the User model designates that this user has all permissions without explicitly assigning them.\n\n```python\nclass UserAdmin(BaseUserAdmin):\n    ...\n    def has_add_permission(self, request, obj=None):\n        return request.user.is_superuser\n\n    def has_delete_permission(self, request, obj=None):\n        return request.user.is_superuser\n```\n\n### 2. How to get the Django admin URL for a model object?\n\nYou can use the URL resolver directly in a template, there's no need to write your filter. E.g.\n\n```html\n{% url 'admin:index' %}\n{% url 'admin:polls_choice_add' %}\n{% url 'admin:polls_choice_change' choice.id %}\n{% url 'admin:polls_choice_changelist' %}\n```\n\nref: [Django official documentation](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls)\n\n### 3. What is a \"slug\" in Django?\n\nA \"slug\" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually. An example:\n\n```xml\n\u003ctitle\u003e The 46 Year Old Virgin \u003c/title\u003e\n\u003ccontent\u003e A silly comedy movie \u003c/content\u003e\n\u003cslug\u003e the-46-year-old-virgin \u003c/slug\u003e\n```\n\nNow let's pretend that we have a Django model such as:\n\n```python\nclass Article(models.Model):\n    title = models.CharField(max_length=100)\n    content = models.TextField(max_length=1000)\n    slug = models.SlugField(max_length=40)\n```\n\nHow would you reference this object with a URL and with a meaningful name? You could for instance use Article. id so the URL would look like this:\n\n```text\nwww.example.com/article/23\n```\n\nOr, you might want to reference the title like this:\n\n```text\nwww.example.com/article/The 46 Year Old Virgin\n```\n\nSince spaces aren't valid in URLs, they must be replaced by %20, which results in:\n\n```text\nwww.example.com/article/The%2046%20Year%20Old%20Virgin\n```\n\nBoth attempts are not resulting in very meaningful, easy-to-read URL. This is better:\n\n```text\nwww.example.com/article/the-46-year-old-virgin\n```\n\nIn this example, the-46-year-old-virgin is a slug: it is created from the title by down-casing all letters, and replacing spaces with hyphens -\n\n### 4. What is a Django middleware, and how is it used?\n\nA Django middleware is a component that sits between the web server and the view function and can perform operations on incoming requests or outgoing responses. Middleware can be used to perform tasks such as authentication, caching, logging, or modifying headers.\n"])</script>
1<script>self.__next_f.push([1,"5a:T1799,"])</script>
1<script>self.__next_f.push([1,"\n### 1. What is Git?\n\nGit is the most popular, open-source, widely used, and an example of a distributed version control system (DVCS) used for handling the development of small and large projects more efficiently and neatly.\n\nIt is most suitable when multiple people are working on projects as a team and is used for tracking the project changes and efficiently supports the collaboration of the development process.\n\nGit is a version control system for tracking changes in computer files and is used to help coordinate work among several people on a project while tracking progress over time. In other words, it’s a tool that facilitates source code management in software development. In case of any unforeseen circumstances, the code can be reverted to any of the previously working versions thereby saving huge efforts.\n\n### 2. What is a Git repository?\n\nA Git repository refers to a place where all the Git files are stored. These files can either be stored on the local repository or on the remote repository.\n\n### 3. How can you initialize a repository in Git?\n\nIf you want to initialize an empty repository to a directory in Git, you need to enter the git init command. After this command, a hidden .git folder will appear.\n\n```bash\ntest$ git init\nhint: Using 'master' as the name for the initial branch. This default branch name\nhint: is subject to change. To configure the initial branch name to use in all\nhint: of your new repositories, which will suppress this warning, call:\nhint:\nhint:   git config --global init.defaultBranch\nhint:\nhint: Names commonly chosen instead of 'master' are 'main', 'trunk' and\nhint: 'development'. The just-created branch can be renamed via this command:\nhint:\nhint:   git branch -m\nInitialized empty Git repository in /Users/npangirahy/Documents/test/.git/\n```\n\n### 4. How is Git different from Subversion (SVN)?\n\n|  |  |\n| --- | --- |\n| GIT | SVN |\n| Git is a distributed decentralized version control system | SVN is a centralized version control system. |\n| Git stores content in the form of metadata. | SVN stored data in the form of files. |\n| The master contains the latest stable release. | In SVN, the trunk directory has the latest stable release |\n| The contents of Git are hashed using the SHA-1 hash algorithm. | SVN doesn?t support hashed contents. |\n\n### 5. Name a few Git commands with their function.\n\n-   Git config - Configure the username and email address\n-   Git add - Add one or more files to the staging area\n-   Git diff - View the changes made to the file\n-   Git init - Initialize an empty Git repository\n-   Git commit - Commit changes to the head but not to the remote repository\n\n### 6. Difference between git fetch and git pull.\n\n| Git Fetch | Git Pull |\n| --- | --- |\n| The Git fetch command only downloads new data from a remote repository. | Git pull updates the current HEAD branch with the latest changes from the remote server. |\n| It does not integrate any of these new data into your working files. | Downloads new data and integrate it with the current working files. |\n| Command - git fetch origingit fetch --all | Tries to merge remote changes with your local ones.Command - git pull origin master |\n\n### 7. What do you understand about the Git merge conflict?\n\nA Git merge conflict is an event that occurs when Git is unable to resolve the differences in code between the two commits automatically.\n\nGit is capable of automatically merging the changes only if the commits are on different lines or branches.\n\n### 8. What is the process to revert a commit that has already been pushed and made public?\n\nThere are two processes through which you can revert a commit: Remove or fix the bad file in a new commit and push it to the remote repository. Then commit it to the remote repository using:\n\n```bash\ngit commit –m “commit message”\n```\n\nCreate a new commit to undo all the changes that were made in the bad commit. Use the following command:\n\n```bash\ngit revert\n```\n\n### 9. What is Git stash?\n\nLet’s say you're developing a module for software and you want to switch branches to work on something else. The issue is you don’t want to make commits in uncompleted work, so you just want to get back to this point later. The solution here is the Git stash.\n\nGit stash takes your modified tracked files and saves them on a stack of unfinished changes that you can reapply at any time. To go back to the work you can use the stash pop.\n\n### 10. What is the difference between fork, branch, and clone?\n\n**Fork** The fork is the process when a copy of the repository is made. It's usually experimentation in the project without affecting the original project. They’re used to advise changes or take inspiration from someone else’s project.\n\n**Branch** Git branches refer to individual projects within a git repository. If there are several branches in a repository, then each branch can have entirely different files and folders.\n\n**Clone** Git clone refers to creating a clone or a copy of an existing git repository in a new directory. Cloning automatically creates a connection that points back to the original repository, which makes it very easy to interact with the central repository.\n\n### 11. What is git cherry-pick??\n\nThe command `git cherry-pick` enables you to pick up commits from a branch within a repository and apply it to another branch. This command is useful to undo changes when any commit is accidentally made to the wrong branch. Then, you can switch to the correct branch and use this command to cherry-pick the commit.\n\n### 12. What is the command used to delete a branch?\n\n-   To delete a branch we can simply use the command `git branch –d [head]`.\n-   To delete a branch locally, we can simply run the command: `git branch -d \u003clocal_branch_name\u003e`\
1n-   To delete a branch remotely, run the command: `git push origin --delete \u003cremote_branch_name\u003e`\n-   Deleting a branching scenario occurs for multiple reasons. One such reason is to get rid of the feature branches once it has been merged into the development branch.\n"])</script>
1<script>self.__next_f.push([1,"5b:T3528,"])</script>
1<script>self.__next_f.push([1,"\n### 1. What are the key differences between a service and IntentService in Android?\n\n| Service | IntentService |\n| --- | --- |\n| Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must create a new thread with in Service | IntentService can be used in long running tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. |\n| Service can be started using startService() method | IntentService can be started using the startService() method and it triggers onHandleIntent() method. |\n| Service can be triggered from any thread | IntentService must be triggered from Main Thread |\n| Service runs in background but it runs on the Main Thread of the application. | IntentService runs on a separate worker thread |\n| The Service may block the Main Thread of the application. | The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially. |\n| You must call stopSelf() or stopService() to stop a service once your its job is done. | IntentService stops itself when it finishes its job so you never have to call stopSelf() |\n\n### 2. What is an alarm service and explain the purpose with real-world examples.\n\nAlarm service is used to run tasks periodically at a given interval. You can design applications like Alarm, birthday reminder, or AlarmManager can be used to initiate long-running operations such as syncing data from the server once a day. Once an Alarm is Started, this will execute until it is stopped explicitly or until the device reboots.\n\n### 3. How to pass data to an IntentService?\n\nYou can pass data as a bundle to IntentService before you start.\n\n```java\nIntent intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class);\n\n/* Send optional extras to Download IntentService */\nintent.putExtra(\"url\", url);\nintent.putExtra(\"receiver\", mReceiver);\nintent.putExtra(\"requestId\", 101);\n\nstartService(intent);\n```\n\n### 4. How to define a service in an Android manifest file?\n\nAll the services used in the app need to be registered in the application Manifest. Services are declared as shown below\n\n```xml\n\u003c!--Service declared in manifest --\u003e\n\u003cservice android:name=\".HelloService\"\nandroid:exported=\"false\"/\u003e\n```\n\n### 5. What are the different clock types supported for AlarmService?\n\nAndroid supports two clock types for alarm service. Once is elapsed in real time and the other is a real-time clock (RTC). Elapsed real time uses the time since the device last booted. Real-time clock (RTC) uses UTC for alarm service clock. RTC is most commonly used for setting alarm services in Android.\n\n### 6. What is the difference between bound and unbounded service in Android?\n\n1.  **Bound Service -** Service which calls indefinitely in between activities. An Android component may bind itself to a Service using bindservice (). A bound service would run as long as the other application components are bound to it. As soon as they unbind, the service destroys itself.\n2.  **Unbound Service -** Service which calls at the life span of calling activity. In this case, an application component starts the service, and it would continue to run in the background, even if the original component that initiated it is destroyed. For instance, when started, a service would continue to play music in the background indefinitely.\n\n### 7. Explain service lifecycle methods in Android.\n\nA service can be run by the system, If someone calls Context.startService() or bindService() method.\n\n1.  **onStartCommand()** - This method is called when the service is started by calling startService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). If you are defining your service as, a bounded service then you don't need to implement this method.\n2.  **onBind()** 
1- You need to override this method, only if you are defining your service as a bounded service. This method is called when another component wants to bind with the service by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don't want to allow binding, then you should return null.\n3.  **onCreate()**\\- This method is called while the service is first created. Here all the service initialization is done. This method is never called again.\n4.  **onDestroy()** - The system calls this method when the service is no longer used and is being destroyed. This method is used to, clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.\n\n### 8. What is the purpose of Service in Android?\n\nAndroid Service is used to perform long-running jobs off the UI thread. Typical long-running tasks can be periodic downloading of data from the internet, saving multiple records into the database, performing file I/O, fetching your phone contacts list, etc. For such long-running tasks, Service is used to avoid UI lags and make the user experience better.\n\n### 9. How to Pass Data Between Activities in Android?\n\nWe can pass values between the activities, by using Bundles. Use the below code to send data from ActivityA\n\n```java\nString name=\"Javatechig\";\nString url=\"http://stacktips.com\"\nIntent intent=new Intent(ActivityA.this, ActivityB.class);\nintent.putExtra(\"name\", name);\nintent.putExtra(\"url\", url);\nstartActivity(intent);\n```\n\nNow, you can retrieve the data in ActivityB using the below code\n\n```java\nBundle bundle = new Bundle();\nbundle = getIntent().getExtras();\nString name = bundle.getString(\"name\");\nString url = bundle.getString(\"url\");\n```\n\n### 10. How to display Android Toast?\n\nToast is a notification message that pops up, displays a certain amount of time, and automatically fades in and out, most people just use it for debugging purposes. Below are the code snippets to create a Toast message\n\n```java\n//display in a short period of time\nToast.makeText(getApplicationContext(), \"msg msg\", Toast.LENGTH_SHORT).show();\n\n//display over a long period of time\nToast.makeText(getApplicationContext(), \"msg msg\", Toast.LENGTH_LONG).show();\n```\n\n[Android custom toast example](http://stacktips.com/android/android-toast-example/)\n\n### 11. How to Display HTML in Android TextView?\n\nIn Android, there is a lovely class `android.text.HTML` that processes HTML strings into displayable styled text. Currently android doesn't support all HTML tags.\n\n`Html.formHtml()` method takes an `Html.TagHandler` and an `Html.ImageGetter` as arguments as well as the text to parse. We can parse null as for the `Html.TagHandler` but you'd need to implement your own `Html.ImageGetter` as there isn't a default implementation. The Html.ImageGetter needs to run synchronously and if you're downloading images from the web you?ll probably want to do that asynchronously.\n\nBut in my example, I am using the images from resources to make my ImageGetter implementation simpler.\n\n```java\nString htmlText = \"\u003chtml\u003e\u003cbody\u003e....\u003c/body\u003e\u003c/html\u003e\";\nTextView htmlTextView = (TextView)findViewById(R.id.html_text);\nhtmlTextView.setText(Html.fromHtml(htmlText, new ImageGetter(), null));\n```\n\n### 12. How to open a link in Android Browser?\n\n```java\nIntent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http://stacktips.com\"));\nstartActivity(browserIntent);
1\n```\n\n### 13. When is the onResume() method called in the activity lifecycle?\n\nThe onResume() method is an activity lifecycle method. This is called when the activity comes to the foreground. You can override this method in your activity to execute code when the activity is started, restarted or comes to the foreground.\n\n### 14. How to launch an activity in your application?\n\nFor launching an activity, we need to create an explicit intent that defines the activity that we wish to start. In the below code snippet, the first parameter to the Intent constructor is the current activity context and the second parameter is your new activity `class.startActivity()` method can be called on Activity context.\n\n```java\nIntent intent = new Intent(this, SecondActivity.class);\nstartActivity(intent);\n```\n\nIf you want to start an activity from a fragment\n\n```java\nIntent intent = new Intent(getActivity(), SecondActivity.class);\ngetActivity().startActivity(intent);\n```\n\n### 15. How to define an Activity as a launcher activity in the application Manifest file?\n\nAll the activities used in the application should be defined in the application manifest file. For the launcher activity, you need to define the intent filter as shown in the below code snippets.\n\n```xml\n\u003cactivity android:name=\".MyActivity\"\n          android:label=\"@string/app_name\"\u003e\n    \u003cintent-filter\u003e\n        \u003caction android:name=\"android.intent.action.MAIN\" /\u003e\n        \u003ccategory android:name=\"android.intent.category.LAUNCHER\" /\u003e\n    \u003c/intent-filter\u003e\n\u003c/activity\u003e\n```\n\n### 16. What is an ANR? What measures you can take to avoid application ANR?\n\nANR is short for Application Not Responding. Android systems show this dialog if the application is performing too much of a task on the main thread and has been unresponsive for a long period.\n\n**Measures to avoid application ANR:** ANR in the application is annoying to the users. It can be caused due to various reasons. Below are some of the tips to avoid ANR\n\n-   Perform all your long-running network or database operations in a separate thread\n-   If you have too much of background tasks, then take it off the UI thread. You may use IntentService\n-   The server not responding for a longer period can be guilty of ANR. To avoid always defining HTTP time out for all your web service calls.\n-   Be watchful of infinite loops during your complex calculations\n\n### 17. How to share text using android share Intent?\n\nShare intent is an easy and convenient way of sharing the content of your application with other apps.\n\n```java\nIntent sendIntent = new Intent();\nsendIntent.setAction(Intent.ACTION_SEND);\nsendIntent.putExtra(Intent.EXTRA_TEXT, \"This is my text to send.\");\nsendIntent.setType(\"text/plain\");\nstartActivity(sendIntent);\n```\n\n### 18. What is the use of WebView in Android?\n\nA WebView is an Android UI component that displays webpages. It can either display a remote webpage or can also load static HTML data. This encompasses the functionality of a browser that can be integrated into an application.\n\nWebView uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backwards through a history, zoom in and out, etc.\n\n### 19. Define different kinds of context in android\n\nContext defines the current state of the application or object. Context provides access to things such as creating new activity instances, accessing databases, starting a service, etc. You can get the context by invoking `getApplicationContext()`, `getContext()`, `getBaseContext()` or `this` when in the activity class.\n\n```java\n//Creating ui instance\nImageButton button = new ImageButton(getContext());\n\n//creating adapter\nListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);\n\n//querying content provider\ngetApplicationContext().getContentResolver().query(uri, ...);\n\n//start activity. Here this means activity context\nIntent intent = new Intent(this, SecondActivity.class);\n```\n\n### 20. What are the different data storage options available in Android?\n\nAndroid offers several different options for data persistence.\n\n1.  **Shared Preferences** - Used to store private primitive data in key-value pairs. This sometimes gets limited as it offers only key-value pairs. You cannot save your own Java types.\n2.  **Internal Storage** - Used to store private data on the device's memory\n3.  **External Storage** - Used to store public data on the shared external storage\n4.  **SQLite Databases** - Used to store structured data in a private database. You can define many tables and can store data like other RDBMS.\n\n### 21. How to send SMS in Android?\n\nYou may send SMS either using SmsManager or by invoking the Built-in SMS application\n\n**Sending SMS using SmsManager API**\n\n```java\nSmsManager smsManager = SmsManager.getDefault();\nsmsManager.sendTextMessage(\"\", null, \"\u003c message body\u003e\", null, null);\n```\n\nSmsManager requires **SMS\\_SEND** permission in your Android manifest.\n\n**Sending SMS by invoking the Built-in SMS application**\n\n```java\nIntent sendIntent = new Intent(Intent.ACTION_VIEW);\nsendIntent.putExtra(\"sms_body\", ?\");\nsendIntent.setType(\"vnd.android-dir/mms-sms\");\nstartActivity(sendIntent);\n```\n\n### 22. How to Make a Call in Android?\n\n```java\nIntent callIntent = new Intent(Intent.ACTION_CALL);\ncallIntent.setData(Uri.parse(\"tel:03777788\"));\nstartActivity(callIntent);\n```\n\n### 23. How to send Email from Android application?\n\nAndroid Intent is a handy way to send Email using your app.\n\n```java\nString to = toEmail.getText().toString();\nString subject = emailSubject.getText().toString();\nString message = emailBody.getText().toString();\nIntent email = new Intent(Intent.ACTION_SEND);\nemail.putExtra(Intent.EXTRA_EMAIL, new String[] { to });\nemail.putExtra(Intent.EXTRA_SUBJECT, subject);\nemail.putExtra(Intent.EXTRA_TEXT, message);\n\n// need this to prompt email client-only\nemail.setType(\"message/rfc822\");\nstartActivity(Intent.createChooser(email, \"Choose an Email client\"));\n```\n"])</script>
1<script>self.__next_f.push([1,"5c:T87a,"])</script>
1<script>self.__next_f.push([1,"\nAccessing related objects through the ORM can sometimes lead to performance bottlenecks, especially when dealing with large datasets or complex relationships. One common issue is the \"N+1 queries\" problem, where a query is executed for each related object, leading to a significant increase in database queries and slow performance.\n\nTo avoid this problem in Django, we can use `select_related` and `prefetch_related` are methods that used to optimize the database queries when dealing with related objects.\n\n## Using select\\_related method\n\nThe `select_related` is used to retrieve related objects using a single SQL query. It works by following foreign key relationships and joining the related objects into a single query. This can be useful when you need to access related objects in a loop or when accessing a single related object in a template.\n\nFor example, consider the following code:\n\n```python\n# Retrieve all books and their authors using select_related\nbooks = Book.objects.select_related('author')\nfor book in books:\n    print(book.title, book.author.name)\n```\n\nIn this example, `select_related` is used to retrieve all books and their authors in a single query.\n\n### Using prefetch\\_related method\n\nOn the other hand, `prefetch_related` is used to retrieve related objects using multiple queries. It works by first retrieving the main queryset, and then retrieving the related objects in a separate query. This can be useful when you need to access many related objects, or when you want to avoid unnecessary database joins.\n\nFor example, consider the following code:\n\n```python\n# Retrieve all books and their reviews using prefetch_related\nbooks = Book.objects.prefetch_related('reviews')\nfor book in books:\n    print(book.title)\n    for review in book.reviews.all():\n        print(review.body)\n```\n\nIn this example, `prefetch_related` is used to retrieve all books and their reviews in two separate queries.\n\nIn general, you should use `select_related` when accessing a single related object, or when accessing related objects in a loop.\n\nUse `prefetch_related` when accessing many related objects or when you want to avoid unnecessary database joins.\n"])</script>
1<script>self.__next_f.push([1,"5d:T1470,"])</script>
1<script>self.__next_f.push([1,"\nForms are the key component of building any web applications. Forms provide an easy and efficient way to handle user input and process form data.\n\nIn Django a form is a Python class that defines the fields of a form and their behavior, including how data is validated and processed. Django provide a convenient way to render forms in HTML templates. Form fields can be customized with labels, help text, and error messages. They can also be styled with CSS to match the look and feel of the web application.\n\nDjango provides two main types of forms:\n\n-   Standard forms\n-   Model forms.\n\nStandard forms are used for creating custom forms that are not tied to any specific database model.\n\nModel forms, on the other hand, are used for creating forms that are tied to a specific database model. Model forms automatically generate form fields based on the fields of the model, which can save a lot of time and effort in creating and managing forms.\n\n## Handling Standard forms in Django\n\nHere is a basic example of how to handle form submissions in Django:\n\nFirst, let us define a Django form in `forms.py` file.\n\n```python\nfrom django import forms\n\nclass ContactForm(forms.Form):\n    name = forms.CharField(max_length=100)\n    email = forms.EmailField()\n    message = forms.CharField(widget=forms.Textarea)\n```\n\nSecondly, define a view that renders the form and handles form submissions in `views.py`\n\n```python\nfrom django.shortcuts import render\nfrom .forms import ContactForm\n\ndef contact_form_view(request):\n    if request.method == 'POST':\n        form = ContactForm(request.POST)\n        if form.is_valid():\n            name = form.cleaned_data['name']\n            email = form.cleaned_data['email']\n            message = form.cleaned_data['message']\n            return render(request, 'success_page.html')\n    else:\n        form = ContactForm()\n    return render(request, 'contact_page.html', {'form': form})\n```\n\nIf the request method is not `POST`, we create a new instance of the `ContactForm` class and render the form using a template `contact_page.html`. We pass the form object to the template context using a dictionary.\n\nLastly, define a template `contact_page.html` that renders the form\n\n```html\n\u003cform method=\"post\"\u003e\n    {% csrf_token %}\n    {{ form.as_p }}\n    \u003cbutton type=\"submit\"\u003eSubmit\u003c/button\u003e\n\u003c/form\u003e\n```\n\nThe `form.as_p` method outputs each form field as a separate HTML paragraph element. We also include a CSRF token using the `{% csrf_token %}` template tag and a submit button to submit the form.\n\nWhen the user submits the form, the data is sent to the server using a `POST` request. The view code above will then validate and process the data, and return an appropriate response to the user.\n\n## Handling Model Forms in Django\n\nCreating Model Forms in Django is pretty straightforward.\n\n### Define Model\n\nFirst we need to define a model class. A model class represents the database table, that the form with interact with.\n\n```python\nfrom django.db import models\n\nclass Person(models.Model):\n    name = models.CharField(max_length=100)\n    email = models.EmailField()\n```\n\n### Create a form class:\n\nNext, create a form class that is based on your model. This can be done by using Django's built-in ModelForm class.\n\nThe ModelForm class automatically creates form fields based on the fields in your model.\n\n```python\nfrom django import forms\nfrom .models import Person\n\nclass PersonForm(forms.ModelForm):\n    class Meta:\n        model = Person\n        fields = ('name', 'email')\n        labels = {\n            'name': 'Name',\n            'email': 'Email Address',\n        }\n        help_texts = {\n            'name': 'Enter your name',\n            'email': 'Enter your email address',\n        }\n```\n\nIn this example, we have defined a `Person` model with two fields: `name` and `email`. Then, we have created a `PersonForm` form class that is based on the `Person` model.\n\nThe form fields can be customized by specifying additional attributes such as labels, help texts, and validation rules.\n\n### Define Form template\n\nLastly, define a template `person_form.html` that renders the form\n\n```html\n{% extends \"base.html\" %}\n\n{% block content %}\n  \u003ch1\u003eCreate a new person\u003c/h1\u003e\n  \u003cform method=\"post\"\u003e\n    {% csrf_token %}\n    {{ form.as_p }}\n    \u003cinput type=\"submit\" value=\"Save\"\u003e\n  \u003c/form\u003e\n{% endblock %}\n```\n\n### Create the form in a view:\n\nCreate an instance of the form class in a view function that is responsible for rendering the form to the user.\n\n```python\nfrom django.shortcuts import render, redirect\nfrom .forms import PersonForm\n\ndef create_person(request):\n    if request.method == 'POST':\n        form = PersonForm(request.POST)\n        if form.is_valid():\n            person = form.save()\n            return redirect('person_detail', pk=person.pk)\n    else:\n        form = PersonForm()\n    return render(request, 'person_form.html', {'form': form})\n\ndef person_detail(request, pk):\n    person = Person.objects.get(pk=pk)\n    return render(request, 'person_detail.html', {'person': person})\n```\n\nWhen the user submits the form, the `create_person` view function will validate the form data and save it to the database. If the data is valid, we redirect the user to the `person_detail` view.\n"])</script>
1<script>self.__next_f.push([1,"5e:T21c7,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we will discuss how to connect two different MongoDB databases from your Spring boot application. This article assumes you already have MongoDB integrated into your project, hence this post skips the basics.\n\nTo connect to multiple MongoDB databases, we need to use `MongoClientFactoryBean` to create multiple `MongoClient` instances that connects to two different databases.\n\nFirst let us add two set of MongoDB connection properties to your `application.properties` file corresponding to each DB.\n\n```properties\n# Primary MongoDB configs\nspring.data.mongodb.primary.host=localhost\nspring.data.mongodb.primary.port=27017\nspring.data.mongodb.primary.username=root\nspring.data.mongodb.primary.password=admin\nspring.data.mongodb.primary.database=movies_db\nspring.data.mongodb.primary.authentication-database=admin\n\n# Secondary MongoDB configs\nspring.data.mongodb.secondary.host=localhost\nspring.data.mongodb.secondary.port=27018\nspring.data.mongodb.secondary.username=root\nspring.data.mongodb.secondary.password=admin\nspring.data.mongodb.secondary.database=movies_db2\nspring.data.mongodb.secondary.authentication-database=admin\n```\n\n### MongoDB Config\n\nNext, we will bind these configuration properties property to the `MongoProperties` object using the `@ConfigurationProperties` annotation.\n\nAnd then, we will use these properties to create a `MongoClient` bean. The `MongoClient` is the entry point to the MongoDB driver API.\n\nWe then have to register a `MongoClient` via `MongoDatabaseFactory`. The `MongoDatabaseFactory` is used to bootstrap the connectivity to the database. Finally we can use the `MongoDatabaseFactory` instance to configure the `MongoTemplate` .\n\nThe `MongoTemplate` will be used for performing all Mongo DB CRUD operations including BSON queries or updates.\n\n**Primary MongoDB Config:**\n\n```java\n@Configuration\n@EnableMongoRepositories(basePackages = \"com.stacktips.app.repository.primary\",\n        mongoTemplateRef = \"primaryMongoTemplate\")\npublic class PrimaryMongoConfig {\n\n    @Primary\n    @Bean(\"primaryMongoProperties\")\n    @ConfigurationProperties(prefix = \"spring.data.mongodb.primary\")\n    public MongoProperties primaryMongoProperties() {\n        return new MongoProperties();\n    }\n\n    @Primary\n    @Bean(name = \"primaryMongoClient\")\n    public MongoClient primaryMongoClient(@Qualifier(\"primaryMongoProperties\") MongoProperties mongoProperties) {\n\n        ServerAddress serverAddress = new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort());\n        MongoClientSettings settings = MongoClientSettings.builder()\n                .applyToClusterSettings(builder -\u003e\n                        builder.hosts(List.of(serverAddress)))\n                .credential(MongoCredential.createCredential(\n                        mongoProperties.getUsername(),\n                        mongoProperties.getAuthenticationDatabase(),\n                        mongoProperties.getPassword()))\n                .build();\n        return MongoClients.create(settings);\n    }\n\n    @Primary\n    @Bean(name = \"primaryMongoFactory\")\n    public MongoDatabaseFactory mongoDatabaseFactory(\n            @Qualifier(\"primaryMongoClient\") MongoClient mongoClient,\n            @Qualifier(\"primaryMongoProperties\") MongoProperties mongoProperties) {\n        return new SimpleMongoClientDatabaseFactory(mongoClient, mongoProperties.getDatabase());\n    }\n\n    @Primary\n    @Bean(name = \"primaryMongoTemplate\")\n    public MongoTemplate mongoTemplate(\n            @Qualifier(\"primaryMongoFactory\") MongoDatabaseFactory mongoDatabaseFactory) {\n        return new MongoTemplate(mongoDatabaseFactory);\n    }\n}\n```\n\n**Important Notes:**\n\n-   The `@EnableMongoRepositories` is the key here. This will scan all mongo repository from specific package as defined. All repositories that will be used to\n-   The `mongoTemplateRef` is used to configure the name of the `MongoTemplate` bean to be used with the repositories detected.\n-   The `@Primary` annotation indicates that the a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.\n\n**Secondary MongoDB Config:**\n\nThe secondary mongo db config is similar to the primary, except for the `@Primary` annotation and it will read properties with `spring.data.mongodb.secondary` prefix.\n\n```java\n@Configuration\n@EnableMongoRepositories(basePackages = \"com.stacktips.app.repository.secondary\",\n        mongoTemplateRef = \"secondaryMongoTemplate\")\npublic class SecondaryMongoConfig {\n\n    @Bean(\"secondaryMongoProperties\")\n    @ConfigurationProperties(prefix = \"spring.data.mongodb.secondary\")\n    public MongoProperties secondaryMongoProperties() {\n        return new MongoProperties();\n    }\n\n    @Bean(name = \"secondaryMongoClient\")\n    public MongoCl
1ient secondaryMongoClient(\n            @Qualifier(\"secondaryMongoProperties\") MongoProperties mongoProperties) {\n\n        ServerAddress serverAddress = new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort());\n        MongoClientSettings settings = MongoClientSettings.builder()\n                .applyToClusterSettings(builder -\u003e builder.hosts(List.of(serverAddress)))\n                .credential(MongoCredential.createCredential(\n                        mongoProperties.getUsername(),\n                        mongoProperties.getAuthenticationDatabase(),\n                        mongoProperties.getPassword()))\n                .build();\n        return MongoClients.create(settings);\n    }\n\n    @Bean(name = \"secondaryMongoFactory\")\n    public MongoDatabaseFactory mongoDatabaseFactory(\n            @Qualifier(\"secondaryMongoClient\") MongoClient mongoClient,\n            @Qualifier(\"secondaryMongoProperties\") MongoProperties mongoProperties) {\n        return new SimpleMongoClientDatabaseFactory(mongoClient, mongoProperties.getDatabase());\n    }\n\n    @Bean(name = \"secondaryMongoTemplate\")\n    public MongoTemplate mongoTemplate(\n            @Qualifier(\"secondaryMongoFactory\") MongoDatabaseFactory mongoDatabaseFactory) {\n        return new MongoTemplate(mongoDatabaseFactory);\n    }\n}\n```\n\nIn the above example, we're defining two `MongoTemplate` beans, one for each database. We're passing in the `MongoClient` instances created by the `MongoClientFactoryBean` beans, along with the corresponding database name from the `MongoProperties` beans.\n\n### Mongo Repositories\n\nIn this example, we will created a two repositories to perform CRUD operation. Note that they reside in two different packages, i.e. `com.stacktips.app.repository.primary` and `com.stacktips.app.repository.secondary`.\n\nHere we are using extending `MongoRepository` to perform the CRUD operations, but the same will work for custom repository that uses `MongoTemplate`.\n\n```java\npackage com.stacktips.app.repository.primary;\n\nimport com.stacktips.app.model.Movie;\nimport org.springframework.data.mongodb.repository.MongoRepository;\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic interface PrimaryMovieRepository extends MongoRepository\u003cMovie, String\u003e {\n\n}\n```\n\nSecondary Mongo Repository:\n\n```java\npackage com.stacktips.app.repository.secondary;\n\nimport com.stacktips.app.model.Movie;\nimport org.springframework.data.mongodb.repository.MongoRepository;\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic interface SecondaryMovieRepository extends MongoRepository\u003cMovie, String\u003e {\n\n}\n```\n\nNo that we have everything, let us now inject these repositories into our service:\n\n```java\n@Service\npublic class MovieService {\n\n    private final PrimaryMovieRepository primaryMovieRepository;\n    private final SecondaryMovieRepository secondaryMovieRepository;\n\n    public MovieService(\n            PrimaryMovieRepository primaryMovieRepository,\n            SecondaryMovieRepository secondaryMovieRepository) {\n        this.primaryMovieRepository = primaryMovieRepository;\n        this.secondaryMovieRepository = secondaryMovieRepository;\n    }\n\n    public Movie savePrimary(Movie movie) {\n        return primaryMovieRepository.save(movie);\n    }\n\n    public List\u003cMovie\u003e findAllPrimary() {\n        return primaryMovieRepository.findAll();\n    }\n\n    public Movie saveSecondary(Movie movie) {\n        return secondaryMovieRepository.save(movie);\n    }\n\n    public List\u003cMovie\u003e findAllSecondary() {\n        return secondaryMovieRepository.findAll();\n    }\n}\n```\n\nThat's it! With the above configuration, you should be able to connect to multiple MongoDB Databases from your Spring Boot application.\n\nFor complete project source code checkout of the download link.\n"])</script>
1<script>self.__next_f.push([1,"5f:Ta93,"])</script>
1<script>self.__next_f.push([1,"\nApache Kafka and ActiveMQ are both open-source message brokers, but they have some key differences in terms of their design and intended use cases.\n\nKafka is a distributed streaming platform that is designed for handling large streams of data in real-time. It is often used for processing real-time data streams, such as log data, sensor data, and financial data. Kafka is highly scalable and can handle millions of events per second.\n\nActiveMQ, on the other hand, is a message broker that supports a wide range of messaging protocols including JMS, AMQP, and MQTT. It is designed for enterprise use cases such as integration of distributed systems, event-driven architectures, and service-oriented architectures. It has a more traditional message broker architecture, which supports both point-to-point and publish-subscribe messaging patterns.\n\n1.  **Scalability:** Kafka is designed to handle high throughput, low latency, and high scalability. It uses a publish-subscribe model and is built on a distributed architecture, allowing it to handle large amounts of data and handle high levels of concurrency. ActiveMQ, on the other hand, is designed for more traditional messaging scenarios and may not be as well suited for extremely high scalability.\n    \n2.  **Durability:** Kafka's messages are written to disk and replicated across multiple nodes, providing a high level of durability in case of node failures. ActiveMQ also provides a high level of durability, but it may not be as robust as Kafka in certain scenarios.\n    \n3.  **Performance:** Kafka has been designed for very high performance and can handle millions of messages per second. ActiveMQ also provides good performance, but it may not be as fast as Kafka in certain scenarios.\n    \n4.  **Latency:** Kafka has a lower latency than ActiveMQ as it uses a zero-copy design and a memory-mapped file system. ActiveMQ's latency is higher as it requires message to be copied between different layers of the system.\n    \n5.  **Use cases:** Kafka is often used in big data and streaming scenarios, such as real-time data pipelines and event-driven architectures. ActiveMQ is more commonly used in traditional messaging scenarios, such as enterprise application integration and message-oriented middleware.\n    \n6.  **Partitioning:** Kafka supports partitioning of messages across multiple servers which allows it to scale horizontally. ActiveMQ does not have built-in support for partitioning.\n    \n\nIn general, Kafka is often considered to be a better choice for large-scale, high-performance, and real-time streaming scenarios, while ActiveMQ is more appropriate for traditional message driven architecture integration in enterprise systems..\n"])</script>
1<script>self.__next_f.push([1,"60:T10da,"])</script>
1<script>self.__next_f.push([1,"\nMongoDB is a cross-platform document-oriented database program. It is classified as a NoSQL database, which means that it does not use the traditional SQL relational database model. Instead, MongoDB stores data in flexible, JSON-like documents, which can have fields that hold values of different data types.\n\nThe key advantages of using MongoDB are:\n\n1.  **Scalability:** MongoDB can be easily scaled horizontally by adding more nodes to a replica set or sharded cluster, which enables it to handle increasing amounts of data and read/write loads.\n\n2.  **Flexibility:** MongoDB's document data model allows you to store data in a flexible, JSON-like format, which makes it easier to change the structure of your data as your application evolves.\n\n3.  **Performance:** MongoDB's use of indexing, sharding, and in-memory storage options can significantly improve the performance of your applications compared to traditional relational databases.\n\n4.  **Easy to use:** MongoDB provides a simple and straightforward API for inserting, updating, and retrieving data, making it easier for developers to work with compared to traditional relational databases.\n\n5.  **High availability:** MongoDB provides built-in high availability features, such as replica sets and auto-electing primary nodes, which can help ensure that your data is always available even in the event of a node failure.\n\n6.  **Agile development:** MongoDB's flexible data model and easy-to-use API can help speed up the development process and reduce the time and effort required to build complex applications.\n\n7.  **Cost-effective:** MongoDB is an open-source software, which means that you can use it for free. Additionally, it's scalable and flexible architecture can help reduce the costs associated with managing and storing data.\n\nOverall, MongoDB is a highly flexible and scalable NoSQL database that provides a number of advantages over traditional relational databases, making it an excellent choice for a wide range of applications and use cases.\n\n## Spring Boot CRUD with MongoDB\n\nHere is an example of a simple Spring Boot application that performs CRUD operations on a MongoDB database:\n\n### Adding MongoDB Spring Boot Dependency\n\nStart by creating a new Spring Boot project and adding the following dependencies to your `**pom.xml**` file:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-data-mongodb\u003c/artifactId\u003e\n\u003c/dependency\u003e\n```\n\n### MongoDB Connection Properties\n\nIn application.properties file add the following properties for mongodb connection\n\n```properties\nspring.data.mongodb.uri=mongodb://\u003chost\u003e:\u003cport\u003e/\u003cdatabase\u003e\nspring.data.mongodb.username=\u003cusername\u003e\nspring.data.mongodb.password=\u003cpassword\u003e\n```\n\n### Data Model Class Declaration\n\nCreate a model class, for example `**Person**` which will be mapped to a MongoDB collection. This class should have fields that correspond to the fields in the MongoDB document, as well as appropriate getters and setters.\n\n```java\n@Document(collection = \"people\")\npublic class Person {\n    @Id\n    private String id;\n    private String name;\n    private int age;\n\n    //getters and setters\n}\n```\n\n### Mongo Repository Interface\n\nCreate a `**MongoRepository**` interface to perform CRUD operations on the `**Person**` class.\n\n```java\npublic interface PersonRepository extends MongoRepository\u003cPerson, String\u003e {\n\n}\n```\n\n### Using Mongo Repository From Services\n\nIn your application main class, autowire the `**PersonRepository**` and use it to perform CRUD operations. For example:\n\n```java\n@Service\nclass PersonService {\n\n    @Autowired\n    private PersonRepository repository;\n\n    public void addPerson(Person person) {\n        repository.save(person);\n    }\n\n    public List\u003cPerson\u003e getAllPeople() {\n        return repository.findAll();\n    }\n}\n```\n\nThis is just an example, and you will likely need to add more functionality to your application depending on your specific requirements.\n\nPlease note that this is just a starting point and you should consult the official Spring Boot and MongoDB documentation for more information on how to properly implement your application.\n\n## References\n\nSpring Boot MongoDB References – [MongoDB Reference](https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#reference)\n"])</script>
1<script>self.__next_f.push([1,"61:Tef3,"])</script>
1<script>self.__next_f.push([1,"\nYou have two choices when it comes to installing Java. You either use the Oracle JDK or OpenJDK. Oracle JDK offers all the features of Open JDK, plus some proprietary features and commercial support from Oracle.\n\nOpen JDK is the open source version of Java and it is free to use for both personal and commercial projects.\n\nThere are many different distributions of OpenJDK available, some of the popular distributions are Amazon Corretto, Microsoft JDK, Azul Zulu, and Red Hat OpenJDK.\n\nIn this article, we show you how to install Java on Mac using **SDKMan** and **Homebrew** and using windows installer.\n\n## Install Java Using SDKMan\n\nSDKMan is a command line utility used for managing multiple versions of SDKs. This works for MacOS and Linux, Windows WSL.  SDKMan simplifies the installation, management, and switching between different versions of Java SDK effortlessly.\n\nTo get the list of available java SDK's using SDKMan, use\n\n```bash\nsdk list java\n```\n\nThis will return a list of all available Java versions\n\n![](/media/summernote/install_java_in_mac_using_homebrew.png)  \n\nYou can filter a specific Java version using \\`grep\\` command.  \n\n```bash\nsdk list java | grep 17\n```\n\nNow to install a specific version, you need to use the distribution identifier\n\n```bash\nsdk install java 21-amzn\n```\n\nTo check the list of installed Java versions\n\n```bash\nsdk list java | grep installed\n```\n\nUse specific versions of Java\n\n```bash\nsdk use java 21-amzn\n```\n\n## Install Java in Windows OS\n\nFor instructions on how to install using the graphical `PKG` and `MSI` installers, or through package managers `WinGet`, `Homebrew`, `apt`, and `yum`, see the [Install](https://learn.microsoft.com/en-us/java/openjdk/install) page.\n\nTo ensure that Java is installed correctly, open a Command Prompt or PowerShell window and enter the following command.\n\n```bash\njava -version\n```\n\n## Install Java using Homebrew\n\n-   Install and upgrade [Homebrew](https://brew.sh/).\n\n-   Type `brew search openjdk` to find all available Java-related formulas.\n\n```bash\n$ brew search openjdk\n==\u003e Formulae\nopenjdk ✔           openjdk@11          openjdk@17 ✔        openjdk@8\n\n==\u003e Casks\nadoptopenjdk       homebrew/cask-versions/adoptopenjdk8\nmicrosoft-openjdk  homebrew/cask-versions/microsoft-openjdk11\nopenkey\n```\n\nTo show the formula details, you can use the `brew info` command. The Java formula always contains the latest OpenJDK version; at the time of writing, the latest is JDK 17.\n\nThe `openjdk@17` formula contains the Java 17LTS version\n\n```bash\n$ brew info openjdk@17\n==\u003e openjdk@17: stable 17.0.4.1 (bottled) [keg-only]\nDevelopment kit for the Java programming language\nhttps://openjdk.java.net/\n/usr/local/Cellar/openjdk@17/17.0.4.1_1 (639 files, 305.6MB)\n  Poured from bottle on 2023-09-25 at 00:00:57\nFrom: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/[email protected]\nLicense: GPL-2.0-only with Classpath-exception-2.0\n==\u003e Dependencies\nBuild: autoconf ✘\n==\u003e Requirements\nBuild: Xcode ✔\n==\u003e Caveats\nFor the system Java wrappers to find this JDK, symlink it with\n  sudo ln -sfn /usr/local/opt/openjdk@17/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-17.jdk\n\nopenjdk@17 is keg-only, which means it was not symlinked into /usr/local,\nbecause this is an alternate version of another formula.\n\nIf you need to have openjdk@17 first in your PATH, run:\n  echo 'export PATH=\"/usr/local/opt/openjdk@17/bin:$PATH\"' \u003e\u003e ~/.zshrc\n\nFor compilers to find openjdk@17 you may need to set:\n  export CPPFLAGS=\"-I/usr/local/opt/openjdk@17/include\"\n\n==\u003e Analytics\ninstall: 30,649 (30 days), 82,462 (90 days), 154,946 (365 days)\ninstall-on-request: 20,080 (30 days), 52,615 (90 days), 88,978 (365 days)\nbuild-error: 65 (30 days)\n```\n\nNow install the Open JDK 17:\n\n```bash\nbrew install openjdk@17\n```\n"])</script>
1<script>self.__next_f.push([1,"62:T9fa,"])</script>
1<script>self.__next_f.push([1,"\nJava is a high-level, cross-platform, mature, object-oriented programming language. Java is extremely popular due to its flexibility and ability to run anywhere. It abstracts away a lot of details that we don't need to worry about which allows us to focus on the logic in our code.\n\n### Prerequisites\n\nHere are the prerequisites for working with Java:\n\n**Java Development Kit (JDK):** This is the essential software that contains the compiler, tools, and libraries needed to develop Java applications.\n\n**Integrated Development Environment:** This is completely optional, but highly recommended. An IDE provides a user-friendly interface for writing, editing, debugging, and running Java code. Here are some of the popular choices:\n\n-   IntelliJ IDEA\n-   Eclipse\n-   NetBeans\n-   Visual Studio Code (with Java extensions)\n\nIf you've got these two things, you're ready to start this class!\n\n### Installing Java\n\nIf you don't already have Java installed, you can do that using our [Java installation guide](https://stacktips.com/articles/how-to-install-java-for-macos-and-windows). To test that you installed Java correctly, run this command:\n\n```bash\njava --version\n```\n\nYou should get an output similar to this:\n\n```bash\nopenjdk 17.0.7 2023-04-18 LTS\nOpenJDK Runtime Environment Microsoft-7626293 (build 17.0.7+7-LTS)\nOpenJDK 64-Bit Server VM Microsoft-7626293 (build 17.0.7+7-LTS, mixed mode)\n```\n\nIf you have Java installed, you're good to go.\n\n### Installing a IDE\n\nYou will most likely need a Java IDE to write, compile and run your Java code, at least if you don't want to do all of this in the command line. We recommend IntelliJ IDEA but the choice is entirely yours. Follow the [installation steps](https://www.jetbrains.com/help/idea/installation-guide.html) from official IntelliJ website.\n\nAt this point, we will assume you have the Java and an IDE installed. Let's move on to writing Java code!\n\n### Hello World\n\nThe classic example to starting any programming language has got to be printing out `Hello World!`, so let's do just that in Java. First create a file called `HelloWorld.java`\n\n```java\npublic class HelloWorld {\n    public static void main(String[] args) {\n        System.out.println(\"Hello World!\");\n    }\n}\n```\n\nTo run this, you first need to compile your code. We can do that using javac\n\n```bash\njavac HelloWorld.java\n```\n\nThis will compile your code and generate another file HelloWorld.class. To run this file, you need following command:\n\n```bash\njava HelloWorld\n```\n\nNotice, this will print \n\n```bash\nHelloWorld!\n```\n"])</script>
1<script>self.__next_f.push([1,"63:Ta94,"])</script>
1<script>self.__next_f.push([1,"\nEncapsulation is the principle of wrapping data inside an object to protect it from unwanted accesses or manipulation. The point of encapsulating the data inside an object is to ensure that the data inside is properly read and written to.  \n\nEncapsulation is achieved by setting the data inside a class to `private`. This makes the fields inaccessible directly from outside the class. Then we define getter and setter methods whose job it is to ensure data is read and written to in a safe and valid way.\n\n### Getter Methods\n\nHere is an example showing the usefulness of controlling how data is accessed as well using **getter** methods:\n\n```java\npublic class Length {\n    private int millimeters;\n\n    public Length(int millimeters) {\n        this.millimeters = millimeters;\n    }\n\n    public int getMillimeters() {\n        return millimeters;\n    }\n\n    public int getCentimeters() {\n        return millimeters / 100;\n    }\n\n    public int getMeters() {\n        return millimeters / 1000;\n    }\n}\n```\n\nNow instead of having to remember conversions, like this:\n\n```java\nLength length = new Length(345964);\nint centimeters = length.millimeters / 100;\n\nSystem.out.println(centimeters);\n```\n\nYou can just write the conversion method once, and call it anytime you want, completely skipping direct access of `millimeters`:\n\n```java\nLength length = new Length(345964);\nint centimeters = length.getCentimeters();\n\nSystem.out.println(centimeters);\n```\n\n### Setter Methods\n\nHere is an example of encapsulation using a **setter** method:\n\n```java\npublic class BankAccount {\n    private int balance;\n\n    public int getBalance() {\n        return balance;\n    }\n\n    public void deposit(int amount) {\n        if (amount \u003c 0) {\n            // show error\n            return;\n        }\n        this.balance += amount;\n    }\n}\n```\n\nIn this example, our class just has a single field, `balance` that was set to `private`. Now, instead of allowing this:\n\n```java\nBankAccount account = new BankAccount();\nint depositAmount = 5;\n\naccount.balance += depositAmount;\n```\n\nUsers of this class must use the internal method to manipulate the `balance`:\n\n```java\nBankAccount account = new BankAccount();\nint depositAmount = 5;\n\naccount.deposit(depositAmount);\n```\n\nUsing setter methods prevents negative amount deposits from happening:\n\n```java\nBankAccount account = new BankAccount();\nint depositAmount = -5;\n\naccount += depositAmount;\n```\n\nBecause we can have additional checks and improved data integrity by forcing all desired changes to use setter methods. This is ultimately the beauty and point of utilizing encapsulation. You can have more control over your data and ensure that only valid operations are performed with it.\n"])</script>
1<script>self.__next_f.push([1,"64:Te2d,"])</script>
1<script>self.__next_f.push([1,"\nCreating a new object creates a new instance of that class. Because two different objects are separate instances, things can happen inside each one without affecting the other. We've already seen many cases where instances matter. For example, inside the constructor, like this:\n\n```java\npublic class Pet {\n    String name;\n    int weight;\n\n    Pet(String name, int weight) {\n        this.name = name;\n        this.weight = weight;\n    }\n}\n```\n\nThe `this` keyword refers to the current instance of the class. Sometimes, you will want data or methods to remain inaccessible to other classes. This is where access modifiers come in to play.\n\n### Access Modifiers\n\nAccess modifiers change how a class, method, or property can be accessed by other classes. For example, we can restrict direct access to `name` and `weight` by marking them as private:\n\n```java\npublic class Pet {\n    private String name;\n    private int weight;\n\n    Pet(String name, int weight) {\n        this.name = name;\n        this.weight = weight;\n    }\n}\n```\n\nOf course, these are properties you want accessible in some fashion. This is why getters (and setter) methods exist:\n\n```java\npublic class Pet {\n    private String name;\n    private int weight;\n\n    Pet(String name, int weight) {\n        this.name = name;\n        this.weight = weight;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public int getWeight() {\n        return weight;\n    }\n}\n```\n\nWhich lets you get things like this:\n\n```java\npet.getName();\npet.getWeight();\n```\n\nIn this particular instance, it doesn't really add much value, but sometimes you want to do some validation or calculations using the property. In that case, you definitely want to restrict direct access of a property and instead make users go through specific methods.\n\n#### Public Access Modifier\n\nThe `public` access modifier is usable on classes, properties, methods, and constructors. This makes them accessible for all classes:\n\n```java\npublic class Pet {\n    public String name;\n    public int weight;\n\n    Pet(String name, int weight) {\n        this.name = name;\n        this.weight = weight;\n    }\n}\n```\n\n#### Private Access Modifier\n\nThe `private` access modifier is usable on properties, methods, and constructors. They make the code only accessible within that class:\n\n```java\npublic class Pet {\n    private String name;\n    private int weight;\n\n    Pet(String name, int weight) {\n        this.name = name;\n        this.weight = weight;\n    }\n}\n```\n\nTo access these values, the class needs to provide a public method inside that returns that value.\n\n#### Protected Access Modifier\n\nThe `protected` access modifier is usable on properties, methods, and constructors. They make the code only accessible within that class and any class that extends it:\n\n```java\npublic class Pet {\n    protected String name;\n    protected int weight;\n\n    Pet(String name, int weight) {\n        this.name = name;\n        this.weight = weight;\n    }\n}\n\npublic class Cat extends Pet {\n    Cat(String name, int weight) {\n        super(name, weight);\n    }\n}\n```\n\n### Static\n\nThe `static` makes properties and methods available for use without the need for instances or objects:\n\n```java\npublic class Main {\n\n    public static void main(String[] args) {\n        hello();\n    }\n\n    public static void hello() {\n        System.out.println(\"Hello\");\n    }\n}\n```\n\n### Final\n\nThe `final` keyword makes it so that a defined property cannot be overridden:\n\n```java\npublic class Main {\n\n    final static int example = 0;\n\n    public static void main(String[] args) {\n        example = 1; // this would fail\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"65:T8c6,"])</script>
1<script>self.__next_f.push([1,"\nEnums, short for enumerations in Java are a group of named constants that you can define in an array-like structure. They are useful for when you want to create a bunch of related values.\n\n### Defining an Enum\n\nLet's dive straight into it and define an enum using the `enum` keyword:\n\n```java\nenum Fruit {\n    APPLE,\n    ORANGE,\n    BANANA\n}\n```\n\nThis enum we have created is named `Fruit` and it contains three items in it. Keep in mind that it is convention to capitalize all the names. Inside a class, it can look like this:\n\n```java\npublic class Main {\n\n    enum Fruit {\n        APPLE,\n        ORANGE,\n        BANANA\n    }\n\n    public static void main(String[] args) {\n\n    }\n}\n```\n\n### Using an Enum value\n\nNow that we have our enum, we can decide to use it. A common way enums are used are inside a switch statement. Let's see how that looks:\n\n```java\npublic class Main {\n\n    enum Fruit {\n        APPLE,\n        ORANGE,\n        BANANA\n    }\n\n    public static void main(String[] args) {\n        Fruit fruit = Fruit.APPLE;\n        switch(fruit) {\n            case APPLE:\n                System.out.println(\"An apple was found!\");\n                break;\n            case ORANGE:\n                System.out.println(\"An orange was found!\");\n                break;\n            case BANANA:\n                System.out.println(\"A banana was found!\");\n                break;\n        }\n    }\n}\n```\n\n```bash\nAn apple was found!\n```\n\n### Looping through Enums\n\nInstead of using an enum one at a time, you can loop through them all by using the `values()` method which returns an array of all the enum values. This then allows you to loop over all of them:\n\n```java\npublic class Main {\n\n    enum Fruit {\n        APPLE,\n        ORANGE,\n        BANANA\n    }\n\n    public static void main(String[] args) {\n        for (Fruit fruit : Fruit.values()) {\n            System.out.println(fruit);\n        }\n    }\n}\n```\n\n```bash\nAPPLE\nORANGE\nBANANA\n```\n\nFor the most part, enums are used when you know the value of them will not change and there's a finite number of them, since they are constant. Real world examples of good cases to use enums include the months in a year, a list of US states, time zones, and the planets in our solar system, to name a few.\n"])</script>
1<script>self.__next_f.push([1,"66:T6e4,"])</script>
1<script>self.__next_f.push([1,"\nAn interface is a template for another class to follow. It defines strictly all of the abstract methods that any class that wants to implement must include. Interfaces are similar to abstract classes except that every method in an interface must be abstract, it does not contain a constructor, and it does not contain instance fields.\n\n### Declaring Instances\n\nTo declare a new instance, use the `instance` keyword:\n\n```java\npublic interface Phone {\n    public void call();\n    public void text();\n}\n```\n\nLet's say we want to represent phones in our code. Phones can both call and text, but each phone does it slightly differently. This interface defines the methods that all phones need to do, so any class that implements this interface, will need to include their version of it.\n\n### Implementing Interfaces\n\nNow let's create classes that implement our `Phone` interface using the `implements` keyword:\n\n```java\npublic class iPhone implements Phone {\n\n   public void call() {\n      System.out.println(\"iPhone call\");\n   }\n\n   public void text() {\n      System.out.println(\"iPhone Text\");\n   }\n}\n\npublic class Pixel implements Phone {\n\n   public void call() {\n      System.out.println(\"Pixel call\");\n   }\n\n   public void text() {\n      System.out.println(\"Pixel Text\");\n   }\n}\n```\n\nNow we can create actual `Phone` objects and invoke their interface methods:\n\n```java\nPhone iPhone = new iPhone();\niPhone.call();\niPhone.text();\n\nPhone pixel = new Pixel();\npixel.call();\npixel.text();\n```\n\n```bash\niPhone call\niPhone Text\nPixel call\nPixel Text\n```\n\nKeep in mind that a single class can implement multiple interfaces!\n\nAnd just like that, we can define multiple instances of `Phone` and be guaranteed that each one will have the methods outlined in the interface.\n"])</script>
1<script>self.__next_f.push([1,"67:T740,"])</script>
1<script>self.__next_f.push([1,"\nAbstract classes are classes in Java that contain abstract methods which let children classes provide the implementation. Defining abstract classes is useful for when you want different implementation for the same method.\n\n### Creating an Abstract Class\n\nLet's say we are trying to get from point A to point B. This is represented by our abstract class `Transportation.java`:\n\n```java\npublic abstract class Transportation {\n    public abstract void travel();\n}\n```\n\nOur new `Transportation` class is abstract which means you cannot actually make an object directly from it.\n\n### Extending an Abstract Class\n\nWhile you can't make objects directly from an abstract class, you can make objects from the classes that extend it. Let's define two different modes of transportation, by extending that abstract class:\n\n```java\npublic class Train extends Transportation {\n    public void travel() {\n        System.out.println(\"Choo choo!\");\n    }\n}\n\npublic class Car extends Transportation {\n    public void travel() {\n        System.out.println(\"Beep beep!\");\n    }\n}\n```\n\nOur classes `Train` and `Car` extend our abstract class `Transportation`, which forced both of them to provide an implementation for the `travel()` abstract method.\n\nNow we can use our new classes, like this:\n\n```java\npublic class Main {\n\n    public static void main(String[] args) {\n        Train train = new Train();\n        train.travel();\n\n        Car car = new Car();\n        car.travel();\n    }\n}\n```\n\n```bash\nChoo choo!\nBeep beep!\n```\n\nThis right here is the power of abstract classes. Their job is just to define a contract, and any class that extends it agrees to that contract. In this case, the contract is that if you want to be a mode of transportation, you must be able to travel. Both `Train` and `Car` implemented that method and thus became valid types of transportation.\n"])</script>
1<script>self.__next_f.push([1,"68:Tebd,"])</script>
1<script>self.__next_f.push([1,"\nInheritance is the process in which a class is able to access and utilize the properties, methods, and fields of a parent class. This is useful for when you don't want to define multiple classes that share functionality because you can just have the parent hold that functionality and allow children classes to specialize wherever needed.\n\n### Inheriting from a Parent Class\n\nSticking to our `Pet` class example, let's define two kinds of pets, `Cat` and `Dog`. Given that both of these animals tend to be pets, it makes sense to have them be children of the `Pet` class.\n\nDeclare children to be parents of another class by using the `extends` keyword:\n\n```java\npublic static class Cat extends Pet {\n    Cat(String name, int weight) {\n        super(name, weight);\n    }\n\n    void meow() {\n        System.out.println(\"Meow!\");\n    }\n}\n\npublic static class Dog extends Pet {\n    Dog(String name, int weight) {\n        super(name, weight);\n    }\n\n    void bark() {\n        System.out.println(\"Bark!\");\n    }\n}\n```\n\nFor reference, this is how the parent `Pet` class looks like:\n\n```java\npublic static class Pet {\n    String name;\n    int weight;\n\n    Pet(String name, int weight) {\n        this.name = name;\n        this.weight = weight;\n    }\n\n    void printInfo() {\n        System.out.println(\"Name: \" + name + \" Weight: \" + weight + \" pounds.\");\n    }\n}\n```\n\nBoth children classes, `Cat` and `Dog`, extend the `Pet` class. What this means is that now both of them have access to the same properties that `Pet` has defined, namely `name`, `weight`, and `printInfo()`.\n\nIf you were wondering about what `super` does, that just calls the constructor of the parent class and passes in the necessary parameters up the chain. This ensures that the child class is still a valid type of its parent.\n\n### Creating Children objects\n\nNow that we have the parent and children classes defined, we can create objects from them and truly illustrate the usefulness of inheritance in Java.\n\nLet's put it all together and create both a cat and dog.\n\n```java\npublic class Main {\n\n    public static class Pet {\n        String name;\n        int weight;\n\n        Pet(String name, int weight) {\n            this.name = name;\n            this.weight = weight;\n        }\n\n        void printInfo() {\n            System.out.println(\"Name: \" + name + \" Weight: \" + weight + \" pounds.\");\n        }\n    }\n\n    public static class Cat extends Pet {\n        Cat(String name, int weight) {\n            super(name, weight);\n        }\n\n        void meow() {\n            System.out.println(\"Meow!\");\n        }\n    }\n\n    public static class Dog extends Pet {\n        Dog(String name, int weight) {\n            super(name, weight);\n        }\n\n        void bark() {\n            System.out.println(\"Bark!\");\n        }\n    }\n\n    public static void main(String[] args) {\n        Dog dog = new Dog(\"Scooby\", 4);\n        dog.bark();\n        dog.printInfo();\n\n        Cat cat = new Cat(\"Tinkerbell\", 9);\n        cat.meow();\n        cat.printInfo();\n    }\n}\n```\n\n```bash\nBark!\nName: Scooby Weight: 4 pounds.\nMeow!\nName: Tinkerbell Weight: 9 pounds.\n```\n\nNotice what happened here. Only a dog can bark and only a cat can meow, so it makes sense that only those classes can call those respective methods. But notice how both objects were able to call `printInfo()`, which uses `name` and `weight`? That is, of course, because `Dog` and `Cat` are still valid instance of `Pet` and thus have access to those sames properties just like any `Pet`.\n\nUsing inheritance, we were able to create specialized children classes that inherit functionality from the parent class that they extend from for free. This helps keep logically connected classes linked by their parent which helps structure our overall program much better.\n"])</script>
1<script>self.__next_f.push([1,"69:Tf9e,"])</script>
1<script>self.__next_f.push([1,"\nPolymorphism is the concept that an object can take the form of many different types. We touched upon polymorphism a little with our previous `Pet`, `Dog` and `Cat` classes. Specifically, how both cats and dogs can use properties and methods from their parent class since they are also pets:  \n\n```java\npublic class Main {\n\n    public static class Pet {\n        String name;\n        int weight;\n\n        Pet(String name, int weight) {\n            this.name = name;\n            this.weight = weight;\n        }\n\n        void printInfo() {\n            System.out.println(\"Name: \" + name + \" Weight: \" + weight + \" pounds.\");\n        }\n    }\n\n    public static class Cat extends Pet {\n        Cat(String name, int weight) {\n            super(name, weight);\n        }\n\n        void meow() {\n            System.out.println(\"Meow!\");\n        }\n    }\n\n    public static class Dog extends Pet {\n        Dog(String name, int weight) {\n            super(name, weight);\n        }\n\n        void bark() {\n            System.out.println(\"Bark!\");\n        }\n    }\n\n    public static void main(String[] args) {\n        Dog dog = new Dog(\"Scooby\", 4);\n        dog.bark();\n        dog.printInfo();\n\n        Cat cat = new Cat(\"Tinkerbell\", 9);\n        cat.meow();\n        cat.printInfo();\n    }\n}\n```\n\n```bash\nBark!\nName: Scooby Weight: 4 pounds.\nMeow!\nName: Tinkerbell Weight: 9 pounds.\n```\n\n### Method Overloading\n\nMethod overloading is when you create multiple methods with the same name but different parameters. This is useful for when you want to have optional parameters.\n\nHere's an example of method overloading:\n\n```java\npublic class Main {\n\n    public static void main(String[] args) {\n        int squareSideLength = 3;\n        int squareArea = getAreaOfRectangle(squareSideLength);\n\n        System.out.println(squareArea);\n\n        int rectangleWidthLength = 5;\n        int rectangleHeightLength = 6;\n        int rectangleArea = getAreaOfRectangle(rectangleWidthLength, rectangleHeightLength);\n\n        System.out.println(rectangleArea);\n    }\n\n    public static int getAreaOfRectangle(int width, int height) {\n        return width * height;\n    }\n\n    public static int getAreaOfRectangle(int length) {\n        return length * length;\n    }\n}\n```\n\n```bash\n9\n30\n```\n\nIn this example of method overloading, we have the same method name, `getAreaOfRectangle()` twice, but depending on which one you use, the method will function slightly different.\n\n### Method Overriding\n\nMethod overriding is when you define a method with the same name and parameters as one used by the parent class. When you do this, calling that method will result in the child's class method being run and not the parent's.\n\nLet's take a look at how this looks in practice:\n\n```java\npublic class Main {\n\n    public static class Pet {\n        String name;\n        int weight;\n\n        Pet(String name, int weight) {\n            this.name = name;\n            this.weight = weight;\n        }\n\n        void printInfo() {\n            System.out.println(\"Name: \" + name + \" Weight: \" + weight + \" pounds.\");\n        }\n    }\n\n    public static class Cat extends Pet {\n        Cat(String name, int weight) {\n            super(name, weight);\n        }\n\n        void printInfo() {\n            System.out.println(\"Cat Name: \" + name + \" Cat Weight: \" + weight + \" pounds.\");\n        }\n    }\n\n    public static void main(String[] args) {\n        Pet pet = new Pet(\"Scooby\", 4);\n        pet.printInfo();\n\n        Cat cat = new Cat(\"Tinkerbell\", 9);\n        cat.printInfo();\n    }\n}\n```\n\n```bash\nName: Scooby Weight: 4 pounds.\nCat Name: Tinkerbell Cat Weight: 9 pounds.\n```\n\nWe defined `printInfo()` in both the child and parent class. Since they both were named the same with the same parameters, Java automatically used the children's implementation, which includes a different string at the start. Overriding methods is super useful for when you want to have specialized behavior in a child object when compared to the more general parent object.\n"])</script>
1<script>self.__next_f.push([1,"6a:T1ca9,"])</script>
1<script>self.__next_f.push([1,"\nAn exception is an event that can disrupt the execution flow. Handling exceptions is the process of responding to exceptions. Exception handling in Java allows you to handle any interruptions, allowing a program to continue or terminate gracefully.\n\nIf you don't handle it properly, it can cause your entire program to terminate and produce undesired behaviours.\n\n### Examples of exceptions:\n\nFor example, let's say we have an algorithm that divides two numbers and calculates the Quotient. What happens when the value of `number2` is 0?\n\n```java\nclass Calculator {\n    public float calculateQuotient(int number1, int number2) {\n        return number1 / number2;\n    }\n}\n\npublic class Main {\n    public static void main(String[] args) {\n        Calculator calculator = new Calculator();\n        //1\n        System.out.println(\"Result: \" + calculator.calculateQuotient(3000, 2));\n        //2\n        System.out.println(\"Result: \" + calculator.calculateQuotient(3000, 0));\n        //3\n        System.out.println(\"Result: \" + calculator.calculateQuotient(3000, 3));\n    }\n}\n```\n\nThe above program will cause an `ArithmeticException` and the program will terminate after executing the first line.\n\n```text\nResult: 1500.0\nException in thread \"main\" java.lang.ArithmeticException: / by zero\n    at exceptionhandling.Calculator.calculateQuotient(Calculator.java:6)\n    at exceptionhandling.Main.main(Main.java:8)\n```\n\nThis is a simple example, but when your application is running in production, you can expect other events such as: - a network connection being interrupted - attempting to access the data from a database with an invalid username/password - or, when your users enter incorrect data\n\nIn this lesson, we'll learn how to safely and gracefully handle an exception so that your program behaves as expected.\n\n## Java Exception Types\n\nThere are mainly three types of exceptions: checked, unchecked and Error. An error is considered an unchecked exception.\n\n![](/media/summernote/Java-Exception_Class_Hierarchy.jpg)  \n\n### Checked Exceptions\n\nChecked Exceptions are exceptions that the JAVA compiler requires us to handle. We have to use the try, cache block to handle the exception or throw the exception up the call stack. For example, **IOException**, **SQLException**, etc are examples of checked exceptions.\n\nAll modern Java IDEs (Integrated Development Environments) will show these errors during the compilation time.\n\n### Unchecked Exceptions\n\nThe Java compiler ignores the unchecked exceptions and we are not forced by the compiler to handle it. Unchecked exceptions are those exceptions that extend `RuntimeException` For example, **NullPointerException**, **IllegalArgumentException**, etc are examples of unchecked exceptions.\n\nThough the Java compiler does not force us, we can still choose to handle this exception to maintain the normal flow of the program.\n\n### Errors\n\nErrors are unrecoverable conditions. For example, if infinite recursion or memory leaks are considered as errors. Errors do not extend the `RuntimeException` class, but they are considered as unchecked as well.\n\nFor example, **StackOverflowError**, **OutOfMemoryError**, etc are considered as errors.\n\n## Custom Exceptions\n\nAccording to your business requirements, we may create your own custom exceptions by extending any of the exception classes from the hierarchy above. For example, we want to validate certain user inputs and throw an exception if invalid inputs are provided.\n\n## Handling Exception in Java\n\nExceptions in Java are handled using the `try-catch` block.\n\n-   The try block contains the code where exceptions might occur.\n-   The `catch` block contains the code to handle the exception when it is thrown\n-   The `finally` block executes no matter if an exception was thrown or not, you can use the `finally` block:\n\n_Note_\n\nIn java, you can use a try block without a catch block but you can't use the catch block without a try block. There can be multiple catch blocks for a try block but only one finally block for a try-catch block.\n\nHere is a flow diagram of how the try-catch block works in Java.\n\n![](/media/summernote/Exception-handling.drawio.png)  \n\nLet us now rewrite the above example with an exception handler.\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n\n        try {\n            Calculator calculator = new Calculator();\n            System.out.println(\"Result:\" + calculator.calculateQuotient(3000, 2));\n            System.out.println(\"Result:\" + calculator.calculateQuotient(3000, 0));\n            System.out.println(\"Result:\" + calculator.calculateQuotient(3000, 3));\n        } catch (ArithmeticException e) {\n            System.out.println(\"An Ar
1ithmeticException was thrown! \" + e.getMessage());\n        } finally {\n            System.out.println(\"Moving on!\");\n        }\n    }\n}\n```\n\nOutput:\n\n```bash\nAn ArithmeticException was thrown!\nMoving on!\n```\n\n### Multiple Exception Blocks\n\nYou can handle multiple exceptions by chaining the `catch` blocks to a single try block.\n\n```java\ntry {\n    // Your code goes here..\n} catch(ArithmeticException e) {\n    System.out.println(\"An ArithmeticException was thrown!\");\n} catch(NullPointerException e) {\n    System.out.println(\"A NullPointerException was thrown!\");\n} finally {\n    System.out.println(\"Moving on!\");\n}\n```\n\nWhen multiple `catch` blocks are provided, the matched catch block will be executed.\n\nSince Java 7, we can catch multiple exceptions in a single catch block using the `|` pipe symbol as follows:\n\n```java\ntry {\n    // Your code goes here..\n} catch(ArithmeticException | NullPointerException e) {\n    System.out.println(\"An was thrown!\");\n} finally {\n    System.out.println(\"Moving on!\");\n}\n```\n\nThough this approach is flexible and reduces code duplication, it is not recommended as it is not possible to differentiate between different types of exceptions.\n\n### Throwing Custom Exceptions\n\nJava allows us to create custom exceptions to provide meaningful error messages for your application. A custom exception class may extend the `Exception` class for checked exceptions or the `RuntimeException` class for unchecked exceptions.\n\nFor example, let's say we have an application that needs to import the content of a file into the database. For our application to work, we need to provide our database username and password. Given my importer application has started without passing a username or password, our app should validate and throw a custom exception before attempting to connect to the database.\n\nIn this example, we want our application to fail as it cannot process without a valid username or password. For this, we can write a custom exception class by extending the `Exception` class.\n\n```java\npublic class MissingCredentialsException extends 
1Exception {\n\n    public MissingCredentialsException(String message) {\n        super(message);\n    }\n}\n```\n\nNow we can validate and throw our custom exception by using the `throw` keyword:\n\n```java\npublic void importContent(String username, String password) throws MissingCredentialsException {\n    if(null== username || null== password) {\n        throw new MissingCredentialsException(\"Username or password is empty!\");\n    }\n\n    //TODO your code goes here.\n}\n```\n\nNow that the `importContent()` throws `MissingCredentialsException` like any other exception.\n"])</script>
1<script>self.__next_f.push([1,"6b:T3e22,"])</script>
1<script>self.__next_f.push([1,"\nThe collections framework in Java defines numerous different data structures in which you can store, group, and retrieve objects. Located inside the `java.util` package, the collections framework contains numerous different classes and interfaces including `ArrayList`, `LinkedList`, `Queue`, `HashSet`, `HashMap`, amongst others.\n\nAll of these support adding, removing, getting the total size, clearing, checking if an item exists, whether or not it is empty, and many others. In this lesson, we'll dive into some of these collections and learn how to do the basic operations in each.\n\n### ArrayList\n\nAn `ArrayList` is similar to a normal Java array except that the size here is dynamically and automatically adjusted as the size of the collection changes. Remember that normal arrays have a fixed size that cannot change. With `ArrayList`, you don't need to worry about the size. Import the class you're good to go:\n\n```java\nimport java.util.ArrayList;\n```\n\nLet's look at how to use an `ArrayList`.\n\n#### Creating an ArrayList\n\n```java\nimport java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList\u003cString\u003e countries = new ArrayList\u003cString\u003e();\n    }\n}\n```\n\nPut the type of objects you want to collect inside the diamond operator like shown above and you're good to go.\n\n#### Adding items to an ArrayList\n\n```java\nimport java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList\u003cString\u003e countries = new ArrayList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        System.out.println(countries);\n    }\n}\n```\n\n```bash\n[United States of America, United Kingdom, Canada]\n```\n\n#### Accessing an Item in an ArrayList\n\n```java\nimport java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList\u003cString\u003e countries = new ArrayList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        System.out.println(countries.get(1));\n    }\n}\n```\n\n```bash\nUnited Kingdom\n```\n\n#### Changing an Item in an ArrayList\n\n```java\nimport java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList\u003cString\u003e countries = new ArrayList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n        countries.set(1, \"Australia\");\n        System.out.println(countries.get(1));\n    }\n}\n```\n\n```bash\nAustralia\n```\n\n#### Removing an Item in an ArrayList\n\n```java\nimport java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList\u003cString\u003e countries = new ArrayList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        countries.remove(1);\n        System.out.println(countries);\n    }\n}\n```\n\n```bash\n[United States of America, Canada]\n```\n\n#### Get Size of an ArrayList\n\n```java\nimport java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList\u003cString\u003e countries = new ArrayList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        System.out.println(countries.size());\n    }\n}\n```\n\n```bash\n3\n```\n\n#### Check if Item exists in ArrayList\n\n```java\nimport java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList\u003cString\u003e countries = new ArrayList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        boolean contains = countries.contains(\"Canada\");\n\n        System.out.println(contains);\n    }\n}\n```\n\n```bash\ntrue\n```\n\n#### Iterate over an ArrayList\n\n```java\nimport java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList\u003cString\u003e countries = new ArrayList\u003cString\u003e
1();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        for (int i = 0; i \u003c countries.size(); i++) {\n          System.out.println(countries.get(i));\n        }\n    }\n}\n```\n\n```bash\nUnited States of America\nUnited Kingdom\nCanada\n```\n\n### LinkedList\n\nA `LinkedList` is similar to an `ArrayList` except the way the data is stored in memory. Where an `ArrayList` uses a normal array to store elements, a `LinkedList` uses a doubly linked list to store elements. What this means is that each item knows where the next and previous items are, instead of in an array where you simply increment or decrement the index.\n\nIn general, a `LinkedList` is better when you're manipulating data, but an `ArrayList` is superior when it comes to simply storing and accessing that data. To start using a `LinkedList`, import the class you're good to go:\n\n```java\nimport java.util.LinkedList;\n```\n\n#### Creating a LinkedList\n\n```java\nimport java.util.LinkedList;\n\npublic class Main {\n    public static void main(String[] args) {\n        LinkedList\u003cString\u003e countries = new LinkedList\u003cString\u003e();\n    }\n}\n```\n\n#### Adding items to LinkedList\n\n```java\nimport java.util.LinkedList;\n\npublic class Main {\n    public static void main(String[] args) {\n        LinkedList\u003cString\u003e countries = new LinkedList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        System.out.println(countries);\n    }\n}\n```\n\n```bash\n[United States of America, United Kingdom, Canada]\n```\n\n#### Removing an Item in an LinkedList\n\n```java\nimport java.util.LinkedList;\n\npublic class Main {\n    public static void main(String[] args) {\n        LinkedList\u003cString\u003e countries = new LinkedList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        countries.remove(1);\n\n        System.out.println(countries);\n    }\n}\n```\n\n```bash\n[United States of America, Canada]\n```\n\n#### Get Size of LinkedList\n\n```java\nimport java.util.LinkedList;\n\npublic class Main {\n    public static void main(String[] args) {\n        LinkedList\u003cString\u003e countries = new LinkedList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        System.out.println(countries.size());\n    }\n}\n```\n\n```bash\n3\n```\n\n#### Check if Item exists in LinkedList\n\n```java\nimport java.util.LinkedList;\n\npublic class Main {\n    public static void main(String[] args) {\n        LinkedList\u003cString\u003e countries = new LinkedList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        boolean contains = countries.contains(\"Canada\");\n\n        System.out.println(contains);\n    }\n}\n```\n\n```bash\ntrue\n```\n\n#### Iterate over an LinkedList\n\n```java\nimport java.util.LinkedList;\n\npublic class Main {\n    public static void main(String[] args) {\n        LinkedList\u003cString\u003e countries = new LinkedList\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        for (int i = 0; i \u003c countries.size(); i++) {\n          System.out.println(countries.get(i));\n        }\n    }\n}\n```\n\n```bash\nUnited States of America\nUnited Kingdom\nCanada\n```\n\n### HashSet\n\nA Java `HashSet` is a collection that uses a hash table for storage. Elements are stored by hashing and as a result only supports unique elements only. Unlike most collections, a `HashSet` does not keep track of order. As a result, using a `HashSet` is best when you simply want to search data.\n\nImport the class you're good to go:\n\n```java\nimport java.util.HashSet;\n```\n\n#### Creating a HashSet\n\n```java\nimport java.util.HashSet;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashSet\u003cString\u003e countries = new HashSet\u003cString\u003e
1();\n    }\n}\n```\n\n#### Adding items to a HashSet\n\n```java\nimport java.util.HashSet;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashSet\u003cString\u003e countries = new HashSet\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        System.out.println(countries);\n    }\n}\n```\n\n```bash\n[Canada, United States of America, United Kingdom]\n```\n\nNotice the order is different here? Items are inserted by their hashcode, not their order.\n\n#### Removing an Item in a HashSet\n\n```java\nimport java.util.HashSet;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashSet\u003cString\u003e countries = new HashSet\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        countries.remove(\"United Kingdom\");\n\n        System.out.println(countries);\n    }\n}\n```\n\n```bash\n[Canada, United States of America]\n```\n\n#### Get Size of HashSet\n\n```java\nimport java.util.HashSet;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashSet\u003cString\u003e countries = new HashSet\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        System.out.println(countries.size());\n    }\n}\n```\n\n```bash\n3\n```\n\n#### Check if Item exists in HashSet\n\n```java\nimport java.util.HashSet;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashSet\u003cString\u003e countries = new HashSet\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        boolean contains = countries.contains(\"Canada\");\n\n        System.out.println(contains);\n    }\n}\n```\n\n```bash\ntrue\n```\n\n#### Iterate over a HashSet\n\n```java\nimport java.util.HashSet;\nimport java.util.Iterator;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashSet\u003cString\u003e countries = new HashSet\u003cString\u003e();\n        countries.add(\"United States of America\");\n        countries.add(\"United Kingdom\");\n        countries.add(\"Canada\");\n\n        Iterator\u003cString\u003e iterator = countries.iterator();\n        while(iterator.hasNext()) {\n            System.out.println(iterator.next());\n        }\n    }\n}\n```\n\n```bash\nCanada\nUnited States of America\nUnited Kingdom\n```\n\nAll collections support iterators. We need to use an iterator when we use a `HashSet` to iterate since it doesn't support indexes.\n\n### HashMap\n\nA `HashMap` works fundamentally different than the other collections we've seen here. A `HashMap` uses key-value pairs to insert and access items. All keys must be unique and this, like a `HashSet` does not maintain order. HashMaps are great when you know the key of the item you want to access.\n\n
1Import the class you're good to go:\n\n```java\nimport java.util.HashMap;\n```\n\n#### Creating a HashMap\n\n```java\nimport java.util.HashMap;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashMap\u003cString, Integer\u003e population = new HashMap\u003cString, Integer\u003e();\n    }\n}\n```\n\n#### Adding items to a HashMap\n\n```java\nimport java.util.HashMap;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashMap\u003cString, Integer\u003e population = new HashMap\u003cString, Integer\u003e();\n        population.put(\"United States of America\", 327200000);\n        population.put(\"United Kingdom\", 66440000);\n        population.put(\"Canada\", 37590000);\n\n        System.out.println(population);\n    }\n}\n```\n\n```bash\n{Canada=37590000, United States of America=327200000, United Kingdom=66440000}\n```\n\nNote that like mentioned before, order is not preserved in a `HashMap`.\n\n#### Accessing an Item in a HashMap\n\n```java\nimport java.util.HashMap;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashMap\u003cString, Integer\u003e population = new HashMap\u003cString, Integer\u003e();\n        population.put(\"United States of America\", 327200000);\n        population.put(\"United Kingdom\", 66440000);\n        population.put(\"Canada\", 37590000);\n\n        System.out.println(population.get(\"United Kingdom\"));\n    }\n}\n```\n\n```bash\n66440000\n```\n\n#### Changing an Item in a HashMap\n\n```java\nimport java.util.HashMap;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashMap\u003cString, Integer\u003e population = new HashMap\u003cString, Integer\u003e();\n        population.put(\"United States of America\", 327200000);\n        population.put(\"United Kingdom\", 66440000);\n        population.put(\"Canada\", 37590000);\n\n        population.replace(\"United States of America\", 100000000); // uh oh\n\n        System.out.println(population.get(\"United States of America\"));\n    }\n}\n```\n\n```bash\n100000000\n```\n\n#### Removing an Item in a HashMap\n\n```java\nimport java.util.HashMap;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashMap\u003cString, Integer\u003e population = new HashMap\u003cString, Integer\u003e();\n        population.put(\"United States of America\", 327200000);\n        population.put(\"United Kingdom\", 66440000);\n        population.put(\"Canada\", 37590000);\n\n        population.remove(\"United States of America\");\n\n        System.out.println(population);\n    }\n}\n```\n\n```bash\n{Canada=37590000, United Kingdom=66440000}\n```\n\n#### Get Size of a HashMap\n\n```java\nimport java.util.HashMap;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashMap\u003cString, Integer\u003e population = new HashMap\u003cString, Integer\u003e();\n        population.put(\"United States of America\", 327200000);\n        population.put(\"United Kingdom\", 66440000);\n        population.put(\"Canada\", 37590000);\n\n        System.out.println(population.size());\n    }\n}\n```\n\n```bash\n3\n```\n\n#### Check if Item exists in HashMap\n\n```java\nimport java.util.HashMap;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashMap\u003cString, Integer\u003e population = new HashMap\u003cString, Integer\u003e();\n        population.put(\"United States of America\", 327200000);\n        population.put(\"United Kingdom\", 66440000);\n        population.put(\"Canada\", 37590000);\n\n        boolean contains = population.containsKey(\"Canada\");\n\n        System.out.println(contains);\n    }\n}\n```\n\n```bash\ntrue\n```\n\n#### Iterate over a HashMap\n\n```java\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashMap\u003cString, Integer\u003e population = new HashMap\u003cString, Integer\u003e();\n        population.put(\"United States of America\", 327200000);\n        population.put(\"United Kingdom\", 66440000);\n        population.put(\"Canada\", 37590000);\n\n        for (Map.Entry\u003cString, Integer\u003e country : population.entrySet()) {\n            System.out.println(\"Name: \" + country.getKey() + \", Population: \" + country.getValue());\n        }\n    }\n}\n```\n\n```bash\nName: Canada, Population: 37590000\nName: United States of America, Population: 327200000\nName: United Kingdom, Population: 66440000\n```\n\nAlternatively, you can iterate over either just the keys or just the values:\n\n```java\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic class Main {\n    public static void main(String[] args) {\n        HashMap\u003cString, Integer\u003e population = new HashMap\u003cString, Integer\u003e();\n        population.put(\"United States of America\", 327200000);\n        population.put(\"United Kingdom\", 66440000);\n        population.put(\"Canada\", 37590000);\n\n        // just keys\n        for (String name : population.keySet()) {\n            System.out.println(name);\n        }\n\n        // just values\n        for (int pop : population.values()) {\n            System.out.println(pop);\n        }\n    }\n}\n```\n\n```bash\nCanada\nUnited States of America\nUnited Kingdom\n37590000\n327200000\n66440000\n```\n"])</script>
1<script>self.__next_f.push([1,"6c:T1595,"])</script>
1<script>self.__next_f.push([1,"\nJava offers packages that make working with the file system as easy and painless as possible. These packages enable you to access, manipulate, open, read, write, append, and close files and folders.\n\n### Opening a File\n\nTo open a file, you will need to utilize the `File` class and specify the name of the file to the constructor. Also, don't forget to import the package:\n\n```java\nimport java.io.File;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        File file = new File(\"myfile.txt\");\n    }\n}\n```\n\nFor the purposes of this tutorial, let's assume the contents of `myfile.txt` looks like this:\n\n```bash\nWelcome\nto\nstacktips.com!\n```\n\nAfter this, you are ready to use your new `File` object to do numerous different operations.\n\n### Reading a File\n\nNow that you have opened a file, you can now read from it. The most common way you'll want to read a file, especially a text file, is line by line. We will need to import the `Scanner` class that specializes in read text files. This how you do that in Java:\n\n```java\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.util.Scanner;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        try {\n            File file = new File(\"myfile.txt\");\n            Scanner reader = new Scanner(file);\n\n            while (reader.hasNextLine()) {\n                String line = reader.nextLine();\n                System.out.println(line);\n            }\n\n            reader.close();\n        } catch (FileNotFoundException exception) {\n            exception.printStackTrace();\n        }\n    }\n}\n```\n\n```bash\nWelcome\nto\nstacktips.com!\n```\n\nOur reader needs a `File` instance to initialize itself, so we passed it our previously defined one. Then using a while loop, we keep checking if the text file has another line left, if so, we read it and print it. After that is over, we close our reader. All of this needs to be wrapped in a `try-catch` block for safety.\n\n### Creating a File\n\nYou can create a file easily in Java using the `createNewFile()` method. It will return to you a boolean value indicating whether or not the creation attempt was successful.\n\n```java\nimport java.io.File;\nimport java.io.IOException;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        try {\n            File file = new File(\"myfile.txt\");\n            if (file.createNewFile()) {\n                // file created\n            } else {\n                // file already exists\n            }\n        } catch (IOException exception) {\n            exception.printStackTrace();\n        }\n    }\n}\n```\n\nYou can also create a new file in an entirely different directory by specifying the full path inside your `File` object, like this if you're on windows.\n\n```java\nimport java.io.File;\nimport java.io.IOException;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        try {\n            File file = new File(\"C:\\Users\\myfile.txt\");\n            if (file.createNewFile()) {\n                // file created\n            } else {\n                // file already exists\n            }\n        } catch (IOException exception) {\n            exception.printStackTrace();\n        }\n    }\n}\n```\n\n### Writing to a File\n\nTo write to file, we'll need to use the `FileWriter` class.\n\n```java\nimport java.io.FileWriter;\nimport java.io.IOException;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        try {\n            File writer = new FileWriter(\"myfile.txt\");\n            writer.write(\"This is new content!\");\n            writer.close();\n        } catch (IOException exception) {\n            exception.printStackTrace();\n        }\n    }\n}\n```\n\nKeep in mind that this will write a new file entirely!\n\n### Appending to a File\n\nTo append to a file, it's almost identical to when writing to a new file, except we pass an extra parameter to the `FileWriter` constructor:\n\n```java\nimport java.io.FileWriter;\nimport java.io.IOException;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        try {\n            File writer = new FileWriter(\"myfile.txt\", true);\n            writer.write(\"This is new content being appended!\");\n            writer.close();\n        } catch (IOException exception) {\n            exception.printStackTrace();\n        }\n    }\n}\n```\n\n### Renaming a File\n\nTo rename a file, just call the `renameTo` method using two `File` instances:\n\n```java\nimport java.io.File;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        File from = new File(\"from.txt\");\n        File to = new File(\"to.txt\");\n\n        boolean success = from.renameTo(to);\n    }\n}
1\n```\n\nIt's as simple as that!\n\n### Deleting a File\n\nTo delete a file, use the `delete()` method. It will return back a boolean value indicating whether or not the deletion attempt was successful.\n\n```java\nimport java.io.File;\n\npublic class Main {\n\n    public static void main(String[] args) {\n        File file = new File(\"myfile.txt\");\n        if (file.delete()) {\n            // deleted successfully\n        } else {\n            // failure to delete\n        }\n    }\n}\n```\n\n### Checking if a File exists\n\nBefore performing a file operation, you can check if it exists using the `exists()` method which returns a boolean value indicating whether or not the file exists.\n\n```java\nimport java.io.File;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        File file = new File(\"myfile.txt\");\n        boolean exists = file.exists();\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"6d:Ta86,"])</script>
1<script>self.__next_f.push([1,"\nJava provides a useful and versatile `Date` class in its `java.time` package. This class allows us to represent moments in time and dates, and manipulate them however we want with just a few lines of code.\n\n### Creating a Date\n\nCreating a date is pretty easy. Simply create a `Date` object and print it out:\n\n```java\nimport java.util.Date;\n\npublic class Main {\n    public static void main(String[] args) {\n        Date now = new Date();\n        System.out.println(now.toString());\n    }\n}\n```\n\n```bash\nSun Dec 15 00:00:00 UTC 2019\n```\n\n### Date Formatting\n\nYou can format a date object using the `SimpleDateFormat` class and calling its `format()` method:\n\n```java\nimport java.util.Date;\nimport java.text.SimpleDateFormat;\n\npublic class Main {\n    public static void main(String[] args) {\n        Date now = new Date();\n        SimpleDateFormat format =\n new SimpleDateFormat (\"E yyyy-MM-dd 'at' hh:mm:ss a zzz\");\n\n        System.out.println(format.format(now));\n    }\n}\n```\n\n```bash\nSun 2019-12-15 at 00:00:00 AM UTC\n```\n\nIf you're curious about what those characters do and if there are any others, here are all the characters that you can use when formatting your dates:\n\n-   `G`: Era (AD/BC)\n-   `y`: Year in four digits (2020)\n-   `M`: Month (June)\n-   `d`: Day in month (17)\n-   `h`: Hour from 1-12\n-   `H`: Hour from 0-23\n-   `m`: Minute\n-   `s`: Second\n-   `S`: Millisecond\n-   `E`: Day in week (Friday)\n-   `D`: Day in year (100)\n-   `F`: Day of week in month (2nd Friday in June)\n-   `w`: Week in year (23)\n-   `W`: Week in month (3)\n-   `a`: AM/PM\n-   `k`: Hour in day from 1-24\n-   `K`: Hour from 0-11\n-   `Z`: Timezone\n\n### Unix Time\n\nUnix time is a concept in computer science that refers to the number of milliseconds that have elapsed since the arbitrarily decided midnight on January 1st, 1970. Here's how to get that value in Java:\n\n```java\nimport java.util.Date;\n\npublic class Main {\n    public static void main(String[] args) {\n        Date now = new Date();\n        System.out.println(now.getTime());\n    }\n}\n```\n\n```bash\n1576146483561\n```\n\n### Parsing Strings into Dates\n\nWhen you have a string that represents a date, you can try and parse it into one:\n\n```java\nimport java.util.Date;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\n\npublic class Main {\n    public static void main(String[] args) {\n        SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\");\n        String input = \"1990-01-01\";\n\n        try {\n            Date parsed = format.parse(input);\n            System.out.println(parsed.toString());\n        } catch (ParseException e) {\n            // error parsing\n        }\n    }\n}\n```\n\n```bash\nMon Jan 01 00:00:00 UTC 1990\n```\n"])</script>
1<script>self.__next_f.push([1,"6e:T10eb,"])</script>
1<script>self.__next_f.push([1,"\nJava makes working with math straightforward and simple. It offers the usual arithmetic operators you expect, in addition to mathematical functions and properties so that we don't need to implement them ourselves. This lets us focus on the core logic of our application.\n\n### Arithmetic Operators\n\nArithmetic operators are what you use to manipulate the value of numerical variables and numbers. Here are the ones you can use:\n\n**Addition**\n\n```java\n// adding numbers\nint cakes = 5;\nint cookies = 7;\n\nint total = cakes + cookies;\nSystem.out.println(\"Total: \" + total);\n```\n\n```bash\nTotal: 12\n```\n\n**Subtraction**\n\n```java\n// subtracting numbers\nint cakes = 14;\nint eaten = 7;\n\nint total = cakes - eaten;\nSystem.out.println(\"Total: \" + total);\n```\n\n```bash\nTotal: 7\n```\n\n**Multiplication**\n\n```java\n// multiplying numbers\nint cakes = 3;\nint people = 7;\n\nint total = cakes * people;\nSystem.out.println(\"Total: \" + total);\n```\n\n```bash\nTotal: 21\n```\n\n**Division**\n\n```java\n// dividing numbers\nint cakes = 100;\nint people = 5;\n\nint total = cakes / people;\nSystem.out.println(\"Total: \" + total);\n```\n\n```bash\nTotal: 20\n```\n\n**Modulus**\n\n```java\n// modulus operator\nint cakes = 100;\nint people = 7;\n\nint remainder = cakes / people;\nSystem.out.println(\"Remainder: \" + remainder);\n```\n\n```bash\nTotal: 14\n```\n\n### Order of Operations\n\nOrder of Operations, also known as PEMDAS, works just as you would expect, including parentheses:\n\n```java\n// order of operations\nint result = (5 * 6) + 40 / 2;\n\nSystem.out.println(\"Result: \" + result);\n```\n\n```bash\nResult: 50\n```\n\n### Math Methods\n\nJava offers many useful math methods for numbers that are commonly used in calculations.\n\n**Absolute Value**\n\nGet the absolute number of a number using the\n\n```java\nint number = -34;\nSystem.out.println(\"Number: \" + Math.abs(number));\n```\n\n```bash\nNumber: 34\n```\n\n**Floor**\n\nUse the `floor` method to round any number down to the nearest whole number:\n\n```java\ndouble number = 856.234;\nSystem.out.println(\"Number: \" + Math.floor(number));\n```\n\n```bash\nNumber: 856.0\n```\n\n**Ceiling**\n\nUse the `ceil` method to round any number up to the nearest whole number:\n\n```java\ndouble number = 856.234;\nSystem.out.println(\"Number: \" + Math.ceil(number));\n```\n\n```bash\nNumber: 857.0\n```\n\n**Natural Logarithm**\n\nYou can get the natural logarithm of a number using the `log()` function:\n\n```java\nint number = 43;\nSystem.out.println(\"Number: \" + Math.log(number));\n```\n\n```bash\nNumber: 3.7612001156935624\n```\n\n**Base-10 Logarithm**\n\nYou can get the base-10 logarithm of a number using the `log10()` function:\n\n```java\nint number = 43;\nSystem.out.println(\"Number: \" + Math.log10(number));\n```\n\n```bash\nNumber: 1.6334684555795864\n```\n\n**Maximum**\n\nGet the highest value of a set of numbers using the `max()` function:\n\n```java\nint number1 = 53;\nint number2 = 64;\nSystem.out.println(\"Number: \" + Math.max(number1, number2));\n```\n\n```bash\nNumber: 64\n```\n\n**Minimum**\n\nGet the lowest value of a set of numbers using the `min()` function:\n\n```java\nint number1 = 53;\nint number2 = 64;\nSystem.out.println(\"Number: \" + Math.min(number1, number2));\n```\n\n```bash\nNumber: 53\n```\n\n**Power**\n\nYou can calculate the value of one number risen to the power of another number using the `pow` method:\n\n```java\nint base = 5;\nint exp = 4;\n\nSystem.out.println(\"Number: \" + Math.pow(base, exp));\n```\n\n```bash\nNumber: 625.0\n```\n\n**Random**\n\nYou can get a random number between `0` and `1` using the `random()` function:\n\n```java\ndouble random = Math.random();\nSystem.out.println(\"Random: \" + random);\n```\n\n```bash\nRandom: 0.5497127671041443\n```\n\nYou can then manipulate this value to do other things like getting a random number between two other numbers, like so:\n\n```java\nint min = 4;\nint max = 29;\ndouble result = (Math.random() * ((max - min) + 1)) + min;\nSystem.out.println(\"Result: \" + result);\n```\n\n```bash\nResult: 9.63955715156336\n```\n\n**Round**\n\nYou can round a number to the nearest integer with `round()`:\n\n```java\ndouble value = 9.63955715156336;\nlong result = Math.round(value);\nSystem.out.println(\"Result: \" + result);\n```\n\n```bash\nResult: 10\n```\n\n**Square Root**\n\nYou can take the square root of a number using the `sqrt()` function:\n\n```java\nint value = 245;\ndouble result = Math.sqrt(value);\nSystem.out.println(\"Result: \" + result);\n```\n\n```bash\nResult: 15.652475842498529\n```\n"])</script>
1<script>self.__next_f.push([1,"6f:T713,"])</script>
1<script>self.__next_f.push([1,"\nJava is an object-oriented programming language. What this means is that basically everything is an object. We'll learn more about what an object is and why it's important later in this class.\n\nLet's look at how we printed `Hello World!` again:  \n\n```java\npublic class HelloWorld {\n    public static void main(String[] args) {\n        System.out.println(\"Hello World!\");\n    }\n}\n```\n\nThere's definitely a lot going on here, however for the purposes of this class, there's only a few things you need to take away from this for now:\n\n-   This code defines the `main()` method, which is the starting point for any Java program.\n-   When you run this code, the JVM(Java Virtual Machine) calls the `main()` method and executes its contents.\n-   The line `System.out.println(\"Hello World!\");` prints the message \"Hello World!\" to the console, demonstrating basic output functionality.\n-   When it comes to the syntax, every line of code in Java must end in a semicolon. Unlike some programming languages like Python, indentation doesn't matter here.\n\n### Comments in Java\n\nComments are useful in programming languages to leave yourself or another developer a note of some kind. This is also called documenting your code. Comments are entirely ignored by the compiler so they do not affect the execution or performance of your co
1de.\n\nHere's how a single-line comment looks like:\n\n```java\npublic class HelloWorld {\n    public static void main(String[] args) {\n        // this is a single-line comment!\n        System.out.println(\"Hello World!\");\n    }\n}\n```\n\nYou can leave a comment spanning multiple lines like this:\n\n```java\npublic class HelloWorld {    public static void main(String[] args) {\n        /* this is a\n           multi-line comment!\n          */\n        System.out.println(\"Hello World!\");\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"70:T1319,"])</script>
1<script>self.__next_f.push([1,"\nRegular expressions in Java are a special sequence of characters used to define a search pattern or manipulate strings. Regular expressions are extremely powerful and are used in a wide variety of applications like searching and replacing, finding numerous occurrences of a string, and for validation.\n\nJava offers us the `java.util.regex` package just for regular expressions.\n\n### Matching a Single Character\n\nYou can match a single character in a bigger string. To do so, we'll need to use the `Matcher` and `Pattern` classes:\n\n```java\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        String line = \"I pledge allegiance to the Flag of the United States of America.\";\n        String pattern = \"F\";\n\n        Pattern regex = Pattern.compile(pattern);\n        Matcher match = regex.matcher(line);\n\n        if (match.find()) {\n            System.out.println(match.group(0));\n        } else {\n            // no matches found\n        }\n    }\n}\n```\n\n```bash\nF\n```\n\nOur regular pattern was looking for any instance of the character `F`. It found a match in the word `Flag`. Calling `match.group` returned the first instance (and only instance).\n\n### Using Meta Characters\n\nWith regular expressions, we aren't limited simply to plain text for our search patterns. We can use **meta character** to enhance our patterns.\n\nLet's use a meta character to match a more complex string:\n\n```java\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        String line = \"I pledge allegiance to the Flag of the United States of America.\";\n        String pattern = \"St.tes\";\n\n        Pattern regex = Pattern.compile(pattern);\n        Matcher match = regex.matcher(line);\n\n        if (match.find()) {\n            System.out.println(match.group(0));\n        } else {\n            // no matches found\n        }\n    }\n}\n```\n\n```bash\nStates\n```\n\nIn this case, we are searching for any string that starts with `St`, ends with `tes`, with any character in the middle. In this case, the `.` matches any character. Of course, the string `States` fits the bill.\n\nHere are all the meta characters that you can use:\n\n-   `.`: Matches any character\n-   `\\d`: Matches any digit\n-   `\\D`: Matches and non-digit\n-   `\\s`: Matches any whitespace character\n-   `\\S`: Matches any non-whitespace character\n-   `\\w`: Matches any alpha character\n-   `\\W`: Matches any non-alpha character\n-   `\\b`: Matches a word boundary\n-   `\\B`: Matches a non word boundary\n\n### Replacing the first occurrence\n\nYou can use regular expressions to replace the first occurrence in a string:\n\n```java\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        String line = \"I pledge allegiance to the Flag of the United States of America.\";\n        String pattern = \"United States of America\";\n        String replace = \"Canada\";\n\n        Pattern regex = Pattern.compile(pattern);\n        Matcher match = regex.matcher(line);\n        line = match.replaceFirst(replace);\n\n        System.out.println(line);\n    }\n}\n```\n\n```bash\nI pledge allegiance to the Flag of the Canada.\n```\n\n## Replacing all occurrences\n\nYou can use regular expressions to **replace all occurrence** in a string:\n\n```java\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        String line = \"I pledge allegiance to the Flag of the United States of America.\";\n        String pattern = \"a\";\n        String replace = \"X\";\n\n        Pattern regex = Pattern.compile(pattern);\n        Matcher match = regex.matcher(line);\n        line = match.replaceAll(replace);\n\n        System.out.println(line);\n    }\n}\n```\n\n```bash\nI pledge XllegiXnce to the FlXg of the United StXtes of AmericX.\n```\n\n### Finding all occurrences\n\nYou can find all occurrences of a string, and the index in which they appear:\n\n```java\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class HelloWorld {\n    public static void main(String[] args) {\n        String line = \"I pledge allegiance to the Flag of the United States of America.\";\n        String pattern = \"of\";\n\n        Pattern regex = Pattern.compile(pattern);\n        Matcher match = regex.matcher(line);\n\n        while (match.find()) {\n            System.out.println(\"Match found (\" + match.group() + \") starting at index \" +\nmatch.start() + \" and ending at index \" + match.end());\n        }\n    }\n}\n```\n\n```bash\nMatch found (of) starting at index 32 and ending at index 34\nMatch found (of) starting at index 53 and ending at index 55\n```\n\nAnd just like that, we were able to get the starting and ending index of every occurrence of that search pattern in our search string.\n"])</script>
1<script>self.__next_f.push([1,"71:Tff7,"])</script>
1<script>self.__next_f.push([1,"\nVariables are a fundamental part of any programming language, including Java. Variables are used to store pieces of data and give them a name. When we want to use these variables in some way, we can refer to them by their name.\n\n### Data Types\n\nDefine the kind of data a variable can hold and the operations that can be performed on it. Java has two main categories of data types:\n\n1.  Primitive Data Types:\n2.  Non-Primitive Data Types (Reference Types)  \n    \n\n#### Primitive Data Types\n\nLet's explore the primitive types of data that variables can hold.\n\n| Type | Description | Storage space |\n| --- | --- | --- |\n| byte | Store whole number between -128 and 127. Useful for memory-efficient storage of small integers | 8 bits (1 byte) |\n| short | Store whole number between -32,768 and 32,767. Used for larger integer values than those held by byte | 16 bits (2 bytes) |\n| int | The most common integer type, storing whole numbers from -2,147,483,648 and 2,147,483,647 | 32 bits (4 bytes) |\n| long | Stores even larger whole numbers, between -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 64 bits (8 bytes) |\n| float | Represents single-precision floating-point numbers (numbers with decimals). Used for approximate real numbers where precision isn't critical. | 32 bits (4 bytes) |\n| double | Represents double-precision floating-point numbers, offering more precision than float. Used for accurate scientific calculations or measurements. | 64 bits (8 bytes) |\n| char | Stores a single unicode character. Used for representing text and symbols. | 16 bits (2 bytes) |\n| boolean | Represents logical values: true or false. It is used for conditional statements and decision-making. | 1 bit (but occupies 1 byte in memory for efficiency) |\n\n#### Non-Primitive Data Types (Reference Types)\n\nThe reference types are the objects or instances of classes. Some of the Non-Primitive Data Types in Java includes:\n\n-   String (not a primitive, but a common reference type)  \n    \n-   Arrays\n-   Classes\n-   Interfaces\n\nNow that we know the data types supported in Java, let's declare our variables.\n\n### Types of Variables:\n\n-   **Local Variables:** Declared within a method or block, accessible only within that scope.  \n    \n-   **Instance Variables:** Declared within a class, outside of any method, each object of the class has its own copy.\n-   **Static Variables:** Declared with the static keyword, shared by all objects of the class.\n\n### Declaring\n\nDeclaring a variable is how you create them. Here's an example featuring all of the primitive data types:\n\n```java\npublic class HelloWorld {\n    public static void main(String[] args) {\n        byte b = 6;\n        System.out.println(b);\n\n        short c = 1337;\n        System.out.println(c);\n\n        int d = 12345;\n        System.out.println(d);\n\n        long e = 13371337;\n        System.out.println(e);\n\n        float f = 13.37f;\n        System.out.println(f);\n\n        double g = 13.37;\n        System.out.println(g);\n\n        char h = 'a';\n        System.out.println(h);\n\n        boolean i = true;\n        System.out.println(i);\n    }\n}\n```\n\n```bash\n6\n1337\n12345\n13371337\n13.37\n13.37\na\ntrue\n```\n\nIn general, to declare a variable, you must start off with their type, then an equal sign, then the value. This is the general syntax:\n\n```java\ntype name = value;\n```\n\nSince Java is strongly typed, it requires you to give every variable their type.\n\n### Variable Naming Rules\n\nThere are rules in place for naming Java variables, and here they are:\n\n-   The variable name can only contain alphanumeric characters, underscores, and dollar signs\n-   The variable name must start with a letter, dollar sign, or underscore\n-   The variable name cannot contain spaces\n\nWith that in mind, here are some examples of valid Java variable names:\n\n```java\napples\n_apples\n_apples_\n$apples\n```\n\nAnd here are some examples of invalid Java variables names:\n\n```java\n1apples\napp les\n\u0026apples\n%apples\n```\n\nKeep in mind that variable names are case-sensitive. Also, reserved keywords cannot be used as variable names since they will clash.\n"])</script>
1<script>self.__next_f.push([1,"72:Ta2e,"])</script>
1<script>self.__next_f.push([1,"\nMethods, sometimes called functions, are blocks or sections of code, usually named, that can be executed over and over again. methods are great for reducing duplication of code, improving readability, and reducing complexity. Divide up larger chunks of code so that they become easier to manage.\n\n### Creating a method\n\nLet's look at a method that simply prints out a greeting:\n\n```java\npublic static void introduction() {\n    System.out.println(\"Hello, my name is Jackie.\");\n}\n```\n\nYou can ignore what `public` and `static` means for now. The important part to take away is the return type is `void`. Methods can return things back to you, like a `String` or `int`, but in this case, we are only printing some text, so we can set the method to return nothing.\n\nFinally we just have the actual code that is being run, the print statement.\n\n### Invoking a method\n\nNow that we have defined our method, we just need to invoke or call it. This causes the method to execute:\n\n```java\npublic class Main {\n\n    public static void main(String[] args) {\n        introduction();\n    }\n\n    public static void introduction() {\n        System.out.println(\"Hello, my name is Jackie.\");\n    }\n}\n```\n\n```bash\nHello, my name is Jackie.\n```\n\nThis is cool and all, but what if you wanted to customize the name instead of it being hardcoded?\n\n### Parameters\n\nParameters are pieces of data you can pass into a method that you can then use to perform that method's task. In this case, we want to customize the name that appears, so let's add the name as a parameter:\n\n```java\npublic class Main {\n\n    public static void main(String[] args) {\n        introduction(\"Nia\");\n    }\n\n    public static void introduction(String name) {\n        System.out.println(\"Hello, my name is \" + name + \".\");\n    }\n}\n```\n\n```bash\nHello, my name is Nia.\n```\n\n### Return Types\n\nAs mentioned before, methods can optionally return something back to you. In Java, `void` makes it so that it returns nothing, but setting it with a type makes it return that type.\n\nLet's look at the getting the area of a triangle:\n\n```java\npublic class Main {\n\n    public static void main(String[] args) {\n        int sideLength = 3;\n        int area = getAreaOfSquare(sideLength);\n\n        System.out.println(area);\n    }\n\n    public static int getAreaOfSquare(int side) {\n        return side * side;\n    }\n}\n```\n\n```bash\n9\n```\n\nWe created a method called `getAreaOfSquare()` that takes the side length of a square. It then calculates the area and returns it as an `int`. Now we use that value to set the value of the variable named `area` which we then print out.\n"])</script>
1<script>self.__next_f.push([1,"73:T892,"])</script>
1<script>self.__next_f.push([1,"\nOne of the most common collections in Java are arrays. Arrays can be thought of as simply a list of data, and that data can take the form of numbers, strings, objects, even arrays themselves.\n\n### Defining an Array\n\n**Creating** an array in Java is pretty straightforward. Let's create one that contains strings:\n\n```java\nString[] colors = { \"red\", \"green\", \"blue\" };\n```\n\nThat right there is an array of 3 `string` elements assigned to the variable `colors`.\n\nArrays in Java have a set size. You can either initialize it like previously shown, or like this:\n\n```java\nString[] colors = new String[3];\n```\n\nIn both cases, an array of size `3` is created.\n\n### Retrieve Array Element\n\nNow that we can create arrays, let's learn how to get an element back when we want to use it. Arrays in Java start counting from `0`. This means that the 3rd element in the array has an index of `2`.\n\nWith this in mind, let's get the second element from our original array:\n\n```java\nString[] colors = { \"red\", \"green\", \"blue\" };\n\nSystem.out.println(colors[1]);\n```\n\n```bash\ngreen\n```\n\nYou can take this further and print the entire array, like this:\n\n```java\nString[] colors = { \"red\", \"green\", \"blue\" };\n\nfor (int i = 0; i \u003c colors.length; i++) {\n    System.out.println(colors[i]);\n}\n```\n\n```bash\nred\ngreen\nblue\n```\n\nWe simply iterate through all the values between `0` and the length of the array to get every element in that array.\n\n### Array Reassignment\n\nOnce you have initialized an array with values, you can modify each individual element pretty easily. Simply **reassign** the element's value like you would any variable:\n\n```java\nString[] colors = { \"red\", \"green\", \"blue\" };\ncolors[1] = \"yellow\"; // reassignment\n\nfor (int i = 0; i \u003c colors.length; i++) {\n    System.out.println(colors[i]);\n}\n```\n\n```bash\nred\nyellow\nblue\n```\n\n### Sorting Array\n\nYou can easily sort a Java array by calling the `sort()` method:\n\n```java\nString[] colors = { \"red\", \"green\", \"blue\" };\nArrays.sort(colors);\n\nfor (int i = 0; i \u003c colors.length; i++) {\n    System.out.println(colors[i]);\n}\n```\n\n```bash\nblue\ngreen\nred\n```\n\nKeep in mind that you might need to import the Arrays class, like this: `import java.util.Arrays;`\n"])</script>
1<script>self.__next_f.push([1,"74:T1da4,"])</script>
1<script>self.__next_f.push([1,"\nWhen writing code in any programming language, you will need to account for situations where you need to decide on a path to take given the value of the variables at that point in time. Your program needs to compare values to each other to decide what code to run next. This is called logic.\n\nLet's look at the comparison operators at our disposal in Java!\n\n### Equality Operator\n\nThe **equality operator** is the most basic of comparison operators. If the two values being tested are the same, the result will be `true`, otherwise, the result will be `false`.\n\nTo use this operator, use **two equal signs**:\n\n```java\nSystem.out.println(3 == 4);\nSystem.out.println(6 == 6);\nSystem.out.println(43 == 454);\n```\n\n```bash\nfalse\ntrue\nfalse\n```\n\nIf you want to check strings for equality, use the `equals()` method, like this:\n\n```java\nboolean equal = string1.equals(string2);\n```\n\n### Inequality Operator\n\nThe inequality operator is the exact opposite of the equality operator. If the two values being tested are the same, the result will be `false`. Otherwise, if the values are different, the result will be `true`.\n\nTo use this operator, use an exclamation point, followed by an equal sign.\n\n```java\nSystem.out.println(3 != 4);\nSystem.out.println(6 != 6);\nSystem.out.println(43 != 454);\n```\n\n```bash\ntrue\nfalse\ntrue\n```\n\n### Greater Than and Less Than Operators\n\nYou can check if one value is greater than or less than another using the greater than and less than operators.\n\nThis is how you use them:\n\n```java\nSystem.out.println(3 \u003e 4);\nSystem.out.println(6 \u003c 6);\nSystem.out.println(43 \u003c 454);\n```\n\n```bash\nfalse\nfalse\ntrue\n```\n\n### Or Equal To Operators\n\nIn the case where you need to check either that the values are equal or that one is less than/greater than another value, there is a specific operator for just that.\n\nThis is how you can use the greater than or equal to operator and the less than or equal to operators:\n\n```java\nSystem.out.println(3 \u003e= 4);\nSystem.out.println(6 \u003c= 6);\nSystem.out.println(43 \u003c= 454);\n```\n\n```bash\nfalse\ntrue\ntrue\n```\n\n### Conditionals\n\nWith the ability to return `true` or `false` now, we can now try and act on these values. We can do this by utilizing what are called conditionals.\n\n#### If Conditional\n\nUsing `if` is very simple. If the condition inside is `true` then the code block will run. If it is `false`, the code block will not run.\n\nLet's say if you eat 3 burgers or more, you win a competition.\n\n```java\nint burgersEaten = 4;\n\nif (burgersEaten \u003e= 3) {\n    System.out.println(\"You've won the competition!\");\n}\n```\n\n```bash\nYou've won the competition!\n```\n\nBut watch what happens if you do not eat at least `3` burgers:\n\n```java\nint burgersEaten = 2;\n\nif (burgersEaten \u003e= 3) {\n    System.out.println(\"You've won the competition!\");\n}\n```\n\nNothing was printed. That is because the condition inside the `if` block resulted in `false`. The code block was skipped entirely and thus the line to print it never executed.\n\n#### Else\n\nWith the `else` keyword, you can run block of code if the accompanying `if` condition returned `false`.\n\nLet's see how this looks in action:\n\n```java\nint burgersEaten = 2;\n\nif (burgersEaten \u003e= 3) {\n    System.out.println(\"You've won the competition!\");\n} else {\n    System.out.println(\"You've lost the competition. :(\");\n}\n```\n\n```bash\nYou've lost the competition. :(\n```\n\nSimply put, the because the first `if` returned `false`, the first block of code was skipped, leaving the second block of code to run.\n\nNow what if you wanted to have multiple code paths instead?\n\n#### Else If\n\nThis is where `else if` comes in to play. These keywords are sandwiched after an `if` and before the `else`:\n\n```java\nint burgersEaten = 2;\n\nif (burgersEaten \u003e= 3) {\n    System.out.println(\"You've won the competition!\");\n} else if (burgersEaten == 2) {\n    System.out.println(\"You almost won the competition!\");\n} else if (burgersEaten == 1) {\n    System.out.println(\"You gave it a good try!\");\n} else {\n    System.out.println(\"You didn't come close. :(\");\n}\n```\n\n```bash\nYou almost won the competition!\n```\n\nWhen you use `if` and `else if`, the first block of code where the condition is `true` will run, and the rest will be ignored entirely, so order does matter!\n\n#### Ternary Operator\n\nThe ternary operator is a shorthand way to represent an `if/else` block. It checks a condition and if `true`, returns the left side, otherwise it will return the right side.\n\n```java\nint number = 45;\nboolean isEven = number % 2 == 0 ? true : false;\n\nSystem.out.println(\"isEven: \" + isEven);\n```\n\n```bash\nfalse\n```\n\nTernary operators are really useful for when you want to condense an entire conditional into a single line.\n\n### Switch Statement\n\nYou can use a switch statement whenever you want to check for many different possible values of something, and run code if there is a match. They are similar to using `else if` except they can sometimes be more concise and cleaner.\n\nLet's look at one:\n\n```java\nint number = 4;\nswitch (number) {\n    case 1:\n        System.out.println(\"one\");\n        break;\n    case 2:\n        System.out.println(\"two\");\n        break;\n    case 3:\n        System.out.println(\"three\");\n        break;\n    case 4:\n        System.out.println(\"four\");\n        break;\n    case 5:\n        System.out.println(\"five\");\n        break;\n}\n```\n\n```bash\nfour\n```\n\nThe basic syntax is simple. You put what you want to switch on after the `switch` keyword, then you list all your cases below. If there is a match, the code inside will be executed. Once there is a match, the `break` ensures that once the block of code is run, no more checks are performed.\n\n### Logical Operators\n\nSo far we have seen how to check a 
1single condition and then do something with the result. In the real world, you will often times need to combine the results of multiple conditions before you can make your decision.\n\nTo combine the results of more than one condition, you will need to use a **logical operator**.\n\n#### And (\u0026\u0026)\n\nThe and operator, will only result in `true` if both conditions are `true`:\n\n```java\nboolean isCold = true;\nboolean hasJacket = true;\n\nif (isCold \u0026\u0026 hasJacket) {\n    System.out.println(\"I will put on my jacket since I am cold!\");\n}\n```\n\n```bash\nI will put on my jacket since I am cold!\n```\n\nSince both of the conditions were `true`, the code block executed.\n\n#### Or (||)\n\nSometimes you don't need both conditions to be `true` and instead are okay with just one of the two being `true`. This is where the **or** logical operator comes in to play.\n\n```java\nboolean thereAreTacos = true;\nboolean thereIsPizza = false;\n\nif (thereAreTacos || thereIsPizza) {\n    System.out.println(\"I'm glad there's good food here!\");\n}\n```\n\n```text\nI'm glad there's good food here!\n```\n\nEven though in this case there was no pizza in the house, because there were still tacos, the print statement executed and you were very happy as a result. ??????\n\n#### Not (!)\n\nThe last logical operator we'll take a look at is the **not** operator. This is used when you simply want to negate the value of the condition.\n\nLet's look at an example:\n\n```java\nboolean thereAreTacos = false;\nboolean thereIsPizza = false;\n\nboolean thereIsGoodFood = thereAreTacos || thereIsPizza;\n\nif (!thereIsGoodFood) {\n    System.out.println(\"There is no good food here :(\");\n}\n```\n\n```text\nThere is no good food here :(\n```\n\nIn this case, there were neither tacos nor pizza. That made `thereIsGoodFood` to be `false`. However, since we used the not operator to negate it, the entire condition was `true` and we were able to get the print statement to execute!\n"])</script>
1<script>self.__next_f.push([1,"75:T1333,"])</script>
1<script>self.__next_f.push([1,"\nLoops are a fundamental part of programming languages, and definitely for Java. Loops are extremely powerful, allowing you to condense blocks of code, and making things more readable. If you ever find yourself copy and pasting code because you need to repeat their execution, chances are you instead should be using a loop to accomplish that task.\n\nLet's look at all the different kinds of loops we can use.\n\n### For Loop\n\n**The for loop is the classic loop, and probably the most commonly used one. It is made up of three different parts:**\n\n-   **Initial Value**: This is the inital value set to the variable we will use to control the loop's progression, usually `i`.\n-   **Condition**: This condition is checked before running the next iteration of the loop.\n-   **Iteration**: This part is how you advance further in the loop.\n\nLet's look at loops by showing how to print the numbers `1` to `10`:\n\n```java\nfor (int i = 1; i \u003c= 10; i++) {\n    System.out.println(i);\n}\n```\n\n```bash\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n```\n\nSo first we initialize our variable `i` to be `1`. That way when the first print statement is executed, the value `1` is printed. Then we increment the value of it thanks to:\n\n```java\ni++\n```\n\nThis will keep on going until `i` exceeds the value of `10`. When that happens, the loop stops executing and we finish our printing.\n\n### While Loop\n\nA while loop is a much simpler but equally as powerful loop when compared to a for loop. The structure of a while loop is just a single condition that if it evaluates to `true` will cause it it to execute. The condition is checked at the end of an iteration and will continue until the condition eventually results in a `false`.\n\nLooks look at the same example as before but with a while loop instead:\n\n```java\nint i = 1;\n\nwhile (i \u003c= 10) {\n    System.out.println(i);\n    i++;\n}\n```\n\n```bash\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n```\n\nThe functionality is exactly the same just using a different loop. We are defining the same variable and giving it the same initial value, `1`. From there we check that `i` is equal to or less than `10`. If so, we execute the print statement and increment the value of `i`. This repeats until the value of `i` reaches `11` and the loop terminates.\n\n## Do While Loop\n\nThe do while is exactly the same as a normal while loop except that the code block in the loop is guaranteed to run at least once no matter what the condition results in. This can be useful for when you want the code to run once, then repeat it if the condition is `true`.\n\nLet's look at an example:\n\n```java\nint cupcakes = 5;\n\ndo {\n    System.out.println(\"Since there are still \" + cupcakes + \" cupcakes left, I'll eat one.\");\n    cupcakes--;\n} while (cupcakes \u003e 0);\n\nSystem.out.println(\"All cupcakes gone!\");\n```\n\n```bash\nSince there are still 5 cupcakes left, I'll eat one.\nSince there are still 4 cupcakes left, I'll eat one.\nSince there are still 3 cupcakes left, I'll eat one.\nSince there are still 2 cupcakes left, I'll eat one.\nSince there are still 1 cupcakes left, I'll eat one.\nAll cupcakes gone!\n```\n\nOn the first pass, the code is executed without checking the condition. We eat a cupcake, and then the condition is checked. Since cupcakes remained, the loop executed again. This process repeated itself until finally we ran out of cupcakes. When this happened, the code continued to execute to the final print statement letting us know that the cupcakes officially ran out.\n\n### Break\n\nThe `break` statement is useful when you want to end a loop prematurely for any reason you want. Let's say counting to `10` like before but use a `break` to stop the loop for no reason:\n\n```java\nfor (int i = 1; i \u003c= 10; i++) {\n    System.out.println(i);\n\n    if (i == 5) {\n        break;\n    }\n}\n```\n\n```bash\n1\n2\n3\n4\n5\n```\n\nEven though this loop would have continued printing up until the number `10`, to demonstrate the power of `break` statements, we used it once the value of `i` was `5`. At that point, we exited the loop and no further print statements executed.\n\n### Continue\n\nThe `continue` statement is similar to the `break` except that instead of ending the loop entirely, it continues to the next iteration of the loop. This is useful for when you don't want to run the rest of the loop's code block, but you also don't want to terminate the loop entirely.\n\nLet's look at it in action:\n\n```java\nfor (int i = 1; i \u003c= 10;
1 i++) {\n    if (i == 2 || i == 6) {\n        continue;\n    }\n    System.out.println(i);\n}\n```\n\n```bash\n1\n3\n4\n5\n7\n8\n9\n10\n```\n\nFor absolutely no particular reason, we have decided that when the value of `i` is either `2` or `6`, we will continue on to the next iteration of the loop, instead of printing the value out. \n\nBecause of this, we still got the other values printed out as expected, but at the same time, the entire loop didn't terminate. Knowing when to use `break` and `continue` can make already powerful loops even more powerful!\n"])</script>
1<script>self.__next_f.push([1,"76:Tcab,"])</script>
1<script>self.__next_f.push([1,"\nJava is an object-oriented programming language. What this means is that basically everything in Java can be thought of as an object. An object is a collection of properties and methods that describe a single entity. A class is a blueprint for creating those objects.\n\n### Creating a Class\n\nCreating a class is simple. Simply use the `class` keyword and then give it a name.\n\nLet's create a `Pet` class inside `Pet.java`:\n\n```java\npublic class Pet {\n\n}\n```\n\nThat's it, a class is defined. Of course, it is empty, so let's give it some properties to work with:\n\n```java\npublic class Pet {\n    String name;\n    int weight;\n}\n```\n\nGreat, now that we have two properties that make up a pet, let's create objects using this class.\n\n### Creating an Object\n\nOnce we have a class defined, creating an object is easy, just use the `new` keyword, like this:\n\n```java\nPet pet = new Pet();\n```\n\nWe now have an object of type `Pet`. We still haven't actually been able to set the values of `name` and `weight` just yet, so let's do that now.\n\n### Using a Constructor\n\nA constructor is a special method that literally constructs an object given the parameters you pass in. If all we want to do is set the value of `name` and `weight`, this is how the class would look like:\n\n```java\npublic class Pet {\n    String name;\n    int weight;\n\n    Pet(String name, int weight) {\n        this.name = name;\n        this.weight = weight;\n    }\n}\n```\n\nThe constructor takes in the parameters needed to build the object, initializes the values it needs to, and then returns an instance of that class which essentially is now a separate object.\n\nNow you can create a new `Pet` object like this:\n\n```java\nPet pet = new Pet(\"Scooby\", 4);\n```\n\nLet's throw a method in this class so we can see our objects in action.\n\n```java\npublic class Main {\n\n    public static class Pet {\n        String name;\n        int weight;\n\n        Pet(String name, int weight) {\n            this.name = name;\n            this.weight = weight;\n        }\n\n        void printInfo() {\n            System.out.println(\"Name: \" + name + \" Weight: \" + weight + \" pounds.\");\n        }\n    }\n\n    public static void main(String[] args) {\n        Pet pet = new Pet(\"Scooby\", 4);\n        pet.printInfo();\n    }\n}\n```\n\n```bash\nName: Scooby Weight: 4 pounds.\n```\n\nThis is all in one file for the sake of example but in practice this should probably be in two files like `Pet.java` and `Main.java`.\n\n### Multiple Objects\n\nBecause classes are just blueprints for objects, we can create multiple objects without any interference between each other. Let's create multiple pets to illustrate this:\n\n```java\npublic class Main {\n\n    public static class Pet {\n        String name;\n        int weight;\n\n        Pet(String name, int weight) {\n            this.name = name;\n            this.weight = weight;\n        }\n\n        void printInfo() {\n            System.out.println(\"Name: \" + name + \" Weight: \" + weight + \" pounds.\");\n        }\n    }\n\n    public static void main(String[] args) {\n        Pet scooby = new Pet(\"Scooby\", 4);\n        scooby.printInfo();\n\n        Pet spark = new Pet(\"Spark\", 6);\n        spark.printInfo();\n    }\n}\n```\n\n```bash\nName: Scooby Weight: 4 pounds.\nName: Spark Weight: 6 pounds.\n```\n"])</script>
1<script>self.__next_f.push([1,"77:T538,\nJava packages are used to organize our code and to avoid naming conflicts. Packages strongly resemble folders like the ones found in file directory. Every package has a unique name so that class names can still be duplicated and still be used properly if you import it from the right package. There are two kinds of packages, the built-in ones and the ones you can create yourself.\n\n### Creating a Package\n\nCreate a package using the `package` keyword, and then the name of the package. Ensure that this is the top of the file.\n\n```java\npackage devices;\n\npublic class Phone {\n    private String name;\n\n    public Phone(String name) {\n        this.name = name;\n    }\n\n    public int getName() {\n        return name;\n    }\n}\n```\n\nThis class now lives inside the `devices` package.\n\n### Importing Package\n\nYou can import a class of your choosing by using the `import` keyword and specifying the exact package and class name:\n\n```java\nimport java.lang.Math;\n```\n\nThat, for example, imports the `Math` class only. This makes everything from `Math` available in whatever class you imported it into.\n\nIf you find yourself using multiple classes from the same package, you can just import an entire package to get all the classes inside available:\n\n```java\nimport java.lang.*;\n```\n\nThis imports all the classes inside the `java.lang` package.\n78:T155b,"])</script>
1<script>self.__next_f.push([1,"\n**Python** is a general-purpose, dynamic, interpreted and object-oriented programming language. It is one of the most popular and fastest growing programming languages in the world. It is used in wide variety of applications including web development, data analysis, and running background tasks.\n\nPython has a simple, easy to learn syntax, which emphasizes readability. Applications written in Python can run on almost any computer, including those running Windows, macOS, and all popular Linux distributions. The Python ecosystem has grown over the years and contains a wide range of development tools for writing, debugging, and publishing Python applications.\n\n## Prerequisites\n\n1.  A computer that can install and run Python.\n2.  A desire to learn how to code!\n\nWith that being said, let's get started!\n\n## Python Interpreter\n\nPython is an interpreted language, which reduces the edit-test-debug cycle because there's no compilation step required. In order to run Python apps, you need a runtime interpreter to execute the code.\n\nThe python code is compiled into a lower-level, and platform-independent byte code. The byte code compilation happens internally and hidden from developer.\n\nThe byte code then gets picked up by the Virtual Machine and executes the **byte code** instructions step by step to carry out their operations.\n\n![](/media/https://sgp1.digitaloceanspaces.com/stacktips/media/uploads/summernote/01_02.png)  \n\n## Installing Python\n\nIf you already have Python installed, you can skip this section. Otherwise, install the latest version of **Python 3**.\n\nHead over to the [downloads page](https://www.python.org/downloads/) to get your copy.\n\nPlease note that, Python comes bundled with Mac OS X. But the version that you have is quite likely an older version. [Download](http://www.python.org/download/mac/) and install the the latest binary version of Python that runs on both Power PC and Intel systems.\n\n  \n![](/media/https://sgp1.digitaloceanspaces.com/stacktips/media/uploads/summernote/01-python.png)\n\nYou can verify the installation by running the following command on your terminal.\n\nAlternatively, you can type:\n\n```bash\npython3 -V\n```\n\nThis command will simply print the Python version installed in your computer.\n\n```bash\npython -V\nPython 3.10.6\n```\n\n## Writing Your First Python Program\n\nCreate a new file titled `helloworld.py`. Inside the file, put this code in::\n\n```python\nprint(\"Hello world!\")\n```\n\nTo run the program, type `python3 helloworld.py` command and hit Return.\n\n```bash\n$ python3 helloworld.py\nHello World!\n```\n\nCongratulations! You just wrote your first program in Python. As you can see, this was a pretty easy task. This is the beauty of the Python programming language.\n\n## Python Implementations\n\nPython is licensed under OSI open source license and there are multiple implementations available depending upon your requirements.\n\n-   **CPython:** Commonly used for web development, application development and scripting.\n-   **Anaconada:** This distribution is used for scientific programming tasks such as data schience and machine learning.\n-   **Iron Python:** Open source implementation built for .NET runtime\n-   **Jupyter Notebook:** Jupyter Notebook is a web-based interactive programming environment that supports various programming languages, including Python. Used mainly for academic research and mathematical modeling, machine learning and for teaching.\n\nYou now have everything you need to begin this class on Python! Let's get started with Python!\n\n## Python Syntax and Indentation\n\nIndentation refers to the space used at the beginning of a code to improve readability. Unlike any other programming language, indentation in python is very important as it uses indentation to indicate a block of code.  \n\nFor example, if we're writing a conditional statement using if statement, here's how we use spaces to indent the code.\n\n```python\nif True:\n    print(\"True\")\nelse:\n    print(\"False\")\n```\n\n```text\nTrue\n```\n\nIf you're familiar with any other programming language like Java, or .NET, they use curly braces to indicate a code block. However, for Python you do not require curly braces, instead you're required to use indent your co
1de adequately.\n\nHere are examples of broken syntax in Python:\n\n```python\nif True:\nprint(\"True\")\nelse:\nprint(\"False\")\n```\n\n```python\nif True:\n    print(\"True\")\n        print(\"True\")\n            print(\"True\")\n```\n\nFor all the same reasons, code in Python needs to be perfectly indented or else it will not run.\n\n## Comments in Python  \n\nAt some point down the road, you will want to leave comments in your code, either for yourself in the future, or for another developer working on the same project as you. Here is how comments in Python look like:\n\n```python\n# First comment\nprint(\"Hello world!\") # second comment\n```\n\n```text\nHello world!\n```\n\nFairly straightforward! Comments in Python start with the # character and the following is the comment itself. Unlike most programming languages, Python does not support multi-line comments. However, nothing technically stops you from doing this:\n\n```python\n# This\n# is\n# a\n# multi-line\n# comment\nprint(\"Hello world!\")\n```\n\n```text\nHello world!\n```\n\nThis works but keep in mind that comments in general should be short anyway, so using multi-line comments should be done sparingly, if at all.\n\n## References\n\n-   [Python Homepage](https://www.python.org/)\n-   [Python Downloads Page](https://www.python.org/downloads/)\n"])</script>
1<script>self.__next_f.push([1,"79:T12aa,"])</script>
1<script>self.__next_f.push([1,"\nLists are used to store collection of items in a single variable. They are very similar to what other programming languages call Arrays.\n\nItems stored in the list are ordered and changeable and can contain duplicates. List can contain any number of items and of any type.\n\nLists are created using square brackets:\n\n## Creating a List\n\nLet us define a list to store all the days in a week:\n\n```python\nweek = [\"Sunday\", \"Monday\", \"Tuesday\",\n         \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\nprint(week)\n```\n\n**Output:**\n\n```text\n['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n```\n\n## Accessing List Items\n\nThe syntax for **accessing** an item is also pretty standard, simply provide the **index** of the item you want to access. Note that the first item has an index of `0`:\n\n```python\nweek = [\"Sunday\", \"Monday\", \"Tuesday\",\n         \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n\nprint(week[0])   # prints Sunday\nprint(week[1])   # prints Monday\n```\n\nYou can use the negative index to access the items from the end of the list. For example.\n\n```python\nweek = [\"Sunday\", \"Monday\", \"Tuesday\",\n         \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\nprint(week[-1])    # prints Saturday\n```\n\n## Changing Items\n\nLists defined in python are mutable. This means, we can update the values for a given index.\n\n```python\nweek = [\"Sunday\", \"Monday\", \"Tuesday\",\n         \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n\nweek[1] = \"MONDAY\"\nprint(week)\n```\n\n**Output:**\n\n```text\n['Sunday', 'MONDAY', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n```\n\n## Appending Items to List\n\nYou can append item to list using the built in `append()` function. This method will add the new item to the end of the list.\n\n```python\nanimals = [\"elephant\", \"tiger\", \"lion\"]\nprint(animals)\n\nanimals.append(\"bear\")\nprint(animals)\n```\n\n**Output:**\n\n```text\n['elephant', 'tiger', 'lion']\n['elephant', 'tiger', 'lion', 'bear']\n```\n\n## Deleting Items from List\n\nIf you want to remove an item from the list, you can do that using the built in `del` function and passing in the index.\n\n```python\nanimals = [\"elephant\", \"tiger\", \"lion\", \"bear\"]\nprint(animals)\n\ndel(animals[1])\nprint(animals)\n```\n\n**Output:**\n\n```text\n['elephant', 'tiger', 'lion', 'bear']\n['elephant', 'lion', 'bear']\n```\n\nAlternatively, you can use the delete the item form list using the item value using the `remove` method:\n\n```python\nanimals = [\"elephant\", \"tiger\", \"lion\", \"bear\"]\nprint(animals)\n\nanimals.remove(\"tiger\")\nprint(animals)\n```\n\n**Output:**\n\n```text\n['elephant', 'tiger', 'lion', 'bear']\n['elephant', 'lion', 'bear']\n```\n\n## Looping through a List\n\nLooping through a list is a very common operation and Python luckily makes this easy to do:\n\n```python\nweek = [\"Sunday\", \"Monday\", \"Tuesday\",\n         \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\nfor day in week:\n    print(day)\n```\n\n**Output:**\n\n```text\nSunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\n```\n\n## Checking if an Item Exists in List\n\nSometimes you might be working with huge lists or not even know what is inside the list, in the case of lists being returned from methods.\n\nYou can very easily check if a list contains a value you want, like this:\n\n```python\nweek = [\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n\nprint(\"Monday\" in week)\n```\n\n**Output:**\n\n```text\nTrue\n```\n\n## How to Check Length of a List?\n\nYou can check the length of the list by using the `len()` function:\n\n```python\nweek = [\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n\nprint(len(week))\n```\n\n**Output:**\n\n```text\n7\n```\n\n## How to Join Two Lists?\n\nPython has a simple syntax for combining lists, use the `+` operator\n\n```python\nna = [\"USA\", \"Canada\", \"Mexico\"]\neu = [\"UK\", \"France\", \"Germany\"]\n\ncountries = na + eu\nprint(countries)\n```\n\n**Output:**\n\n```text\n['USA', 'Canada', 'Mexico', 'UK', 'France', 'Germany']\n```\n\n## Reverse a List\n\n**Reverse** the order of the items in a list using the `reverse` function:\n\n```python\nweek = [\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n\nprint(week)\nweek.reverse()\nprint(week)\n```\n\n**Output:**\n\n```text\n['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n['Saturday', 'Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday', '
1Sunday']\n```\n\n## Sort a list\n\nYou can easily **sort** a list using the built-in `sort` function:\n\n```python\nweek = [\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n\nprint(week)\nweek.sort()\nprint(week)\n```\n\n**Output:**\n\n```text\n['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n['Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday']\n```\n"])</script>
1<script>self.__next_f.push([1,"7a:Tb5b,"])</script>
1<script>self.__next_f.push([1,"\nA tuple represents a sequence of any objects separated by commas and enclosed in parentheses. A tuple is an **immutable** object, which means it cannot be changed, and we use it to represent fixed collections of items.\n\n## Creating a Tuple\n\n**Creating** a tuple is very similar to creating a list, unlike the lists where the values are enclosed with in the brackets, tuples use parenthesis.\n\n```python\nweek = (\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\nprint(week)\n```\n\n**Output:**\n\n```text\n('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')\n```\n\n## Accessing items in a Tuple\n\nYou can access an item in a tuple in the same way you do with lists:\n\n```python\nweek = (\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\nprint(week[1]) # Prints Monday\n```\n\nSimilar to list, we can also use negative indexes for accessing the elements from reverse order.\n\n```python\nweek = (\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\nprint(week[-1])  # Prints Saturday\n```\n\n## Looping through a Tuple\n\nHere is how to iterate through a tuple:\n\n```python\nweek = (\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\nfor day in week:\n    print(day)\n```\n\n**Output:**\n\n```text\nSunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\n```\n\n## Check if Item Exists in Tuple\n\nYou can check if an item exists in a tuple like this:\n\n```python\nweek = (\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\nprint(\"Monday\" in week)\nprint(\"Sat\" in week)\n```\n\n**Output:**\n\n```text\nTrue\nFalse\n```\n\n## Tuple Length\n\nGet the length of a tuple using the built-in `len` function:\n\n```python\nweek = (\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\nprint(len(week))\n```\n\n**Output:**\n\n```text\n7\n```\n\n## Combine Multiple Tuples\n\nEven though tuples are immutable, you can still combine them to create a third entirely new tuple. This is how:\n\n```python\nna = (\"USA\", \"Canada\", \"Mexico\")\neu = (\"UK\", \"France\", \"Germany\")\n\ncountries = na + eu\nprint(countries)\n```\n\n**Output:**\n\n```text\n('USA', 'Canada', 'Mexico', 'UK', 'France', 'Germany')\n```\n\n## Converting a Tuple into a List\n\nWhen the situation arises that you indeed must make changes to the tuple, Python gives you the option to convert it to a list instead. Use the `list()` function to do just that:\n\n```python\nweek = (\"Sunday\", \"Monday\", \"Tuesday\",\n        \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\nprint(week)\nweek_list = list(week)\nprint(week_list)\n```\n\n**Output:**\n\n```text\n('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')\n['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n```\n\nThe second output enclosed with in the brackets indicate that it is a list and not a tuple!\n"])</script>
1<script>self.__next_f.push([1,"7b:Ta5b,"])</script>
1<script>self.__next_f.push([1,"\nExceptions are errors in our program that causes Python to stop and display an error message. Exceptions are handled using the try-except-finally block.\n\n## Exception Handling\n\nAs mentioned before, we handle exceptions using the try-except-finally block. The `try` block is where you put the code that could potentially throw an exception. The `except` block is where you can gracefully perform an action if an exception was indeed thrown. Lastly, the `finally` block allows you to run code no matter if an exception was thrown or not.\n\nLet's look at a very simple exception:\n\n```python\ntry:\n    print(myVar)except:\n    print(\"An exception occurred.\")\n```\n\n```text\nAn exception occurred.\n```\n\nIn our piece of code, the variable `myVar` was purposely not defined. This threw an exception which we handled inside our `except` block.\n\nNotice how we didn't use a `finally` block because they are entirely optional. However, we could use one anyway like this:\n\n```python\ntry:\n    print(myVar)except:\n    print(\"An exception occurred.\")\nfinally:\n    print(\"Moving on!\")\n```\n\n```text\nAn exception occurred.\nMoving on!\n```\n\n## Multiple Exceptions\n\nYou can handle multiple exceptions by chaining the `except` blocks and specifying what error you want to handle.\n\nHere's how that looks:\n\n```python\ntry:\n    print(myVar)except OverflowError:\n    print(\"An overflow occurred.\")\nexcept:\n    print(\"An exception occurred.\")\nfinally:\n    print(\"Moving on!\")\n```\n\n```text\nAn exception occurred.\nMoving on!\n```\n\n## Else\n\nYou can use the `else` block to run code when no exceptions were thrown. This is similar to the `finally` block except that the `finally` block runs no matter what whereas the `else` block runs only when the code was exception-free.\n\n```python\ntry:\n    print(\"Hello!\")\nexcept OverflowError:\n    print(\"An overflow occurred.\")\nexcept:\n    print(\"An exception occurred.\")\nelse:\n    print(\"Great, no errors!\")\nfinally:\n    print(\"Moving on!\")\n```\n\n```text\nHello!\nGreat, no errors!\nMoving on!\n```\n\n## Raising Exceptions\n\nWhen the situation arises, you might want to raise an exception yourself. This is done using the `raise` keyword:\n\n```python\nraise Exception(\"Sorry, this is an exception!\")\n```\n\n```text\nTraceback (most recent call last):\nFile \"C:\\Users\\Nilan\\example.py\", line 1, in \u003cmodule\u003e\nraise Exception(\"Sorry, this is an exception!\")\nException: Sorry, this is an exception!\n```\n\nThis is useful especially if you're writing your own module because it allows users of your module to then handle your exceptions themselves and handle it however they want.\n\n[Python Docs - Errors and Exceptions](https://docs.python.org/3/tutorial/errors.html)\n"])</script>
1<script>self.__next_f.push([1,"7c:T18a5,"])</script>
1<script>self.__next_f.push([1,"\nDirectories in a file system are just as important as files, and Python makes working with both pretty easy using the `os` module.\n\n## Creating a new Directory\n\nYou can create a new directory using the `mkdir` function, which is short for \"make directory\":\n\n```python\nimport os\nos.mkdir(\"new_folder\")\n```\n\nYour new folder has been created!\n\n## Getting your Current Working Directory\n\nJust like when you're using the command line, sometimes you just want to know what directory you are currently working off of so you know how to get to where you want to go.\n\nThere is a function you can run to print that out for you, the `getcwd()` function which stands for \"get current working directory\".\n\n```python\nimport os\n\nprint(os.getcwd())\n```\n\n```bash\nC:\\Users\\Nilan\\Desktop\n```\n\nEasy enough!\n\n## Changing your Current Working Directory\n\nNow that you know where you are, you might want to change it to work from another directory. You can do this using the `chdir()` function which stands for \"change directory\":\n\n```python\nimport os\n\nprint(os.getcwd())\n\nos.chdir(\"C:\\Users\\\")\n\nprint(os.getcwd())\n```\n\n```bash\nC:\\Users\\Nilan\\Desktop\nC:\\Users\n```\n\nKeep in mind that the double slashes are so that we can use slash literals, which is what we want in this case.\n\n## Deleting a Directory\n\nYou can delete a directory using the `rmdir()` function, which stands for \"remove directory\", and passing in the path to the directory you want removed:\n\n```python\nimport os\n\nos.rmdir(\"test\")\n```\n\nThere goes the `test` directory!\n\nKeep in mind that you can only remove empty folders!\n\nPython allows you to work with the file system, which includes both files and directories. Using the built-in system functions, you can access, manipulate, open, read, write, append, and close files.\n\n## Opening a File\n\nIn Python, you can open a file using the built-in open function. This function accepts two required arguments: the name of the file you want to open and the mode in which you want to open it.\n\nHere's an example:\n\n```python\nfile = open(\"example.txt\", \"r\")\n```\n\nIn the above code, \"example.txt\" is the name of the file you want to open and \"r\" is the mode. The mode \"r\" stands for \"read\" and it opens the file for reading. There are several other modes you can use:  \n\n-   \"r\": Read mode (default) - used for reading the contents of an existing file \"w\": Write mode - used for creating a new file or overwriting an existing file\n-   \"a\": Append mode - used for appending data to an existing file\n-   \"x\": Exclusive creation mode - used for creating a new file, but will raise an error if the file already exists\n-   \"b\": Binary mode - used for reading or writing binary data You can combine the modes with \"b\" to open a file in binary mode.\n\nFor example, \"rb\" means to open the file in binary read mode, and \"wb\" means to open the file in binary write mode.\n\n## Reading a File\n\nHere's an example of how you can read the contents of a file:  \n\n```python\nfile = open(\"example.txt\", \"r\")\ncontents = file.read()\nprint(contents)\nfile.close()\n```\n\nIn this example, the read method is used to read the contents of the file, and then the close method is used to close the file after you're done with it. It's a good idea to always close your files when you're done with them, to ensure that the resources they use are properly released.\n\nYou can also use the with statement to automatically close the file for you, like this:\n\n```python\nwith open(\"example.txt\", \"r\") as file:\n    contents = file.read()\n    print(contents)\n```\n\nIn this example, the file is automatically closed after the with block is exited, even if an exception is raised.\n\n## Read File Line by Line\n\nMaybe instead of getting the entire file, you want to read it line by line. Thankfully, there is already a built-in function for this. The `readline()` function reads a file line by line each time. If you use it twice, the second time will return the second line.\n\n```python\nfile = open(\"file.txt\", \"r\")\nprint(file.readline())\nprint(file.readline())\n```\n\n```text\nHello!\nWelcome to StackTips!\n```\n\nAlternatively, you can just loop over the lines, like so:\n\n```python\nfile = open(\"file.txt\", \"r\")\nfor line in file:\n    print(line)\n```\n\n```text\nHello!\nWelcome to StackTips!\nHave fun!\n```\n\n## Closing a File\n\n**Closing** a file is important because it is sometimes needed to ensure any changes to a file are propagated in the file system.\n\nThis is how to close a file once you're finished with it:\n\n```python\nfile = open(\"file.txt\", \"r\")\nfor line in file:\n    print(line)\nfile.close()\n```\n\nOur file is now closed!\n\n## Appending to Existing File\n\nYou can append text to an existing file pretty easily. Simply switch the mode when you open and use the `write()` function:\n\n```python\nfile = open(\"file.txt\", \"a\")\nfile.write(\"Coding is fun!\")\nfile.close()\n\nfile = open(\"file.txt\", \"r\")\nprint(file.read())\n```\n\n```text\nHello!\nWelcome to StackTips!\nHave fun!\nCoding is fun!\n```\n\n## Overwriting an Existing File\n\nThe only difference between appending and **overwriting** an existing file is the mode. Here is how you overwrite a file entirely:\n\n```python\nfile = open(\"file.txt\", \"w\")\nfile.write(\"Coding is fun!\")\nfile.close()\n\nfile = open(\"file.txt\", \"r\")\nprint(file.read())\n```\n\n```text\nCoding is fun!\n```\n\nKeep in mind that if the file does not exist, a new one will be created.\n\n## Creating new Empty Files\n\nYou can create a brand new file without any content in it by changing the mode to `x`:\n\n```python\nfile = open(\"file.txt\", \"x\")\nfile.close()\n```\n\nA new blank file has been created!\n\n## Renaming a File\n\nTo **rename** a file using Python, we must import the `os` module, then use its `rename()` function.\n\nHere's how that looks:\n\n```python\nimport os\nos.rename(\"old_name.txt\", \"new_name.txt\")\n```\n\nPretty simple!\n\n## Deleting a File\n\n**Deleting** a file also requires the use of the `os` module.\n\nHere's how y
1ou do it:\n\n```python\nimport os\n\nos.remove(\"file.txt\")\n```\n\nKeep in mind that this will throw an error if the file doesn't exist.\n\n## Check if a File Exists\n\nTo avoid an error with trying to remove a file that does not exist, you should check if the file exists before trying to remove it.\n\nThis is how you do it:\n\n```python\nimport os\n\npath = \"file.txt\"\n\nif os.path.exists(path):\n    os.remove(path)\nelse:\n    print(\"This path does not exist: \" + path)\n```\n"])</script>
1<script>self.__next_f.push([1,"7d:T853,"])</script>
1<script>self.__next_f.push([1,"\nPython offers us easy-to-use functions inside the `datetime` and `time` modules to manipulate, convert, and display dates and time.\n\n## Getting the Date\n\nWe can use the `datetime` module to get the exact date and time at the point of running the program:\n\n```python\nimport datetime\n\nnow = datetime.datetime.now()\nprint(now)\n```\n\n```bash\n2019-12-01 00:00:00.000000\n```\n\n## Getting Information from the Date\n\nOnce you have a date project, you can get specific pieces of information out of it by accessing the properties, like so:\n\n```python\nimport datetime\n\nnow = datetime.datetime.now()\n\nday = now.day\nmonth = now.month\nyear = now.year\n\nprint(\"Day: \" + str(day))\nprint(\"Month: \" + str(month))\nprint(\"Year: \" + str(year))\n```\n\n```bash\nDay: 1\nMonth: 12\nYear: 2019\n```\n\n## Creating a Date\n\nWe can create a new date object by using the `datetime` function and passing in the values we want:\n\n```python\nimport datetime\n\nfuture = datetime.datetime(2030, 6, 18)\n\nday = future.day\nmonth = future.month\nyear = future.year\n\nprint(\"Day: \" + str(day))\nprint(\"Month: \" + str(month))\nprint(\"Year: \" + str(year))\n```\n\n```bash\nDay: 18\nMonth: 6\nYear: 2030\n```\n\n## Formatting a Date\n\nOnce you get or create your date object, you can print it out in a readable format using the `strftime` function:\n\n```python\nimport datetime\n\nfuture = datetime.datetime(2030, 6, 18)\n\nprint(future.strftime(\"%A\"))\n```\n\n```bash\nTuesday\n```\n\nCurious about that `%A`? Here are all the other symbols you can use to format your string:\n\n-   `%a`: Weekday (short)\n-   `%A`: Weekday (full)\n-   `%w`: Weekday (number)\n-   `%d`: Day of Month\n-   `%b`: Month (short)\n-   `%B`: Month (full)\n-   `%m`: Month (number)\n-   `%y`: Year (short)\n-   `%Y`: Year (full)\n-   `%H`: Hour (00-23)\n-   `%I`: Hour (00-12)\n-   `%p`: AM/PM\n-   `%M`: Minute\n-   `%S`: Second\n-   `%f`: Microsecond\n-   `%z`: UTC offset\n-   `%Z`: Timezone\n-   `%j`: Day of Year\n-   `%U`: Week Number (starting from Sunday)\n-   `%W`: Week Number (starting from Monday)\n-   `%c`: Local date and time\n-   `%x`: Local date\n-   `%X`: Local time\n\n[Python Docs - Datetime](https://docs.python.org/3/library/datetime.html)\n"])</script>
1<script>self.__next_f.push([1,"7e:Tb42,"])</script>
1<script>self.__next_f.push([1,"\nRegular expressions are a formatted sequence or pattern of characters that can be used in a search operation. They are written in a specific syntax and then are usually used to search for patterns in other text, or returning whether or not that text has met the pattern.\n\nPython has a built-in module just for this, the `re` module.\n\n## Using Regular Expressions Functions\n\nHere are the functions that the `re` module offers to us:\n\n-   `findall`: Returns a list with all the matches\n-   `search`: Returns a Match object if a match was found\n-   `split`: Returns a list of the string split at every match\n-   `sub`: Substitutes all the matches with a string\n\nLet's see these all in action.\n\n## findall Function\n\nUse the `findall()` function when you want to find all the matches you have described:\n\n```python\nimport re\n\nexample = \"I pledge allegiance.\"\nresults = re.findall(\"le\", example)\nprint(results)\n```\n\n```bash\n['le', 'le']\n```\n\nPython found `le` twice. If nothing was found, the list returned will be empty. You can take the length of this list to the number of results found.\n\n## search Function\n\nThe `search()` function searches the string for a match. It returns back a `re.Match` object.\n\n```python\nimport re\n\nexample = \"I pledge allegiance.\"\n\nresults = re.search(\"le\", example)\nprint(results)\n```\n\n```bash\n\u003cre.Match object; span=(18, 20), match='le'\u003e\n```\n\nUsing this `re.Match` object, you can get the index of the first match, like this:\n\n```python\nimport re\n\nexample = \"I pledge allegiance.\"\n\nresults = re.search(\"le\", example)\nprint(results.start())\n```\n\n```bash\n3\n```\n\n## split Function\n\nThe `split()` function returns the string split at every match.\n\n```python\nimport re\n\nexample = \"I pledge allegiance.\"\n\nresults = re.split(\"le\", example)\nprint(results)\n```\n\n```bash\n['I p', 'dge al', 'giance.']\n```\n\nPretty straightforward, it cuts out all the string passed in when matched, and splits the string at that point.\n\n## sub Function\n\nThe `sub()` function substitutes a match with a string of your choice:\n\n```python\nimport re\n\nexample = \"I pledge allegiance.\"\n\nresults = re.sub(\"le\", \"ABC\", example)\nprint(results)\n```\n\n```bash\nI pABCdge alABCgiance.\n```\n\n## Special Sequences\n\nIn addition to string literals, you can use **special sequences** in your regular expressions to make them more powerful.\n\nHere is a list of the special sequences you can use:\n\n-   `.`: Matches any character\n-   `\\w`: Matches an alphanumeric character (includes underscores)\n-   `\\W`: Matches a non-alphanumeric character (excludes underscores)\n-   `\\b`: Space between word and non-word characters\n-   `\\s`: Matches a single whitespace character\n-   `\\S`: Matches a non-whitespace character\n-   `\\t`: Matches a tab\n-   `\\n`: Matches a newline\n-   `\\r`: Matches a return\n-   `\\d`: Matches a numeric character\n-   `\\^`: Matches the start of a string\n-   `\\$`: Matches the end of a string\n"])</script>
1<script>self.__next_f.push([1,"7f:T1751,"])</script>
1<script>self.__next_f.push([1,"\nPython is used extensively in finance, simulation, data science, statistical analysis, and in many other mathematically-intensive fields of work. The reason being is that Python makes working with numbers very easy.\n\n## Arithmetic Operators\n\nHere are the most common **arithmetic operators** that allow you to manipulate numbers in Python.\n\n### Addition\n\nYou can add numbers in Python using the `+` operator.\n\n```python\nx = 2\ny = 5\n\ntotal = x + y\nprint(total)\n```\n\n```bash\n7\n```\n\n### Subtraction\n\nYou can subtract numbers in Python using the `-` operator.\n\n```python\nx = 8\ny = 3\n\ntotal = x - y\nprint(total)\n```\n\n```bash\n5\n```\n\n### Multiplication\n\nYou can multiply numbers in Python using the `*` operator.\n\n```python\nx = 4\ny = 6\n\ntotal = x * y\nprint(total)\n```\n\n```bash\n24\n```\n\n### Division\n\nYou can divide numbers in Python using the `/` operator.\n\n```python\nx = 54\ny = 2\n\ntotal = x / y\nprint(total)\n```\n\n```bash\n27.0\n```\n\n### Modulus\n\nYou can find the remainder of a division in Python using the `%` operator.\n\n```python\nx = 64\ny = 23\n\ntotal = x % y\nprint(total)\n```\n\n```bash\n18.0\n```\n\n### Exponents\n\nYou can find the **power** of a number in Python using the `**` operator.\n\n```python\nx = 2\ny = 4\n\ntotal = x ** y\nprint(total)\n```\n\n```bash\n16\n```\n\n### Order of Operations\n\n**Order of Operations**, also known as **PEMDAS**, is at play here, including with the use of parentheses.\n\n```python\nx = (4 * 5) + 20 / 4\nprint(x)\n```\n\n```bash\n25\n```\n\n## Python Number Types\n\nThere are three kinds of numbers in Python, and they are as followed:\n\n-   int\n-   float\n-   complex\n\n```python\na = 1337  # int\nb = 13.37 # float\nc = 1337j # complex\n\nprint(type(a))\nprint(type(b))\nprint(type(c))\n```\n\n```bash\n\u003cclass 'int'\u003e\n\u003cclass 'float'\u003e\n\u003cclass 'complex'\u003e\n```\n\n### int\n\n**Integers** are whole numbers like `4` or `532`. They can be positive or negative, and they don't contain any decimals.\n\n```python\na = 423\nb = 74\nc = 87937595\n```\n\nThese are all valid integers.\n\n### Float\n\n**Floating point numbers** are numbers containing a decimal, and can also be positive or negative. Here are some examples:\n\n```python\na = 1.53\nb = 3.1\nc = -95.23\n```\n\n### Complex\n\n**Complex** numbers are Python's representation of imaginary numbers, and they use a `j` to represent the `i`.\n\n```python\na = 4+2j\nb = 9j\nc = -3j\n```\n\n## Number Type Conversion\n\nPython offers built-in methods to convert between these types using the `float()`, `int()`, and `complex()` methods.\n\n```python\na = 5   # int\nb = 3.3 # float\nc = 7j  # complex\n\nfloat = float(a)\nint = int(b)\ncomplex = complex(a)\n\nprint(float)\nprint(int)\nprint(complex)\n\nprint(type(float))\nprint(type(int))\nprint(type(complex))\n```\n\n```bash\n5.0\n3\n(5+0j)\n\u003cclass 'float'\u003e\n\u003cclass 'int'\u003e\n\u003cclass 'complex'\u003e\n```\n\nKeep in mind that you cannot convert complex numbers into anything else.\n\n## Math Methods\n\nWe mentioned before that Python is used heavily in any field that utilizes math. The built-in methods that Python provides is a large reason why. Here are some of the most common ones:\n\n### Absolute Value\n\nGet the **absolute value** of a number by using the `abs()` method:\n\n```python\nnumber = -34\nprint(abs(number))\n```\n\n```bash\n34\n```\n\n### Floor\n\nUse the `floor()` method to get the number passed in rounded down to the nearest integer if it is not already an integer.\n\nFor this and other math methods, you'll need to import the `math` module.\n\n```python\nimport math\n\nnumber = 6.21\nprint(math.min(number))\n```\n\n```bash\n6\n```\n\n### Ceiling\n\nUse the `ceil()` method to get the number passed in rounded up to the next highest integer if it is not already an integer.\n\n```python\nimport math\n\nnumber = 6.21\nprint(math.ceil(number))\n```\n\n```bash\n7\n```\n\n### Natural Logarithm\n\nYou can get the **natural logarithms** of a number using `log()`.\n\n```python\nimport math\n\nnumber = 123\nprint(math.log(number))\n```\n\n```bash\n4.812184355372417\n```\n\n### Base-10 Logarithm\n\nAlternatively, you can also get the **base-10 logarithm** of a number using `log10()`.\n\n```python\nimport math\n\nnumber = 123\nprint(math.log10(number))\n```\n\n```bash\n2.089905111439398\n```\n\n### Maximum\n\nYou can get the **maximum** of two or more numbers using the `max()` method:\n\n```python\nnumber1 = 123\nnumber2 = 456\nnumber3 = 789\nprint(max(number1, number2, number3))\n```\n\n```bash\n789\n```\n\n### Minimum\n\nYou can get the **minimum** of two or more numbers using the `min()` method:\n\n```python\nnumber1 = 123\nnumber2 = 456\nnumber3 = 789\nprint(min(number1, number2, number3))\n```\n\n```bash\n123\n```\n\n### Power\n\nYou can take the **power** of a number using `pow`.\n\n```python\nbase = 3\nexponent = 4\nprint(pow(base, exponent))\n```\n\n```bash\n81\n```\n\n### Round\n\nYou can **round** off any number to the nearest integer using `round()`.\n\n```python\nnumber = 3.1459\nplaces = 3\nprint(round(number, places))\n```\n\n```bash\n3.146\n```\n\n### Square Root\n\nYou can take the **square root** of a number using `sqrt()`.\n\n```python\nimport math\n\nnumber = 81\nprint(math.sqrt(number))\n```\n\n```bash\n9\n```\n\n### Random\n\nGenerating random numbers in Python is easy. There's a module named `random` that has all we need. Call the `randrange()` method to get a number in between two other numbers you define:\n\n```python\nimport random\n\nstart = 1\nend = 10\nprint(random.randrange(start, end))\n```\n\n```bash\n6\n```\n\nKeep in mind that it does NOT include the second parameter. In other words, because our second parameter was a 10, this is effectively only going to ever return a number between and including 1 and 9.\n\n## Math Constants\n\nOne last cool to point out is that Python's `math` module also comes with some predefined constants for us.\
1n\n### Euler's Number\n\nOne of the constants that the `math` module comes with is **Euler's Number**:\n\n```python\nimport math\n\ne = math.e\nprint(e)\n```\n\n```bash\n2.718281828459045\n```\n\n### Pi\n\nPython's `math` module also comes with a value for **Pi**, the ratio of the circumference of a circle relative to its diameter.\n\n```python\nimport math\n\npi = math.pi\nprint(pi)\n```\n\n```bash\n3.141592653589793\n```\n"])</script>
1<script>self.__next_f.push([1,"80:T7a3,"])</script>
1<script>self.__next_f.push([1,"\nJSON stands for JavaScript Object Notation and it is one of the most popular data formats to store and transfer data between two points. Python has a built-in module called `json` that we can use to work with JSON.\n\n## Deserialising JSON in Python\n\nWe can parse a string of JSON into a Python dictionary using the `loads()` function in the `json` module:\n\n```python\nimport json\n\njson_str = '{ \"name\": \"Timmy Turner\", \"age\": 10, \"show\": \"The Fairly OddParents\"}'\n\nparsed = json.loads(json_str)\nprint(parsed)\n```\n\n```json\n{'name': 'Timmy Turner', 'age': 10, 'show': 'The Fairly OddParents'}\n```\n\nWhile it looks the same as the input, because it is a dictionary, you can access it like you would any dictionary:\n\n```python\nimport json\n\njson_str = '{ \"name\": \"Timmy Turner\", \"age\": 10, \"show\": \"The Fairly OddParents\"}'\n\nparsed = json.loads(json_str)\nprint(parsed[\"name\"])\nprint(parsed[\"age\"])\nprint(parsed[\"show\"])\n```\n\n```bash\nTimmy Turner\n10\nThe Fairly OddParents\n```\n\n## Serialising Object to JSON in Python\n\nYou can do the reverse and **convert** a Python object into a string of JSON using the `dumps()` function:\n\n```python\nimport json\n\nobj = {\n    \"name\": \"Timmy Turner\",\n    \"age\": 10,\n    \"show\": \"The Fairly OddParents\"\n}\n\nconverted = json.dumps(obj)\n\nprint(converted)\n```\n\n```json\n{\"name\": \"Timmy Turner\", \"age\": 10, \"show\": \"The Fairly OddParents\"}\n```\n\n## Formatting JSON\n\nWhen you are outputting to JSON, you can pass optional parameters to the `dumps()` function to format the output for us.\n\nHere's how to indent the string to make it more readable:\n\n```python\nimport json\n\nobj = {\n    \"name\": \"Timmy Turner\",\n    \"age\": 10,\n    \"show\": \"The Fairly OddParents\"\n}\n\nconverted = json.dumps(obj, indent=4)\n\nprint(converted)\n```\n\n```json\n{\n    \"name\": \"Timmy Turner\",\n    \"age\": 10,\n    \"show\": \"The Fairly OddParents\"\n}\n```\n\nIt's a good show that we hope you have watched!\n\n-   [Python Docs - JSON](https://docs.python.org/3/library/json.html)\n"])</script>
1<script>self.__next_f.push([1,"81:Teec,"])</script>
1<script>self.__next_f.push([1,"\nTo send email in Python using the smtplib module, you'll need to have a working SMTP server that you can connect to. You'll also need the email address of the sender and the recipient, as well as the message content. Here's an example of how to send an email using smtplib:\n\nPython offers the `smtplib` module that allows us to use the Simple Mail Transfer Protocol (SMTP) to send mail between mail servers.\n\n```python\nimport smtplib\n\n# Set up the SMTP server\nsmtp_server = \"smtp.gmail.com\"\nsmtp_port = 587\nsmtp_username = \"[email protected]\"\nsmtp_password = \"your_password\"\nserver = smtplib.SMTP(smtp_server, smtp_port)\nserver.starttls()\nserver.login(smtp_username, smtp_password)\n\n# Set up the email message\nfrom_email = \"[email protected]\"\nto_email = \"[email protected]\"\nsubject = \"Test email\"\nbody = \"This is a test email sent from Python.\"\nmessage = f\"Subject: {subject}\\n\\n{body}\"\n\n# Send the email\nserver.sendmail(from_email, to_email, message)\n\n# Close the connection\nserver.quit()\n```\n\nIn this example, we're using Gmail as the SMTP server, but you can use any SMTP server that you have access to. Make sure to replace your\\[email protected] and your\\_password with your actual Gmail email address and password. The starttls method enables encryption for the SMTP connection, and the login method authenticates the connection using the email address and password. The from\\_email and to\\_email variables specify the email addresses of the sender and recipient.\n\nThe subject variable specifies the subject of the email, and the body variable contains the text of the message.\n\nThe message variable combines the subject and body of the email into a single string that can be sent using the sendmail method.\n\nThe sendmail method takes three arguments: the sender's email address, the recipient's email address, and the message content.\n\nAfter the email is sent, the quit method is called to close the connection to the SMTP server.\n\nI hope this helps you get started with sending emails using smtplib in Python!\n\n## Sending HTML Email\n\nTo send an HTML email in Python using smtplib, you can use the email.mime module to create a message with the MIMEMultipart and MIMEText classes. Here's an example of how to send an HTML email:\n\n```python\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n# Set up the SMTP server\nsmtp_server = \"smtp.gmail.com\"\nsmtp_port = 587\nsmtp_username = \"[email protected]\"\nsmtp_password = \"your_password\"\nserver = smtplib.SMTP(smtp_server, smtp_port)\nserver.starttls()\nserver.login(smtp_username, smtp_password)\n\n# Set up the email message\nfrom_email = \"[email protected]\"\nto_email = \"[email protected]\"\nsubject = \"HTML email\"\nhtml = \"This is a test HTML emailThis email was sent using Python.\"\nmessage = MIMEMultipart(\"alternative\")\nmessage[\"Subject\"] = subject\nmessage[\"From\"] = from_email\nmessage[\"To\"] = to_email\nhtml_part = MIMEText(html, \"html\")\nmessage.attach(html_part)\n\n# Send the email\nserver.sendmail(from_email, to_email, message.as_string())\n\n# Close the connection\nserver.quit()\n```\n\nIn this example, we're creating an HTML message using the MIMEMultipart and MIMEText classes from the email.mime module. The html variable contains the HTML code for the email message.\n\nWe're then creating a MIMEMultipart message with the Subject, From, and To headers. The html\\_part variable contains the HTML message as a MIME text object, which we then attach to the MIMEMultipart message using the attach method.\n\nWe then send the email using the sendmail method, passing the from\\_email, to\\_email, and message.as\\_string() as arguments.\n\nFinally, we close the connection to the SMTP server using the quit method.\n\nI hope this helps you get started with sending HTML emails using smtplib in Python!\n"])</script>
1<script>self.__next_f.push([1,"82:T94a,"])</script>
1<script>self.__next_f.push([1,"\nVariables are the one of the fundamental building blocks of Python that are used to hold data in memory.\n\nVariables have two components, name and type. The data in the variables can be referenced by their names. Type defines what type of data it stores.\n\nLet's start by creating one.\n\n## Declaration\n\nDeclaring a variable is incredibly simple in Python. Unlike in other programming languages, you do not need to specify the type of variable, it is done automatically for you.\n\nExample of variable declaration looks like this:\n\n```python\nname = \"John Doe\"\nx = 777\nprint(name)\nprint(x)\n```\n\nThe above code block prints\n\n```text\nJohn Doe\n777\n```\n\n-   A variable is declared and assigned a value using the assignment operator =  \n    \n-   Python treats bool as a special type of integer. Technically, True has a value of 1 and False has a value of 0.  \n    \n-   A string is a collection of zero or more characters. Strings are commonly declared using single quotation marks, but you can also use double quotation marks.  \n    \n-   Python treats integer numbers and decimal numbers differently.\n\n## Variable Naming Rules\n\nHere are the rules for what are valid Python variable names:\n\n-   The variable name must begin with a letter or underscore\n-   The variable name cannot begin with a number or symbol\n-   Throughout the entire variable name, it can only contain alpha-numeric characters with the only exception being underscores\n\nWith that in mind, here are some examples of valid Python variable names:\n\n```text\napples\n_apples\n_apples_\n```\n\nAnd here are examples of invalid Python variable names:\n\n```text\n1apples\napp les\n$apples\n%apples\n```\n\nKeep in mind that variable names are case-sensitive!\n\n## Data Types\n\nPython supports five standard data types. We've already seen two of them already, **Numbers** and **String**. Here is the entire list:\n\n-   Numbers\n-   String\n-   List\n-   Tuple\n-   Dictionary\n\nIt is useful to know that you can get the type of a variable by using the `type` method, like so:\n\n```python\nname = \"John Doe\"\nprint(type(name))\nprint(name)\n\npi = 3.1415926\nprint(type(pi))\nprint(pi)\n\nx = 777\nprint(type(x))\nprint(x)\n\nisSuccess = True\nprint(type(\n```\n\nOutput of the code prints:\n\n```text\n\u003cclass 'str'\u003e\nJohn Doe\n\u003cclass 'float'\u003e\n3.1415926\n\u003cclass 'int'\u003e\n777\n\u003cclass 'bool'\u003e\nTrue\n```\n\nWe'll get into **lists**, **tuples**, and **dictionaries** in later lessons.\n"])</script>
1<script>self.__next_f.push([1,"83:T19da,"])</script>
1<script>self.__next_f.push([1,"\nClass are blueprints to create objects which represent a collection of related properties and methods\n\nPython is an object-oriented programming language.\n\nObjects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes.\n\n## Creating a Class in Python\n\nTo define a class we can use class keyword and define the properties and methods inside it.\n\n```python\nclass Vehicle:\n    number_of_wheels = 2\n    color = \"red\"\n```\n\nIn the above code snippet, we have declared a class called `Vehicle` with two properties `color` and `number_of_wheels`with some default values.\n\nNow that we have our class defined, let's create a object of the class `Vehicle`.\n\n## Creating an Object\n\nTo create a new object, simply reference the class you want to build the object out of. In this case, we'll use our previously defined `Person` class.\n\n```python\nclass Vehicle:\n    number_of_wheels = 2\n    color= \"red\"\n\nvehicle1 = Vehicle() # Creating object of class Vehicle\nprint(vehicle1)\nprint(\"Vehicle1:\", vehicle1.color)\n```\n\n**Output:**\n\n```text\n\u003c__main__.Vehicle object at 0x10ae31ae0\u003e\nVehicle1: red\n```\n\nAwesome, we created an object of class Vehicle and accessed the color property.\n\nLet us now make our classes useful.\n\n## **Python Class Constructor**\n\nConstructors are special kind of method, used for instantiating an object.\n\n-   The task of constructors is to initialize and assign values to the data members of the class when an object of the class is created.\n-   In Python, the `__init__()`method is called the constructor and is always called when an object is created.\n-   Python doesn?t support defining multiple constructors in a class. i.e constructor overloading is not supported by the language.\n-   You can pass any number of parameters to the **init** method similar to how you can pass in parameters to functions. However, the first parameter should always be self.\n\nLet us now define a constructor for Vehicle class:\n\n```python\nclass Vehicle:\n\n    def __init__(self, color, number_of_wheels):\n        self.color = color\n        self.number_of_wheels = number_of_wheels\n\nvehicle1 = Vehicle(\"Red\", 4)\nprint(vehicle1)\nprint(\"Vehicle1:\", vehicle1.color)\n\nvehicle2 = Vehicle(\"Blue\", 2)\nprint(vehicle2)\nprint(\"Vehicle2\", vehicle2.color)\n```\n\n**Output:**\n\n```text\n\u003c__main__.Vehicle object at 0x114b0f3a0\u003e\nVehicle1: Red\n\u003c__main__.Vehicle object at 0x114b0e470\u003e\nVehicle2 Blue\n```\n\n## Python Class Methods\n\nStrings and numbers aren't the only thing you can define in classes. Objects can also contain functions. Let's create one in our `Person` class.\n\n```python\nclass Vehicle:\n\n    def __init__(self, color, number_of_wheels):\n        self.color = color\n        self.number_of_wheels = number_of_wheels\n\n    def drive(self):\n        print(\"Drive mode on!\")\n\n    def stop(self):\n        print(\"Drive mode off!\")\n\nvehicle1 = Vehicle(\"Red\", 4)\nvehicle1.drive()\nvehicle1.stop()\n```\n\n**Output:**\n\n```text\nDrive mode on!\nDrive mode off!\n```\n\n### Python-Inheritance and Super\n\nInheritance is an important concept of OOP (Object Oriented Programming). It is a process by which a class inherit the properties and methods from another class (parent class).\n\nThe classes which are derived from parent class are called child classes.\n\nFor example. let us examine class Vehicle.\n\n```python\nclass Vehicle:\n    def __init__(self, brand, color):\n        self.brand = brand\n        self.color = color\n\n    def drive(self):\n        print(f\"Starting {{0}}\".format(self.brand))\n\n    def stop(self):\n        print(f\"Stopping {{0}}\".format(self.brand))\n```\n\nNow that we have our parent class defined, let's create our child class `Car` which inherits class `Vehicle`.\n\n```python\nclass Car(Vehicle):\n    def __init__(self, brand, color, fuel_type, number_of_seats):\n        super().__init__(brand, color)\n        self.fuel_type = fuel_type\n        self.number_of_seats = number_of_seats\n\n    def horn(self):\n        print(\"Beep Beep!!\")\n```\n\nA lot is going on here.\n\n-   First, `class Car(Vehicle):` is used for inheriting a Car class from a parent class `Vehicle`.\n-   We can use `super()` to call the parent class constructor by passing the required parameters.\n-   As the Car is inheriting the Vehicle class, all the properties and methods defined in Vehicle are now available to Car class.\n\n## Creating Objects\n\nNow that we have defined the Car class, let us now create few car objects and see it in action.\n\n```python\nvolkswagen = Car(\"Volkswagen\", \"Red\", \"Petrol\", 5)\nvolkswagen.drive()\nvolkswagen.horn()\nvolkswagen.stop()\n\nprint(\"=======\")\ntesla = Car(\"Tesla\", \"White\", \"Electric\", 5)\ntesla.drive()\ntesla.horn()\ntesla.stop()\n```\n\n**Output:**\n\n```text\nStarting Volkswagen\nBeep Beep!!\nStopping Volkswagen\n=======\nStarting Tesla\nBeep Beep!!\nStopping Tesla\n```\n\n## Overriding Methods in Python\n\nMethod overriding is one of the object-oriented programming feature, that allows subclass to provide a specific implementation of a method that is already defined in its parent class.\n\nWhen a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.\n\nOne last cool feature of inheritance is the concept of **overriding** methods. This is creating\
1n\nLet's see this in action:\n\n```python\nclass Vehicle:\n    def __init__(self, brand, color):\n        self.brand = brand\n        self.color = color\n\n    def drive(self):\n        print(f\"Starting {{0}}\".format(self.brand))\n\n    def stop(self):\n        print(f\"Stopping {{0}}\".format(self.brand))\n\nclass Car(Vehicle):\n    def __init__(self, brand, color, fuel_type, number_of_seats):\n        super().__init__(brand, color)\n        self.fuel_type = fuel_type\n        self.number_of_seats = number_of_seats\n\n    def drive(self):\n        print(f\"Starting {{0}}\".format(self.brand))\n        print(\"Activating auto-pilot mode\")\n        print(\"Engine rolling\")\n\n    def horn(self):\n        print(\"Beep Beep!!\")\n\nvolkswagen = Vehicle(\"Volkswagen\", \"Red\")\nvolkswagen.drive()\nvolkswagen.stop()\n\nprint(\"=====\")\ntesla = Car(\"Tesla\", \"White\", \"Electric\", 5)\ntesla.drive()\ntesla.horn()\ntesla.stop()\n```\n\n**Output:**\n\n```text\nStarting Volkswagen\nStopping Volkswagen\n=====\nStarting Tesla\nActivating auto-pilot mode\nEngine rolling\nBeep Beep!!\nStopping Tesla\n```\n\nSince we defined the `drive()` function with the same name as the parent class, Python automatically runs the one in the child.\n\nInheritance is a great way to organize your code and keep properties and functions where they belong.\n"])</script>
1<script>self.__next_f.push([1,"84:T13e8,"])</script>
1<script>self.__next_f.push([1,"\nDecision making is one of the core feature of any programming language. Python uses If keyword to take execution decisions based upon conditions known only during run time.\n\nHere is the general form of the if statement:\n\n```python\nif(condition1):\n    # statemnt 1\nelse:\n    # statemnt 2\n```\n\nHere a statement can be a single statement or multiple statements. The statements inside the if condition needs to be indented properly for python to understand the code block. In the above statement: If the condition1 is True, then statement1 is executed. Otherwise, statement2 is executed. In no case will both statements be executed. At any point, if your program requires more then two conditional checks, you can use elif keyword. For example:\n\n```python\nif(condition1):\n    # statemnt 1\nelif(condition2):\n    # statemnt 2\nelse:\n    # statemnt 3\n```\n\n## Comparison Operators\n\nTo use logic in our program, we'll need to learn about the comparison operates that Python offers.\n\n### Equality Operator\n\nThe most basic comparison operators we have is the equality operator. This simply checks if two values are equivalent or not. If they are the same, the result will be `True`, and if they are not equal, the result will be `False`.\n\nTo use the equality operator, simply use two equal signs.\n\n```python\nnumber1 = 3\nnumber2 = 3\nnumber3 = 6\nprint(number1 == number2)\nprint(number1 == number3)\n```\n\n**Output**\n\n```bash\nTrue\nFalse\n```\n\n### Inequality Operator\n\nThe **inequality operator** functions exactly like the equality operator we just saw but in reverse. If the two values are the same, it will result in `false`, and if they are different, it will result in `true`.\n\nTo use this operator, put an **exclamation point** in front of the equal sign, like so:\n\n```python\nnumber1 = 3\nnumber2 = 3\nprint(number1 != number2)\n```\n\n```bash\nFalse\n```\n\n### Greater Than and Less Than Operators\n\nYou can compare the values of two variables using the **greater than** and **less than** operators. Here is how to use them:\n\n```python\nnumber1 = 3\nnumber2 = 6\nprint(number1 \u003e number2) # greater than\n```\n\n**Output**\n\n```bash\nFalse\n```\n\n```python\nnumber1 = 3\nnumber2 = 6\nprint(number1 \u003c number2) # less than\n```\n\n**Output**\n\n```bash\nTrue\n```\n\n### Or Equal To Operators\n\nIn the case where you need to check if a value is **either** less than/greater than or equal to another value, Python also has an operator for that. It looks like a combination of the operators we saw before:\n\n```python\nprint(3 \u003c= 5)\nprint(3 \u003e= 5)\nprint(7 \u003c= 8)\nprint(7 \u003e= 9)\n```\n\n**Output**\n\n```bash\nTrue\nFalse\nTrue\nFalse\n```\n\n## Conditionals\n\nNow that are able to compare two values, we can now do something with that result. Using **conditionals** we can now take different paths of code depending on if the value inside it is `true` or `false`.\n\n### If\n\nUsing the **if** keyword is very straightforward. If whatever you are checking is `true`, then whatever is inside the next block of code will run.\n\nLet's see an example of this:\n\n```python\nburritos = 6\n\nif (burritos \u003e 5):\n    print(\"You ordered too many burritos.\")\n```\n\n**Output**\n\n```bash\nYou ordered too many burritos.\n```\n\nNow let's order a correct number of burritos and see what happens:\n\n```python\nburritos = 3\n\nif (burritos \u003e 5):\n    print(\"You ordered too many burritos.\")\n```\n\n**Output**\n\nNothing happened! The code block did not execute because the value of `burrito` was not greater than `5`.\n\n## Logical Operators\n\nSo far we've seen how logic works when we only have a single conditional to work with. Eventually, you will need to use multiple conditionals to finally make the decision about what path of code you want to take. When you want to use multiple conditionals at once, you use a **logical operator**.\n\n### And Operator\n\nBy using the **and** operator, the block of code will only execute if both sides of the operator are true:\n\n```python\nisHungry = True\nfoodAvailable = True\n\nif (isHungry and foodAvailable):\n    print(\"Since I am hungry and there is food, I shall eat.\")\n```\n\n**Output**\n\n```bash\nSince I am hungry and there is food, I shall eat.\n```\n\nSince in this case both variables were `true`, the resulting code block was ran, and the print statement was displayed.\n\n### Or Operator\n\nWhile using the `and` operator, both conditionals needed to be `true`, but with the `or` operator, only a **single one** needs to be `true`.\n\nConsider this example:\n\n```python\nsunny = False\nbored = True\n\nif (sunny or bored):\n    print(\"Since it is either sunny outside or I'm bored, I will go play basketball.\")\n```\n\n**Output**\n\n```bash\nSince it is either sunny outside or I'm bored, I will go play basketball.\n```\n\nEven though it is not sunny outside, because you are bored, you decided to play basketball anyway.\n\n### Not Operator\n\nIn our final logical operator, you can invert the results of a conditional entirely but using the **not** operator.\n\nLet's look at an example:\n\n```python\ntemperature = 50\nhot = temperature \u003e 70\n\nif not (hot):\n    print(\"Since it isn't hot, I will wear boots today!\")\n```\n\n**Output**\n\n```bash\nSince it isn't hot, I will wear boots today!\n```\n"])</script>
1<script>self.__next_f.push([1,"85:T141a,"])</script>
1<script>self.__next_f.push([1,"\nLoops are integral part of any programming language. Loop can simply be described as a situation in which you may need to execute the same block of code over and over.\n\nPython supports two looping constructs:\n\n-   for loop\n-   while loop\n\n## For Loop\n\nThe basic syntax of the for loop in Python looks something similar to the one mentioned below.\n\n```python\nfor itarator in sequence:\n    Statements\n    . . .\n    Statements\n```\n\n-   The keyword **for** signifies the beginning of the for loop.\n-   The **iterator** variable which iterates over the sequence and can be used within the loop to perform various functions\n-   The **in** keyword in Python which tells the iterator variable to loop for elements within the sequence\n-   And the **sequence variable** can be a list, a tuple or any other iterator types.\n-   The statements part of the loop is where you can play around with the iterator variable and perform various function\n\nLet us now examine some of the examples;\n\n### Example 1: **Python for loop with range() function**\n\nThe range() function is one of the built in function in Python. This is used when you want a loop to run for a specified number of iterations. For example, printing a number from 1 to 10\n\nWhen you want the for loop to run for a specific number of times, or you need to specify a range of objects to print out, the range function works really well. Consider the following example where I want to print the numbers 1, 2, and 3.\n\n```python\nfor i in range(0, 5):\n    print(i)\n```\n\n**Output:**\n\n```python\n0\n1\n2\n3\n4\n```\n\n### Example 2: **Print all letters of a string using the for loop**\n\n```python\nfor letter in \"stacktips.com\":\n    print(letter)\n```\n\n**Output:**\n\n```text\ns\nt\na\nc\nk\nt\ni\np\ns\n```\n\n### Example 3: Using for loop to print all elements in List\n\nLists and Tuples in python are iterable objects. The following example explains how to loop over the elements with in an iterable object.\n\n```python\nweek = [\"Sunday\", \"Monday\", \"Tuesday\",\n         \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\nfor day in week:\n    print(day)\n```\n\n**Output:**\n\n```text\nSunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\n```\n\n### Example 4: The break statement with for loop\n\nThe break statement is used to terminate the loop prematurely. It is used to exit the loop when a specific condition is met.\n\nFor example, let us write a method to search an item from the list. The following code will iterate over all individual list items and if the given item found, it will break the loop.\n\n```python\nnumbers = [15, 30, 10, 6, 8, 12]\n\ndef search_item(numbers, search_key):\n    found = False\n    for number in numbers:\n        if (number == search_key):\n            found = True\n            break\n    return found\n\nprint(\"List contains 10:\" , search_item(numbers, 10))\nprint(\"List contains 40:\", search_item(numbers, 40))\n```\n\n**Output:**\n\n```text\nList contains 10: True\nList contains 40: False\n```\n\n### Example 5: The continue statement with for loop\n\nThe continue statement in Python is used to skip the loop execution if a specific condition is satisfied.\n\nFor example, let us write a python function to add the sum of all positive numbers in the list.\n\n```python\nnumbers = [5, -3, -6, 4, 2, 1]\nsum=0;\nfor number in numbers:\n    if(number \u003c 0):\n        continue\n    sum+=number\n\nprint(\"Sum of Positive Numbers:\", sum)\n```\n\n**Output:**\n\n```text\nSum of Positive Numbers: 12\n```\n\n### Example 6: Python for loop with else block\n\nUnlike any other programming language, Python allows attaching an else block to the for loop.\n\nWhen an else block is attached, it will executed the statement inside else block when the loop ends.\n\nElse block is not executed, when a loop is terminated with `break` keyword.\n\nIn this example, we want to write a method to check if a string contains only alphabets and no other invalid characters.\n\n```python\ndef validate_name(name):\n    for letter in name:\n        if (letter.isalpha()):\n            continue\n        else:\n            print(name, \"contains invali
1d characters\")\n            break\n    else:\n        print(name, \"is a valid name\")\n\nvalidate_name(\"John\")\nvalidate_name(\"John007\")\n```\n\n**Output:**\n\n```text\nJohn is a valid name\nJohn007 contains invalid characters\n```\n\nThe above example, iterates through individual letters and checks for a valid alphabet, if it contains valid alphabets, the loop continuous. Otherwise it breaks the loop.\n\nThe else block gets executed at the end when the loops is completed successfully without the break clause being called\n\n## While loop\n\nA **while loop** is an even simpler loop. A while loop takes a conditional and if that condition is `true`, it will continue with another loop. The iterator variable is placed outside the while loop.\n\nLet's look at looping from 1 to 5 again but this time using a while loop:\n\n```python\ncount = 1\n\nwhile count \u003c= 5:\n    print(count)\n    count += 1\n```\n\n**Output:**\n\n```text\n1\n2\n3\n4\n5\n```\n\nThe for loop in Python is very similar to any other programming languages. We can use break and continue statements with for loop to alter the execution. However, in Python, we can have optional else block in for loop too.\n"])</script>
1<script>self.__next_f.push([1,"86:Tfef,"])</script>
1<script>self.__next_f.push([1,"\nFunction in Python is group of related statements that performs a specific task.\n\nFunctions are a great way to group related statements that is aimed to break a complex program into smaller and reusable chunks.\n\nIn Python a function is defined using the def keyword.\n\n```python\ndef function_name(parameter1, parameter2):\n    print(\"Hello from a function\")\n```\n\nYou can pass data, known as parameters, into a function. A function can return data as a result.\n\nAs you have noticed above, we have defined a function but it was never invoked. Here is how we invoke a method.\n\n```python\ndef print_hello():\n    print(\"Hello from a function!\")\n\nprint_hello()\n```\n\n**Output:**\n\n```text\nHello from a function!\n```\n\n## Arguments\n\nWe can pass in pieces of data to the function so that it can perform different tasks. For example, in the following method definition greet, we are require to pass two arguments when invoking the function.\n\n```python\ndef greet(name, message):\n    print(\"Hello\", name + ', ' + message)\n\ngreet(\"Adam\", \"Good morning!\") # Positional arguments\ngreet(message=\"Good morning!\", name=\"John\") # Named arguments\n```\n\n**Output:**\n\n```text\nHello Adam, Good morning!\nHello John, Good morning!\n```\n\n-   Notice that, in the first function call, the arguments are passed based on the **position defined** in the function definition.\n-   However, Python also allows passing the **named arguments**. When arguments are passed by their names, the orders are ignored.\n\n**Output:**\n\n```text\nResult: 300\n```\n\nNote that the above function two numbers as parameters and returns the sum of two numbers.\n\n## Default Parameter Values\n\nPython allows you to set a default values for the function parameters. If a function is defined with default parameter values, you don?t have to pass the parameters when invoking the function.\n\nLet's apply this using our previous example:\n\n```python\ndef add_num(number1 = 0, number2 = 0):\n    return number1 + number2\n\nresult = add_num(100, 200)\nprint(\"Result:\", result)\n\nresult = add_num()\nprint(\"Result:\", result)\n```\n\n**Output:**\n\n```text\nResult: 300\nResult: 0\n```\n\nBecause we set the default value for parameters to be 0, when we invoke the method `add_num` without passing the parameters, the values defaulted to 0.\n\n## Arbitrary Arguments (\\*args)\n\nIf the number of arguments that will be passed to a function is not known upfront, you can define a function with arbitrary arguments. Just add a `* (asterisks)` before the argument name in your function definition.\n\nFor example:\n\n```python\ndef my_function(*args):\n  print(\"The third arg is:\", args[2])\n\nmy_function(\"John\", \"Adam\", \"Prakash\")\n```\n\nOutput:\n\n```text\nThe third arg is: Prakash\n```\n\n## Arbitrary Keyword Arguments (\\*\\*kwargs)\n\nIf you do not know how many keyword arguments that will be passed into your function, add two asterisk: `**` before the parameter name in the function definition.\n\nThis way the function will receive a dictionary of arguments, and can access the items by their keys.\n\nFor example:\n\n```python\ndef my_function(**args):\n  print(\"The name2 arg is:\", args[\"name2\"])\n\nmy_function(name1=\"John\", name2=\"Adam\", name3=\"Prakash\")\n```\n\n**Output:**\n\n```text\nThe name2 arg is: Adam\n```\n\n## The pass keyword\n\nA function defined in Python cannot have be empty. But for some reason if you don?t have a function definition, you can use the `pass` statement to avoid the compilation error.\n\n```python\ndef my_function():\n    pass\n```\n\n## Function Recursion\n\nPython also accepts function recursion, which means a defined function can call itself.\n\nLet us now define a method to calculate factorial for a given number.\n\n?? Factorial is the process of multiplying all the integers less than or equal to a given number. So, 5! is equivalent to 5\\*4\\*3\\*2\\*1 which is 120. We can use a recursive function to do this work for us.\n\n```python\ndef factorial(num):\n    if (num == 0):\n        return 1\n    else:\n        return num * factorial(num - 1)\n\nprint('{}! is {}'.format(4, factorial(4)))\nprint('{}! is {}'.format(3, factorial(3)))\n```\n\n**Output:**\n\n```text\n4! is 24\n3! is 6\n```\n"])</script>
1<script>self.__next_f.push([1,"87:T730,"])</script>
1<script>self.__next_f.push([1,"\nIn Python, a file containing statements and definitions is referred as a module.\n\nAll the methods and variables defined in a Python module can be imported and accessed from another modules.\n\nLet us create a module for performing the `math.py`.\n\n```python\n# Python Module example\ndef add(a, b):\n   return a + b\n\ndef subtract(a, b):\n   return a - b\n\ndef multiply(a, b):\n   return a * b\n```\n\nHere, we have defined three functions inside the `math` module.\n\n## How to Import a Module in Python?\n\nTo import a module you need to use `import` statement\n\n```python\nimport math\n\nsum = math.add(5, 10)\nprint(\"Sum is:\", sum)\n\nsum = math.subtract(15, 10)\nprint(\"Sub is:\", sum)\n```\n\n**Output:**\n\n```text\nSum is: 15\nSub is: 5\n```\n\nYou can also import the module by renaming as follows:\n\n```python\nimport math as m\n\nsum = m.add(5, 10)\nprint(\"Sum is:\", sum)\n\nsum = m.subtract(15, 10)\nprint(\"Sub is:\", sum)\n```\n\nNotice that in the above example, we have imported the entire module. Let's say you only wanted a specific function inside the module. We can do that too, like so:\n\n```python\nfrom math import add\nfrom math import subtract\n\nsum = add(5, 10)\nprint(\"Sum is:\", sum)\n\nsub = subtract(15, 10)\nprint(\"Sub is:\", sub)\n```\n\n## Python Built-in Modules\n\nPython has many built-in modules, and we've already used one extensively in this class, namely the `math` module.\n\nHere are some other popular useful built-in modules that might be familiar to you:\n\n| array | copy | html | http |\n| --- | --- | --- | --- |\n| email | fileinput | io | json |\n| gc | gzip | ipaddress | numbers |\n| pip | pipes | random | ssl |\n| string | symbol | sys | time |\n\nDefinitely check out the documentation for these modules if you're curious about what functionality any of them offer!\n\n## References\n\n-   [Python Docs - Modules](https://docs.python.org/3/tutorial/modules.html)\n"])</script>
1<script>self.__next_f.push([1,"88:Tbe0,"])</script>
1<script>self.__next_f.push([1,"\nUnlike all other collection types, dictionaries strictly contain key-value pairs.\n\n**Dictionaries** are collections that are unordered, changeable, and are indexed.\n\nThey are similar to lists but instead of the index being a number, you can instead use the key to access the element.\n\n## Creating a Dictionary\n\nHere's how you **create** a dictionary:\n\n```python\nqueens = {\n    \"city\": \"New York City\",\n    \"state\": \"New York\",\n    \"country\": \"United States\"\n}\n\nprint(queens)\n```\n\n**Output:**\n\n```text\n{'city': 'New York City', 'state': 'New York', 'country': 'United States'}\n```\n\n## Accessing Items\n\nItems in a dictionary can be accessed using the key.\n\n```python\nqueens = {\n    \"city\": \"New York City\",\n    \"state\": \"New York\",\n    \"country\": \"United States\"\n}\n\nprint(queens[\"city\"])\n```\n\n**Output:**\n\n```text\nNew York\n```\n\n## Adding Items to Python Dictionary\n\nYou can **add** items to a dictionary by setting a new key-value pair, like this:\n\n```python\ncompany = {\n    \"city\": \"New York City\",\n    \"state\": \"New York\",\n    \"country\": \"United States\"\n}\ncompany[\"name\"] = \"ABC Inc\"\nprint(company)\n```\n\n**Output:**\n\n```text\n{'city': 'New York City', 'state': 'New York', 'country': 'United States', 'name': 'ABC Inc'}\n```\n\n## Update Items in Python Dictionary\n\nDictionaries allow you to **change** the value of an item if you refer to it directly:\n\n```python\ncompany = {\n    \"city\": \"New York City\",\n    \"state\": \"New York\",\n    \"country\": \"United States\"\n}\ncompany[\"city\"] = \"London\"\ncompany[\"country\"] = \"GB\"\nprint(company)\n```\n\n```text\n{'city': 'London', 'state': 'New York', 'country': 'GB'}\n```\n\n## Looping through a Dictionary\n\nYou can **iterate** through the keys of a dictionary, and then use that key to get the value. Here's how:\n\n```python\nqueens = {\n    \"city\": \"New York City\",\n    \"state\": \"New York\",\n    \"country\": \"United States\"\n}\nfor key in queens:\n    value = queens[key]\n    print(\"Key: \" + key + \" Value: \" + value)\n```\n\n**Output:**\n\n```text\nKey: city Value: New York City\nKey: state Value: New York\nKey: country Value: United Statess\n```\n\n## Checking if a Key Exists\n\nYou can check if a **key exists** inside a dictionary like this:\n\n```python\nqueens = {\n    \"city\": \"New York City\",\n    \"state\": \"New York\",\n    \"country\": \"United States\"\n}\nprint(\"city\" in queens)\n```\n\n**Output:**\n\n```text\nTrue\n```\n\n## Removing Items\n\nYou can **remove** items from a dictionary by using the `pop()` function and providing the key. Here's how that looks:\n\n```python\nqueens = {\n    \"city\": \"New York City\",\n    \"state\": \"New York\",\n    \"country\": \"United States\"\n}\n\nqueens.pop(\"city\")\nprint(queens)\n```\n\n```text\n{'state': 'New York', 'country': 'United States'}\n```\n\n## Dictionary Length\n\nYou can get the number of items that exist in your dictionary by using the `len()` function:\n\n```python\nqueens = {\n    \"city\": \"New York City\",\n    \"state\": \"New York\",\n    \"country\": \"United States\"\n}\nprint(queens)\nprint(len(queens))\n```\n\n**Output:**\n\n```text\n{'city': 'New York City', 'state': 'New York', 'country': 'United States'}\n3\n```\n"])</script>
1<script>self.__next_f.push([1,"89:Tcb7,"])</script>
1<script>self.__next_f.push([1,"\nSets in Python are similar to list except that they do not allow for duplicate elements inside. Not only that but the collection is un-indexed, meaning there is no concept of indexes at all.\n\nSets are defined using curly braces.\n\n## Creating a Set\n\n**Creating** a set is similar to creating both a list and tuple:\n\n```python\ncolors = {\"red\", \"white\", \"blue\"}\nprint(colors)\n```\n\n**Output:**\n\n```text\n{'white', 'red', 'blue'}\n```\n\nNotice that the order of items printed in the output is different from the order defined. Because sets are unordered and without indexes, the order in which items appear can be in any order.\n\n## Adding Items to a Set\n\nWhile you cannot change the items inside a set, you can still **add new items** to the set. To do this, use the `add()` method.\n\n```python\ncolors = {\"red\", \"white\", \"blue\"}\ncolors.add(\"green\")\nprint(colors)\n```\n\n**Output:**\n\n```text\n{'white', 'red', 'green', 'blue'}\n```\n\nIf you want to add multiple items to a set at once, Python also offers this functionality using the `update()` method:\n\n```python\ncolors = {\"red\", \"white\", \"blue\"}\ncolors.update([\"orange\", \"black\", \"green\"])\nprint(colors)\n```\n\n**Output:**\n\n```text\n{'red', 'green', 'orange', 'white', 'black', 'blue'}\n```\n\n## Looping through a Set\n\nHere is how you iterate over a set:\n\n```python\ncolors = {\"red\", \"white\", \"blue\", \"orange\"}\n\nfor color in colors:\n    print(color)orange\nwhite\nred\nblue\n```\n\n**Output:**\n\n```text\n    white\nblue\nred\n```\n\n## Delete an Item from a Set\n\nIn addition to adding an item to a set, you can also **remove items** from it using the `remove` function.\n\n```python\ncolors = {\"red\", \"white\", \"blue\", \"orange\"}\ncolors.remove(\"blue\")\nprint(colors)\n```\n\n**Output:**\n\n```text\n{'orange', 'white', 'red'}\n```\n\nIf the item you're trying to remove doesn't exist, an error will be raised.\n\nIf you want to safely try to remove an item from a set that you're not sure exists in the set or not, use the `discard`:\n\n```python\ncolors = {\"red\", \"white\", \"blue\", \"orange\"}\ncolors.discard(\"green\")\nprint(colors)\n```\n\n```text\n{'orange', 'white', 'red', 'blue'}\n```\n\n## Check if Item Exists in Set\n\nYou can check if an item exists in a set using the `in` keyword:\n\n```python\ncolors = {\"red\", \"white\", \"blue\"}\n\nprint(\"red\" in colors)\nprint(\"yellow\" in colors)\n```\n\n**Output:**\n\n```text\nTrue\nFalse\n```\n\n## Set Length\n\nGet the number of items in your set using the `len()` function:\n\n```python\ncolors = {\"red\", \"white\", \"blue\"}\nprint(len(colors))\n```\n\n**Output:**\n\n```text\n3\n```\n\n## Combining Multiple Sets\n\nWhen you have two sets and you want to combine them, Python gives you two options. You can either make a new set or add the items to an existing set. To make a new set entirely, use the `union()` function:\n\n```python\ncolors1 = {\"red\", \"white\", \"blue\"}\ncolors2 = {\"red\", \"purple\", \"brown\"}\n\ncolors3 = colors1.union(colors2)\nprint(colors3)\n```\n\n**Output:**\n\n```text\n{'white', 'brown', 'red', 'purple', 'blue'}\n```\n\nIf you don't want to make a new set, and simply want to add the items from one set to another, use the `update()` function:\n\n```python\ncolors1 = {\"red\", \"white\", \"blue\"}\ncolors2 = {\"red\", \"purple\", \"brown\"}\n\ncolors1.update(colors2)\nprint(colors1)\n```\n\n**Output:**\n\n```text\n{'blue', 'purple', 'brown', 'red', 'white'}\n```\n"])</script>
1<script>self.__next_f.push([1,"8a:T1340,"])</script>
1<script>self.__next_f.push([1,"\nSpring Boot Annotations are metadata that provides compile time or runtime instructions to spring to decide how to wire your application together. It follows convention over configuration principle rather than XML.\n\nIn the [previous chapter](/articles/dependency-injection-in-spring-boot), we saw several of these annotations in action while learning Dependency Injection. This chapter pulls them together into one quick reference guide, and we shall preview the ones you'll meet next as we start building APIs.\n\n## Stereotype and Bean Annotations (Recap)\n\nThese annotations register and wire up your beans — we covered each of them in detail in [Chapter 4](/articles/understanding-spring-boot-project-structure) and [Chapter 5](/articles/dependency-injection-in-spring-boot), so here's a quick reference table rather than a re-explanation:\n\n| Annotation | What it does |\n| --- | --- |\n| `@SpringBootApplication` | This houses your main class. It combines `@Configuration`, `@EnableAutoConfiguration`, and `@ComponentScan` into one annotation. |\n| `@Component` | Generic stereotype marking a class as a Spring-managed bean. |\n| `@Service` | A specialization of `@Component` for classes that hold business logic. |\n| `@Repository` | A specialization of `@Component` for classes that hold data persistence logic. |\n| `@Controller` | A specialization of `@Component` for the presentation layer in Spring MVC. Spring provides another REST variant, `@RestController` used for API development.|\n| `@Autowired` | Tells Spring to inject an already-registered bean — on a field, constructor, or setter. |\n| `@Configuration` | Marks a class as a source of bean definitions. |\n| `@Bean` | Used inside `@Configuration` class to register a custom Spring managed bean. |\n\nThe `@Controller`, `@Service`, and `@Repository` annotations are all specializations of `@Component` annotation. Spring treats them the same way at registration time, but the distinct names help developers to identify purpose of a class at glance.\n\n```mermaid\ngraph TD\n    A[\"@Component\"] --\u003e B[\"@Controller\"]\n    A --\u003e C[\"@Service\"]\n    A --\u003e D[\"@Repository\"]\n```\n\nHere is how 
1we can use the `@Bean` annotation to register a Spring managed bean:\n\n```java\n@Configuration\npublic class AppConfig {\n\n    @Bean\n    public BeanExample beanExample() {\n        return new BeanExample();\n    }\n}\n```\n\n## Other Commonly Used Annotations\n\n- **`@Value`** — injects a value from your `application.properties` (or `application.yml`) file into a field, using `${property.name}` syntax. We'll use this extensively in [Chapter 7, Configuration Management](/articles/configuration-management-in-spring-boot).\n\n```java\n@Value(\"${app.name}\")\nprivate String appName;\n```\n\n- **`@PostConstruct`** — marks a method to run once, right after Spring has finished injecting all of a bean's dependencies. Useful for initialization logic that depends on those dependencies already being set:\n\n```java\n@Service\npublic class UserService {\n\n    @PostConstruct\n    public void init() {\n        System.out.println(\"UserService is ready to use.\");\n    }\n}\n```\n\n- **`@ControllerAdvice`** — marks a class that handles exceptions globally across all your `@Controller`/`@RestController` classes, instead of handling errors in every controller individually. We'll build one from scratch in [Chapter 19, Centralized Error Handling](/articles/centralized-error-handling-in-spring-boot-with-controlleradvice).\n\n## Coming Up: Annotations for Building REST APIs\n\nAll of the annotations we have seen so far deal with wiring of spring beans. Let's shift our focus to some of the new set of annotation used for building REST APIs:\n\n| Annotation | What it's for |\n| --- | --- |\n| `@RestController` | A `@Controller` that also assumes every method's return value should be written directly to the HTTP response body, as JSON. |\n| `@GetMapping`, `@PostMapping`, `@PutMapping`, `@DeleteMapping` | Map an HTTP method and URL path to a controller method. |\n| `@PathVariable` | Binds a value from the URL path (e.g., the `123` in `/users/123`) to a method parameter. |\n| `@RequestParam` | Binds a query-string parameter (e.g., `?page=2`) to a method parameter. |\n| `@RequestBody` | Deserializes the incoming JSON request body into a Java object. |\n| `@Valid` | Triggers bean validation on a `@RequestBody` or `@PathVariable`. |\n\nThis isn't an exhaustive list of every annotation in Spring — there are many more — but these cover the ones you'll use regularly while building applications with Spring Boot.\n\n## Summary\n\nIn this chapter, we reviewed some of the most commonly used annotations and their uses. Also we have previewed the REST-specific annotations we're about to start using in the coming chapters.\n\nIn the next chapter, we'll dig into [Configuration Management in Spring Boot](/articles/configuration-management-in-spring-boot), including a closer look at `@Value` and externalized configuration.\n"])</script>
1<script>self.__next_f.push([1,"8b:T132c,"])</script>
1<script>self.__next_f.push([1,"\nIn the [previous tutorial](/articles/spring-boot/getting-started-with-spring-boot), we discussed the basics of Spring Boot and generated a Spring Boot project using the Spring Initializer. In this section, we will discuss the project structure and various components of a Spring Boot project.\n\n## Application Structure\n\nSpring Boot is an opinionated framework that makes the development process very easy since we don’t have to choose the versions of different dependencies based on the version of Spring framework, its all taken care of by Spring Boot.\n\nThe project structure looks as follows:\n\n![](/media/articles/2/project-structure-1024x495.png)\n\n## Main Application Class\n\nThe main application class is the entry point to the application. It is located in a root package above other classes. The main application class is responsible for initializing the Spring application context and starting the Spring application.\n\nThe @SpringBootApplication annotation is often placed on your main class, and it implicitly defines a base “search package” for certain items. For example, if you are writing a JPA application, the package of the @SpringBootApplication annotated class is used to search for @Entity items. Using a root package also allows the component scan to apply only to your project.\n\n```java\npackage com.example.hellospringboot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class HelloSpringBootApplication {\n\n    public static void main(String[] args) {\n        SpringApplication.run(HelloSpringBootApplication.class, args);\n    }\n\n}\n```\n\nA single @SpringBootApplication annotation can be used to enable those three features, that is:\n\n-   @EnableAutoConfiguration: enable Spring Boot’s auto-configuration mechanism\n-   @ComponentScan: enable @Component scan on the package where the application is located\n-   @SpringBootConfiguration: enable registration of extra beans in the context or the import of additional configuration classes.\n\nWe recommend that you follow Java’s recommended package naming conventions and use a reversed domain name (for example, com.example.project).\n\n## The build.gradle file\n\nThe build.gradle must be located at the root of the application as we can see in the above project structure.\n\n```groovy\nplugins {\n    id 'org.springframework.boot' version '2.6.6'\n    id 'io.spring.dependency-management' version '1.0.11.RELEASE'\n    id 'java'\n}\n\ngroup = 'com.example'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = '11'\n\nrepositories {\n    mavenCentral()\n}\n\ndependencies {\n    implementation 'org.springframework.boot:spring-boot-starter-web'\n    testImplementation 'org.springframework.boot:spring-boot-starter-test'\n}\n\ntasks.named('test') {\n    useJUnitPlatform()\n}\n```\n\n## Spring Boot Application Properties\n\nVarious properties can be specified inside your application.properties file, inside your application.yml file, or as command-line switches.\n\nThe application.properties file is located in the src/main/resources directory. The properties are defined as key-value pairs. Where the key is the property name and the value is the property value.\n\nFor, eg.\n\n```text\nserver.port=8080\nserver.contextPath=/\n\nspring.activemq.broker-url=tcp://localhost:61616\nspring.activemq.user=admin\nspring.activemq.password=password\n\nspring.datasource.driver-class-name=org.h2.Driver\nspring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1\nspring.datasource.password=root\nspring.datasource.username=admin\nspring.datasource.type=mysql\n```\n\nCheck out the list of common Spring Boot properties and references to the underlying classes that consume them [here](https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html).\n\n## Static Content\n\nIn a spring boot web application, static files like HTML, CSS, JavaScript, and images files can be served directly from any of the following classpath locations out of the box. No configuration is required.\n\nLet’s look at the resources folder in the above project structure. This directory, as the name suggests, is dedicated to all the static resources, templates, and property files.\n\n-   resources/static – contains static resources such as CSS, js, and images.\n-   resources/templates – contains server-side templates which are rendered by Spring.\n\n## Templates\n\nSpring supports the following template engines by default. Templates are used with we have to build a dynamic website using SpringBoot. These templates can be activated using appropriate SpringBoot starters.\n\n-   **FreeMarker** – spring-boot-starter-freemarker\n-   **Groovy** – spring-boot-starter-groovy\n-   **Thymeleaf** – spring-boot-starter-thymeleaf\
1n-   **Mustache** – spring-boot-starter-mustache\n\nAll these template engines will resolve their template files from the path src/main/resources/template.\n"])</script>
1<script>self.__next_f.push([1,"8c:T20bc,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial covers the introduction to the Spring Boot framework, the benefits the Spring Framework offers, and the Spring Boot starter project. This tutorial is intended for developers who are new to Spring Boot and want to get started quickly.\n\n## What is Java Spring Boot?\n\nSpring Boot Framework is a popular, open-source, enterprise-level framework for creating standalone, production-grade applications that run on the Java Virtual Machine (JVM). It requires minimal or zero configuration and is easy to get started. It is a widely popular choice among Java developers for developing microservices and web applications.\n\nIt inherits the features like dependency Injection or Inversion of Control (IoC) from the Spring Framework and provides a rich set of features like RESTful web services, transaction management, caching, and more.\n\nSpring Framework also offers built-in support for typical tasks that an application needs to perform, such as data binding, type conversion, validation, exception handling, resource and event management, internationalization, and more.\n\nIt integrates with various Java EE technologies such as RMI, AMQP (Advanced Message Queuing Protocol), Java Web Services, and others.\n\n## Spring Boot Features\n\n-   Autoconfiguration\n-   Embed Tomcat, Jetty (no need to deploy WAR files)\n-   Provides ‘starter’ dependencies to simplify your build configuration\n-   Automatically configure Spring and 3rd party libraries whenever possible\n-   Provide production-ready features such as metrics, health checks, and externalized configuration\n-   Absolutely no code generation and no requirement for XML configuration\n\n**Autoconfiguration:** Springboot applications are initialized with pre-set dependencies that you don’t have to configure manually. As Java Spring Boot comes with built-in autoconfiguration capabilities, it automatically configures both the underlying Spring Framework and third-party packages as necessary for your application. This helps you to reduce the errors possibly caused by misconfiguration and make the developers more productive.\n\n## Spring Boot vs. Spring Framework\n\nThe biggest advantages of using Spring Boot versus Spring Framework alone are ease of use and faster development. However, this comes at the expense of the greater flexibility you get from working directly with Spring Framework.\n\nIn practice, unless you need or want to implement a very unique configuration, using Spring Booth is worth the tradeoff. It lets you easily inject extra dependencies into your application if something is not present in the Spring Starter bundle.\n\nAnd, you still get access to all Spring Framework features, including easy event handling, validation, data binding, type conversion, and built-in security and testing capabilities. Bottom line, Spring Boot can significantly streamline the development process and remove the fuss about the configurations.\n\n## Spring Boot Starters\n\nSpring Boot Starters are a set of convenient dependency descriptors which can be easily included in any level of application. These starters work as a bootstrapping process for the Spring-related technologies, we no longer need to worry about the dependencies and they will be automatically managed by Spring Boot Starters.\n\nSpring Boot starters follow a similar naming pattern: `spring-boot-starter-XYZ`, where XYZ denotes a particular type of application.\n\nE.g. Spring Boot starters:\n\n-   **spring-boot-starter-web** – RESTful web services using Spring MVC and embedded Tomcat container.\n-   **spring-boot-starter-data-jpa** – Manage relational data from Spring boot\n-   **org.springframework.boot:spring-boot-starter-security** – security implementation\n-   **org.springframework.boot:spring-boot-starter-activemq** – connect to ActiveMQ server\n\n## Spring Initializr\n\nSpring Initializr is a web-based tool provided by Pivotal. With the help of Spring Initializr, we can easily generate and download the Spring Boot Project template. Checkout online spring initial tool here [https://start.spring.io](https://start.spring.io)\n\n![](/media/articles/3/Screenshot-2022-04-16-at-20.38.25-1024x658.png)\n\n## Creating First Spring Boot Application\n\nNow that we understand the basics of Spring Boot, let’s create our first Spring Boot application.\n\nFor developing a spring boot application, you need the following **prerequisites**:\n\n-   Java8 must be installed on your machine.\n-   Need an IDE for writing code. I prefer IntelliJ IDEA. You can download a community edition if you don’t have it already.\n\nOnce the above prerequisites are satisfied, you can start the development process by following the steps below:\n\n-   Navigate to [https://start.spring.i](https://start.spring.i)o.\n-   Select the Maven or Gradle build type and select the language. I’ve selected, Gradle with Java.\n-   Select the Spring boot version. At the time of writing this article, Spring Boot 2.6.6 was the latest release version.\n-   Provide the details like group name. Usually the reverse of your domain. If your domain is example.com, your group name will be `com.example`\n-   The artifact name is the name of the jar without a version. For example, if your artifact name is my-app, then the jar will be my-app-1.0.0.jar.\n-   Provide a name for your application. Let’s call it a “hello-spring-boot” app.\n-   Select the version of Java you want to use. I’ve selected Java 8.\n-   On the right-hand side, you will see the list of dependencies. You can add any of the starter dependencies you want to your project. For eg. in this case, we want to build a web application, so we need to add spring-boot-starter-web.\n\nOnce the above details are filled 
1in, you can click on the “**Generate**” button. This will download a new Spring Boot project with the configuration you’ve selected. Now, you can extract the zip file and open the project in your IntelliJ IDEA.\n\n## Build and Run Spring Boot Application\n\n**For Gradle projects**  \nFor Gradle projects, you can build and run the project by following the steps below:\n\nBuild spring boot application into an executable jar\n\n```bash\n./gradlew build\n```\n\nStart/Run spring boot application\n\n```bash\n./gradlew bootRun\n```\n\n**For Maven projects**  \nIf you’re using maven based build, you can build and run the project by following the steps below:\n\nBuild spring boot application into an executable jar\n\n```bash\n./mvnw clean package\n```\n\nStart/Run spring boot application\n\n```bash\n./mvnw spring-boot:run\n```\n\nWhen you run your Spring Boot application, you will see a log message like this:\n\n```text\n    . ____ _ __ _ _\n    /\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\\n    ( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\\n    \\/ ___)| |_)| | | | | || (_| | ) ) ) )\n    ' |____| .__|_| |_|_| |_\\__, | / / / /\n    =========|_|==============|___/=/_/_/_/\n    :: Spring Boot :: (v2.6.6)\n\n    2022-04-16 17:17:14.805 INFO 25315 --- [ main] c.e.h.HelloSpringBootApplication : Starting HelloSpringBootApplication\n    using Java 11.0.11 on BLR-P7111831LP.local with PID 25315\n    (/Users/Neel/spring-boot-examples/hello-spring-boot/build/classes/java/main started by\n    p7111831 in /Users/Neel/spring-boot-examples/hello-spring-boot)\n    2022-04-16 17:17:14.807 INFO 25315 --- [ main] c.e.h.HelloSpringBootApplication : No active profile set, falling back to\n    1 default profile: \"default\"\n    2022-04-16 17:17:15.347 INFO 25315 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with\n    port(s): 8080 (http)\n    2022-04-16 17:17:15.353 INFO 25315 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]\n    2022-04-16 17:17:15.354 INFO 25315 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine:\n    [Apache Tomcat/9.0.60]\n    2022-04-16 17:17:15.416 INFO 25315 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded\n    WebApplicationContext\n    2022-04-16 17:17:15.417 INFO 25315 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext:\n    initialization completed in 570 ms\n    2022-04-16 17:17:15.681 INFO 25315 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080\n    (http) with context path ''\n    2022-04-16 17:17:15.692 INFO 25315 --- [ main] c.e.h.HelloSpringBootApplication : Started HelloSpringBootApplication in\n    1.148 seconds (JVM running for 1.61)\n```\n"])</script>
1<script>self.__next_f.push([1,"8d:T586,"])</script>
1<script>self.__next_f.push([1,"\nThe Spring Boot framework provides the default embedded server (Tomcat) to run the Spring Boot application. It runs on port 8080. It is possible to change the port in Spring Boot.\n\nIf you want to change the default port you have several options. But using `application.properties` option is recommended to overwrite default values.\n\nTo override the default port, we need to specify `server.port` property in application.properties file.\n\n#### Changing Default Port in Spring Boot\n\nIn the `application.properties` file, we can set a custom port number for the property server.port\n\n```properties\nserver.port = 9090\n```\n\nIn the application.yml file, you can find as follows −\n\n```yaml\nserver:\n    port: 9090\n```\n\n#### Running Spring Boot in Random Port\n\nIn the `application.properties` file, we can set a random port number for the property `server.port`\n\n```properties\nserver.port = 0\n```\n\nIn the `application.yml file`, you can find it as follows −\n\n```yaml\nserver:\n   port: 0\n```\n\n**Note** − If the server.port number is 0 while starting the Spring Boot application, Tomcat uses the random port number based on the availability.\n\n#### Using Command-Line Arguments\n\nWe can also set the server port using the java command line argument as follows.\n\n```bash\njava -jar spring-boot-app.jar --server.port=8009\n```\n\nor by using the equivalent syntax:\n\n```bash\njava -jar -Dserver.port=8009 spring-boot-app.jar\n```\n"])</script>
1<script>self.__next_f.push([1,"8e:T18e5,"])</script>
1<script>self.__next_f.push([1,"\nRestTemplate is a synchronous client to make HTTP request from Spring Boot application. It simplifies the process of making HTTP requests and handling the responses by providing a higher-level abstraction.\n\nTo consume a REST API using RestTemplate in a Spring Boot application, you need to first add the RestTemplate dependency in your project. If you're using Maven, add the following dependency to your pom.xml file.\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.springframework.boot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-web\u003c/artifactId\u003e\n\u003c/dependency\u003e\n```\n\n**Depreciation** **Notice!!**\n\nA modern version of the HTTP client called WebClient has been introduced in Spring 5. It is an alternative to RestTemplate. It provides both synchronous and asynchronous API’s to make the REST calls more efficient.\n\nIf you’re developing a new application or migrating an old one, it is recommended to use [WebClient](/articles/what-is-webclient-how-to-use-webclient-in-java-springboot) over RestTemplate. RestTemplate will be deprecated 
1in future versions.\n\nRestTemplate provides a variety of methods for making HTTP calls to RESTful APIs. Here are some commonly used methods:\n\n-   **getForObject()**: This method performs a GET request and returns the response body as an object of the specified type. It's typically used when you expect the response body to be deserialized into a single object.\n\n```java\nT response = restTemplate.getForObject(url, responseType);\n```\n\n-   **getForEntity()**: Similar to getForObject(), this method performs a GET request and returns the entire response as a ResponseEntity object. It provides access to the response body, headers, and status code.\n\n```java\nResponseEntity response = restTemplate.getForEntity(url, responseType);\n```\n\n-   **postForObject()**: This method performs a POST request and sends the request body along with the request. It returns the response body as an object of the specified type.\n\n```java\nT response = restTemplate.postForObject(url, request, responseType);\n```\n\n-   **postForEntity()**: Similar to postForObject(), this method performs a POST request and returns the entire response as a ResponseEntity object.\n\n```java\nResponseEntity\u003cT\u003e response = restTemplate.postForEntity(url, request, responseType);\n```\n\n-   **put()**: This method performs a PUT request to update a resource on the server. It sends the request body and returns the response as a ResponseEntity.\n\n```java\nResponseEntity\u003cVoid\u003e response = restTemplate.put(url, request);\n```\n\n-   **delete()**: This method performs a DELETE request to delete a resource on the server. It does not expect a response body and returns a ResponseEntity.\n\n```java\nResponseEntity\u003cVoid\u003e response = restTemplate.delete(url);\n```\n\n-   **exchange()**: This method is a more flexible option that allows you to perform any HTTP method (GET, POST, PUT, DELETE, etc.) and provides full control over the request and response. It returns a ResponseEntity object.\n\n```java\nHttpEntity\u003cRequestType\u003e requestEntity = new HttpEntity\u003c\u003e(request, headers);\nResponseEntity\u003cResponseType\u003e response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);\n```\n\nThese are just a few examples of the methods provided by RestTemplate. RestTemplate also supports methods for handling HTTP headers, handling file uploads, setting query parameters, handling authentication, and more.\n\n## Consuming the GET API\n\nIn the given example, we are fetching the API response as a JSON String. We need to use ObjectMapper to parse it to the POJO before using it in the application.\n\ngetForObject() method is pretty useful when we are getting an unparsable response from the server, and we have no  \ncontrol to get it fixed on the server-side. Here, we can get the response as String, and use a custom parser or use a string replacement function to fix the response before handling it to the parser.\n\nIn the course of this tutorial, we will create simple `RestTemplate` bean in the application.\n\n```java\n@Service\npublic class ProductService {\n\n    private static final String POST_API = \"https://fakestoreapi.com/products\";\n    private static final String GET_API = \"https://fakestoreapi.com/products/{productId}\";\n    private static final String DELETE_API = \"https://fakestoreapi.com/products/{productId}\";\n\n    private final RestTemplate restTemplate;\n\n    public ProductService(RestTemplateBuilder restTemplateBuilder) {\n        this.restTemplate = restTemplateBuilder.build();\n    }\n}\n```\n\n#### Consuming APIs as String\n\n```java\nMap\u003cString, String\u003e params = new HashMap\u003c\u003e();\nparams.put(\"productId\", productId);\nString result = restTemplate.getForObject(GET_API, String.class, params);\n```\n\n#### Consuming APIs response to POJO\n\n```java\nMap\u003cString, String\u003e params = new HashMap\u003c\u003e();\nparams.put(\"productId\", productId);\n\nProduct result = restTemplate.getForObject(GET_API, Product.class, params);\n```\n\n#### Using getForEntity() Method\n\n```java\nMap\u003cString, String\u003e params = new HashMap\u003c\u003e();\nparams.put(\"productId\", productId);\nResponseEntity\u003cProduct\u003e result = restTemplate.getForEntity(GET_API, Product.class, params);\n\nHttpStatus statusCode = result.getStatusCode();\nProduct product = result.getBody();\n```\n\n#### Sending HTTP Headers using RestTemplate\n\n```java\nHttpHeaders headers = new HttpHeaders();\nheaders.setAccept(List.of(MediaType.APPLICATION_JSON));\nheaders.set(\"X-API-KEY\", \"YOUR_API_KEY\");\nHttpEntity\u003cString\u003e httpEntity = new HttpEntity\u003c\u003e(headers);\n\nMap\u003cString, String\u003e params = new HashMap\u003c\u003e();\nparams.put(\"productId\", productId);\n\nResponseEntity\u003cProduct\u003e result = restTemplate.exchange(GET_API, HttpMethod.GET, httpEntity,\n                    Product.class, params);\nreturn result.getBody();\n```\n\n## Consuming the POST API\n\n```java\nHttpHeaders headers = new HttpHeaders();\nheaders.set(\"X-API-KEY\", \"YOUR_API_KEY\");\nheaders.setContentType(MediaType.APPLICATION_JSON);\nHttpEntity\u003cProduct\u003e httpEntity = new HttpEntity\u003c\u003e(product, headers);\n\nProduct createdProduct = restTemplate.postForObject(POST_API, httpEntity, Product.class);\n```\n\n## Consuming the PUT API\n\n```java\nMap\u003cString, String\u003e params = new HashMap\u003c\u003e();\nparams.put(\"productId\", product.getId());\n\nrestTemplate.put(GET_API, product, params);\n```\n\n## Consuming the DELETE API\n\n```java\nMap\u003cString, String\u003e params = new HashMap\u003c\u003e();\nparams.put(\"productId\", productId);\n\nrestTemplate.delete(GET_API, params);\n```\n"])</script>
1<script>self.__next_f.push([1,"8f:T1eb0,"])</script>
1<script>self.__next_f.push([1,"\nSpring boot offers multiple options, for executing your code during the application startup. This post covers some of the ‘out of the box’ practices recommended by the Spring developers. There are mainly 3 options\n\n1.  Using @PostConstruct annotation\n\n2.  Using ApplicationRunner or Command Line Runner Interface\n\n3.  Option-3: Using Spring Boot Events\n\nIn this article, we will cover all of the available options and look into the best practices dos and don't.\n\nLet us begin by creating a simple Spring Boot application.\n\n## Option-1: @PostConstruct Annotation\n\nThe @**PostConstruct** annotation can be used on a method to indicate a spring that, this method should be executed after the bean is initialized.\n\nYou can add `@PostConstruct` annotation in your Spring boot main application class or from a `@Component` or a `@Service` class.\n\n@PostConstruct is mainly used to complete the initialization of your application. It is part of the Spring Boot Lifecycle.\n\n```java\n@Slf4j\n@SpringBootApplication\npublic class MyApplication {\n\n    public static void main(String[] args) {\n        SpringApplication.run(MyApplication.class, args);\n    }\n\n        @PostConstruct\n    public void int(){\n             log.info(\"MyApplication::init()\");\n        }\n}\n```\n\nPlease note that I am using the `@Slf4j` from the `Lombok` package for logging purposes.\n\nThe @PostConstruct is mainly used to complete the initialization of your application. It is part of the Spring Boot Lifecycle. This can be used to execute code on startup, but it is not as common as the other two options.\n\nHere is how the logs will be printed:\n\n```text\nINFO 81697 - [main] com.stacktips.MyApplication              : Starting MyApplication using Java 17.0.7 on N-Panigrahy.local with PID 81697\nINFO 81697 - [main] com.stacktips.MyApplication              : No active profile set, falling back to 1 default profile: \"default\"\nINFO 81697 - [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)\nINFO 81697 - [main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]\nINFO 81697 - [main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.65]\nINFO 81697 - [main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext\nINFO 81697 - [main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 824 ms\nINFO 81697 - [main] com.stacktips.MyApplication              : MyApplication::run()\nINFO 81697 - [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''\nINFO 81697 - [main] com.stacktips.MyApplication              : Started MyApplication in 1.457 seconds (JVM running for 1.693)\n```\n\nIf you want to execute some long-running tasks, you should avoid this approach.\n\nNow let's review the second option.\n\n## Option-2: Using ApplicationRunner or Command Line Runner Interface\n\nBoth `ApplicationRunner` and `CommandLineRunner` is the recommended method if you have to execute some code after the initialization of the application.\n\nBoth the `CommandLineRunner` and `ApplicationRunner` are functional interface that provides a `run()` method. The run method is called after the Spring application context is initialized.\n\nLet's see how to implement that.\n\n```java\n@Slf4j\n@Component\npublic class AppRunner1 implements ApplicationRunner {\n\n    @Override\n    public void run(ApplicationArguments args) throws Exception {\n        log.info(\"AppRunner1:run() \");\n    }\n}\n```\n\nYou could implement the `ApplicationRunner` in your main class as well, but I would like to separate it into a dedicated class.\n\n**ApplicationRunner:** This is similar to the `CommandLineRunner` interface, but it provides an `ApplicationArguments` object that contains the command-line arguments that were passed to the application. This can be useful if you need to access the command-line arguments in your startup code.\n\nYou could have multiple `ApplicationRunner` implementations in your code.\n\n```java\n@Slf4j\n@Component\npublic class AppRunner2 implements ApplicationRunner {\n\n    @Override\n    public void run(ApplicationArguments args) throws Exception {\n        log.info(\"AppRunner2:run()\");\n    }\n}\n```\n\nBut where there are multiple runners, spring doesn’t know which order they should execute. if you want to preserve the order of execution for the application runners, you can do that using the  `@Order(1)` annotation.\n\nHere is how our logs will be printed now\n\n```text\nINFO 81697 - [main] com.stacktips.MyApplication              : Starting MyApplication using Java 17.0.7 on N-Panigrahy.local with PID 81697\nINFO 81697 - [main] com.stacktips.MyApplication              : No active profile set, falling back to 1 default profile: \"default\"\nINFO 81697 - [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)\nINFO 81697 - [main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]\nINFO 81697 - [main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.65]\nINFO 81697 - [main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext\nINFO 81697 - [main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 824 ms\nINFO 81697 - [main] com.stacktips.MyApplication              : MyApplication::run()\nINFO 81697 - [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''\nINFO 81697 - [main] com.stacktips.MyApplication              : Started MyApplication in 1.457 seconds (JVM running for 1.693)\nINFO 81697 - [main] com.stacktips.AppRunner2                 : App
1Runner2::run()\nINFO 81697 - [main] com.stacktips.AppRunner                  : AppRunner::run()\n```\n\n## Option-3: Using Spring Boot Events\n\nThe Spring Boot application provides a number of events that are published during the application lifecycle. We can register a listener for one of these events and execute code in the listener's `onApplicationEvent()` method.\n\n```java\n@Slf4j\n@Component\npublic class ApplicationStartEvent {\n\n    @EventListener(ApplicationReadyEvent.class)\n    public void onReadyEvent(){\n        log.info(\"ApplicationStartEvent::onReadyEvent()\");\n    }\n\n}\n```\n\nNow if we run all three options together, this is what the output looks like.\n\n```text\nINFO 81697 - [main] com.stacktips.MyApplication              : Starting MyApplication using Java 17.0.7 on N-Panigrahy.local with PID 81697\nINFO 81697 - [main] com.stacktips.MyApplication              : No active profile set, falling back to 1 default profile: \"default\"\nINFO 81697 - [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)\nINFO 81697 - [main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]\nINFO 81697 - [main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.65]\nINFO 81697 - [main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext\nINFO 81697 - [main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 824 ms\nINFO 81697 - [main] com.stacktips.MyApplication              : MyApplication::run()\nINFO 81697 - [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''\nINFO 81697 - [main] com.stacktips.MyApplication              : Started MyApplication in 1.457 seconds (JVM running for 1.693)\nINFO 81697 - [main] com.stacktips.AppRunner2                 : AppRunner2::run()\nINFO 81697 - [main] com.stacktips.AppRunner                  : AppRunner::run()\nINFO 81697 - [main] com.stacktips.ApplicationStartEvent      : ApplicationStartEvent::onReadyEvent()\n```\n"])</script>
1<script>self.__next_f.push([1,"90:T17b3,"])</script>
1<script>self.__next_f.push([1,"\nWhen you expose a set of REST API endpoints, documentation of those endpoints is quite essential for the API consumers. Some companies follow the documentation first approach, where the documentation tool such as RAML, or Swagger is used to generate the API specification before proceeding with development.\n\nWhile some other companies do the documentation as the API endpoints are being developed. This is where the Swagger2 comes into the picture. While there are some downsides to this approach, there are many benefits Swagger has to offer. Every change in the API should be simultaneously described in the reference documentation. Accomplishing this manually is a tedious exercise, so automation of the process makes it easy to maintain the documentation.\n\n## What is Swagger\n\nSwagger is widely used for visualizing APIs, and Swagger UI provides an online sandbox for frontend developers. A swagger is a tool, a specification, and a complete framework implementation for producing the visual representation of RESTful Web Services.\n\nWhen Swagger is property configured and annotated in your project, a consumer can understand and interact with the remote service from the Swagger UI with a minimal amount of implementation logic. Thus Swagger removes the guesswork in calling the service.\n\n## Configure Swagger2 in Spring Boot\n\nFor the tutorial, we will use the `springfox-boot-starter` dependency to enable the Swagger2 in your Spring boot project.\n\nIf you’re using maven based project, then add the following dependency into your `pom.xml` file\n\n```xml\n\u003cdependency\u003e\n   \u003cgroupId\u003eio.springfox\u003c/groupId\u003e\n   \u003cartifactId\u003espringfox-boot-starter\u003c/artifactId\u003e\n   \u003cversion\u003e3.0.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nIf your using gradle build system, you need to add these into your `build.gradle` file.\n\n```groovy\nimplementation 'io.springfox:springfox-boot-starter:3.0.0'\n```\n\n## Enable the Swagger2\n\nTo enable the Swagger 2 we need to use the `@EnableSwagger2` annotation. Add the following configuration class to your spring boot project.\n\n```java\n@Configuration\n@EnableSwagger2\npublic class SwaggerConfig {\n\n    @Bean\n    public Docket postsApi() {\n        ApiInfo apiInfo = new ApiInfoBuilder()\n                .title(\"Product API\")\n                .description(\"Product REST API documentation\")\n                .version(\"1.0.0\")\n                .build();\n\n        return new Docket(DocumentationType.SWAGGER_2)\n                .select()\n                .apis(RequestHandlerSelectors.basePackage(\"com.example.kitchensink.api\"))\n                .paths(PathSelectors.any())\n                .build()\n                .apiInfo(apiInfo)\n                .enable(true);\n    }\n}\n```\n\n**Notes:**\n\n-   The Springfox library automatically scans all the API resources defined in the application via @Controller components and adds them to the “documentation index”.\n-   A Docket bean is defined and using its select() method we get an instance of ApiSelectorBuilder. ApiSelectorBuilder we configure the endpoints exposed by Swagger.\n-   After the Docket bean is defined, it’s select() method returns an instance of ApiSelectorBuilder, which provides a way to control the endpoints exposed by Swagger.\n-   Using the RequestHandlerSelectors and PathSelectors we configure the predicates for the selection of RequestHandlers.\n\n## Sring boot Controller\n\nHere is how my controller code looks like.\n\n```java\n@RestController\n@RequestMapping(value = \"/api/products/1.0\", produces = {MediaType.APPLICATION_JSON_VALUE})\n@RequiredArgsConstructor\npublic class ProductController {\n    private final ProductService stockService;\n\n    @GetMapping(\"/products/search\")\n    public ResponseEntity\u003cList\u003cProduct\u003e\u003e search(\n            @RequestParam(defaultValue = \"1\", required = false) int page,\n            @RequestParam(defaultValue = \"50\", required = false) int size,\n            @RequestParam(required = false) String category) throws IOException {\n\n        return ResponseEntity.ok(stockService.searchProducts(page, size, category));\n    }\n\n    @GetMapping(path = \"/products\")\n    public ResponseEntity\u003cList\u003cProduct\u003e\u003e products() throws IOException {\n        return ResponseEntity.ok(stockService.getProducts());\n    }\n\n    @GetMapping(path = \"/products/{productId}\")\n    public ResponseEntity\u003cProduct\u003e productById(@PathVariable String productId) throws IOException {\n\n        return ResponseEntity.ok(stockService.findProductById(productId));\n    }\n\n    @PostMapping(path = \"/products\", consumes = {MediaType.APPLICATION_JSON_VALUE})\n    public ResponseEntity\u003cProduct\u003e createProduct(@Validated @RequestBody ProductDto productDto)\n            throws URISyntaxException {\n\n        final Product product = stockService.creteProduct(productDto);\n        return ResponseEntity\n                .created(new URI(\"/api/products/1.0/products/\" + product.getId()))\n                .body(product);\n    }\n\n    @DeleteMapping(path = \"/products\")\n    public ResponseEntity\u003cResponseType\u003e deleteProduct(@RequestParam long productId) {\n\n        boolean result = stockService.deleteProduct(productId);\n        return ResponseEntity.ok(result ? ResponseType.SUCCESS : ResponseType.FAILURE);\n    }\n}\n```\n\nBasically, I have not made any changes to my Controller class. Additional configuration can be done in your controllers, to generate more descriptive documentation. But we will c
1over that in the next post.\n\n## Test the Swagger UI\n\nThat is all needed for now to generate the swagger documentation for your project.\n\nNow that we’ve configured Swagger, the spring boot will expose `/v2/api-docs` under the hood. Let us run the project and hit [http://localhost:8080/v2/api-docs](http://localhost:8080/v2/api-docs) in your browser to test.\n\nTo access Swagger UI for our API documentation, visit  \n[http://localhost:8080/swagger-ui/#](http://localhost:8080/swagger-ui/#).\n\n![](/media/articles/7/Swagger-UI-1024x619.png)\n\n## Download Project on Github\n\nCheck out the complete source code for this example [here on Github.](https://github.com/npanigrahy/spring-boot-examples/tree/main/kitchensink-api-swagger2)\n"])</script>
1<script>self.__next_f.push([1,"91:T467,\nThe git `diff` command helps you see, compare, and understand changes in your project before you can push your code to the server. It can be used to look at current changes in your working copy, past changes in commits, or even to compare branches.\n\nIn this short article, we’ll talk about the most important use cases you need in your daily work.\n\n## Look for what changed since I last committed?\n\nRunning the plain git diff command without any parameters can be pretty helpful: it will show you all of your local changes since you last committed.\n\n```bash\n$ git diff\n```\n\nWhen you want to do a git diff but do not care about the full diff and just want to know which files changed\n\n```bash\n$ git diff --name-only\n```\n\nTo include some brief information about changed lines\n\n```bash\n$ git diff --stat\n```\n\n## View changes in staging area?\n\nBy adding the `--staged` option, Git will show which local changes you have already added to Staging Area, via “git add”:\n\n\\# Staged changes in a certain file…\n\n```bash\n$ git diff --staged index.html\n```\n\n\\# Staged changes in all local files…\n\n```bash\n$ git diff --staged\n```\n92:Te4b,"])</script>
1<script>self.__next_f.push([1,"\n## What is the Same Origin Policy?\n\nThe same-origin policy (SOP) is a browser security feature that restricts how scripts from one origin can interact with resources from another origin. An origin is defined as a combination of the hostname, port number and URI scheme.\n\nThese security restrictions are implemented in all modern browsers that disallow the cross-domain web Service calls using Ajax.  If you attempt to make cross-origin resources call, the browser will return the following error:\n\n```text\nXMLHttpRequest cannot load URL.\nOrigin http://yourwebserver.com is not allowed by Access-Control-Allow-Origin.\nVisit the below link for more details on browser security policy: \u003ca\nhref=\"http://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy\" target=\"_blank\"\nrel=\"noopener noreferrer\"\u003eSame-origin policy.\u003c/a\u003e\n```\n\nThe solution to the above problem is JSONP.\n\n## What is JSONP?\n\nJSONP (JSON with Padding) allows you to overcome these cross-domain restrictions and allows data to be retrieved from other different origins. \n\n## Working with JSONP in Spring\n\nSince the Spring version 4.2 release, the JSONP is inbuilt into the Spring framework. In order to enable JSONP support for spring controllers, We need to declare an `@ControllerAdvice` bean that extends `AbstractJsonpResponseBodyAdvice`.\n\nAdd the following class alongside your spring config to supp
1ort JSONP requests.\n\n```java\nimport org.springframework.web.bind.annotation.ControllerAdvice;\nimport org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;\n\n@ControllerAdvice\npublic class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {\n    public JsonpAdvice() {\n        super(\"callback\");\n    }\n}\n```\n\nWith such `@ControllerAdvice` bean registered, it will be possible to request the JSON web service from another domain using a `\u003cscript\u003e` tag.\n\nLet us consider the following post resource for our example:\n\n```java\npublic class Post {\n  private int id;\n  private String title;\n  private String excerpt;\n  private String body;\n}\n```\n\n## Spring Controller\n\nWe do not have to make any changes to the REST controller methods. For the sake of simplicity and limited scope of this article, we’re skipping the full implementation of `getPost()` method.\n\n```java\n@RequestMapping(value = \"/api/1.0/posts/{postId}\",\n                      method = RequestMethod.GET,\n                      produces = MediaType.APPLICATION_JSON_VALUE)\npublic ResponseEntity getPost(@PathVariable(\"postId\") long postId) {\n    return new ResponseEntity(postService.getPostById(postId), HttpStatus.OK);\n}\n```\n\nNow we can access the posts list resources via regular REST call or using JSON API call.\n\n## Testing Controllers\n\nAccessing REST Resource:\n\n```bash\n$ curl -X GET http://localhost:8080/api/1.0/posts/1\n```\n\n**Response:** 200 OK\n\n```json\n{\n    \"id\": 1,\n    \"title\": \"Hello World!!\",\n    \"excerpt\": \"Lorem ipsum dolor sit amet\",\n    \"description\": \"Lorem ipsum dolor sit amet, ...\"\n}\n```\n\nAccessing REST Resource using JSONP:\n\n```bash\n$ curl -X GET http://localhost:8080/api/1.0/posts/1?callback=postCallback\n```\n\n**Response:** 200 OK\n\n```json\npostCallback({\n    \"id\": 1,\n    \"title\": \"Hello World!!\",\n    \"excerpt\": \"Lorem ipsum dolor sit amet\",\n    \"description\": \"Lorem ipsum dolor sit amet, ...\"\n})\n```\n\nNotice the difference in the results for both cases. When the resource is accessed using JSONP, the response is returned as JSONP payload as a JavaScript method.\n\nIf you want to access it from another domain, we can use it as\n\n```html\n\u003cscript src=\"http://localhost:8080/api/1.0/posts/1?callback=postCallback\"\n          type=\"application/javascript\"/\u003e\n```\n"])</script>
1<script>self.__next_f.push([1,"93:T6f3,"])</script>
1<script>self.__next_f.push([1,"\nHTTP compression is a capability that can be built into web servers and web clients to improve transfer speed and save bandwidth utilisation. The commonly used compression is **GZIP**.\n\nBy default, the `gzip` compression is disabled in the Spring Boot application. However, we can enable compression using a few property changes.\n\n## Enable GZIP Compression\n\nAdd the following configuration to your Spring Boot [`application.properties`](http://application.properties) file to enable gzip response compression.\n\n```properties\n# Enable response compression\nserver.compression.enabled=true\n\n# Mime types that should be compressed\nserver.compression.mime-types=text/xml, text/css, text/javascript, application/json\n```\n\nThis configuration will enable the gzip compression for all responses for the given mime types defined in the property file.\n\n💡\n\nPlease note, that the wildcard in mime types is not supported. So we need to provide the list of mime types explicitly.\n\nThe `gzip` operation consumes time and other server resources. You may enable the compression only when the response size exceeds a specific limit. This can be configured using the following property.\n\n```properties\n# Minimum response where compression will kick in\nserver.compression.min-response-size=4096\n```\n\n## Exclude user agents from the compression\n\nYou can also exclude the specific user agents using `excluded-user-agents` configuration.\n\n```properties\nserver.compression.excluded-user-agents= Mozilla/5.0\n```\n\nIf you are using a YAML-based configuration, all the above properties can be written as follows:\n\n```yaml\nserver:\n  compression:\n    enabled: true\n    mime-types: text/xml, text/css, text/javascript, application/json\n    min-response-size: 1024\n    excluded-user-agents: Mozilla/5.0\n```\n"])</script>
1<script>self.__next_f.push([1,"94:T187b,"])</script>
1<script>self.__next_f.push([1,"\nA list of some commonly used Git commands to get you going with Git.\n\n## 1. Configuring Git\n\nTo tell Git who you are, run the following two commands:\n\n```bash\n$ git config --global user.name \"King Kong\"\n$ git config --global user.email \"[email protected]\"\n```\n\nPretty colours for the git outputs in terminal:\n\n```bash\n$ git config --global color.ui true\n```\n\nGet the list of configurations:\n\n```bash\n$ git config --list\n```\n\n## 2. Checkout Remote Project\n\nCreate a local copy of a remote repository  \ngit clone ssh://[email protected]/\\[username\\]/\\[repository-name\\].git\n\n## 3. Adding Local Project to Git\n\nInitialize the local directory as a Git repository.\n\n```bash\n$ git init\n```\n\nAdd the files to your new local repository. This stages them for the first commit.\n\n```bash\n$ git add .\n```\n\nOr, alternatively, you can add one by one file\n\n```bash\n$ git add file1.txt file2.txt\n```\n\nTo unstage a file:\n\n```bash\n$ git reset HEAD file1.txt\n```\n\nCommit the files that you’ve staged in your local repository\n\n```bash\n$ git commit -m \"Initial commit\"\n```\n\nIn Terminal, add the URL for the remote repository where your local repository will be pushed. Sets the new remote\n\n```bash\n$ git remote add origin [REMOTE REPO URL]\n```\n\nVerifies the new remote URL\n\n```bash\n$ git remote -v\n```\n\nPush the changes in your local repository to GitHub.\n\n```bash\n$ git push -u origin master\n```\n\n## 4. Git Difference\n\nTo view file diff in git before commit:\n\n```bash\n$ git diff\n```\n\nWhen you want to do a git diff but do not care about the full diff and just want to know which files changed\n\n```bash\n$ git diff --name-only\n```\n\nTo include some brief information about changed lines\n\n```bash\n$ git diff --stat\n```\n\nThe output of –stat is nicely coloured. If you want a more machine-readable output\n\n```bash\n$ git diff --numstat\n```\n\n## 5. Read Previous Git Commit\n\nShow full log of the last commit:\n\n```bash\n$ git show\n```\n\nShow log of last commit (summary only):\n\n```bash\ngit log -1\n```\n\nIf you need just the commit message and nothing else.  \nMore elegantly – if you want a quick overview of your commits\n\n```bash\n$ git log -1 --pretty=%B\n```\n\nShow log of last N commit:\n\n```bash\n$ git log --oneline -5\n```\n\n## 6. Working with Git Branches\n\nView list local branches\n\n```bash\n$ git branch\n```\n\nView list of all\n\n```bash\n$ git branch -a\n```\n\nView list of remote branches\n\n```bash\n$ git branch -r\n```\n\n## 7. Sharing \u0026 Updating Projects\n\nPush a branch to your remote repository\n\n```bash\n$ git push origin \u003cbranch_name\u003e\n```\n\nPush changes to the remote repository (and remember the branch)\n\n```bash\n$ git push -u origin \u003cbranch_name\u003e\n```\n\nPush changes to the remote repository (remembered branch)\n\n```bash\n$ git push\n```\n\nDelete a remote branch\n\n```bash\n$ git push origin --delete \u003cbranch_name\u003e\n```\n\nUpdate local repository to the newest commit\n\n```bash\n$ git pull\n```\n\nPull changes from the remote repository\n\n```bash\n$ git pull origin \u003cbranch_name\u003e\n```\n\n## 8. Create and Manage Branches\n\nIf you’re a developer you probably have used it and are familiar with git workflow. Whenever you want to commit a bug or a new feature, you need to create a branch for it, which will be a copy of your master branch. Once your fixes are ready to merge, you typically create a pull request on your new branch. The reason for this is to keep your master branch clean all the time.\n\nHere is the list of some useful commands to help you create and manage a new branch. Please note, before creating a new branch, pull the changes from upstream. Your master needs to be up to date.  \nCreate a git branch.\n\n```bash\n$ git branch \u003cnew branch name\u003e\n```\n\nSwitch to a branch\n\n```bash\n$ git checkout \u003cbranch name\u003e\n```\n\nCreate the branch on your local machine and switch in this branch:\n\n```bash\n$ git checkout -b \u003cnew branch name\u003e\n```\n\nChange the working branch:\n\n```bash\n$ git checkout \u003cnew branch name\u003e\n```\n\nPush the branch to remote git:\n\n```bash\n$ git push origin \u003cnew branch name\u003e\n```\n\nWhen you want to commit something in your branch, be sure to be in your branch. Add -u parameter to set upstream.\n\nYou can see all the branches created by using :\n\n```bash\n$ git branch\n```\n\nAdd a new remote for your branch:\n\n```bash\n$ git remote add \u003cremote branch name\u003e\n```\n\nPush changes from your commit into your branch :\n\n```bash\n$ git push \u003cnew branch remote name\u003e  \u003cnew branch name\u003e\n```\n\nUpdate your branch when the original branch from the official repository has been updated:\n\n```bash\n$ git fetch \u003cremote branch name\u003e\n```\n\nThen you need to apply to merge changes if your branch is derivated from develop you need to do:\n\n```bash\n$ git merge \u003cname of remote branch\u003e/develop\n```\n\n## 9. Delete Branch\n\nDelete local branch: -d option stands for –delete\n\n```bash\ngit branch -d \u003cbranch_n
1ame\u003e\n```\n\nGit local branch force: -D option stands for –delete –force\n\n```bash\ngit branch -D \u003cbranch_name\u003e\n```\n\nDelete a remote GIT branch\n\n```bash\ngit push origin --delete \u003cbranch_name\u003e\n```\n\n## 10. Git Stashing\n\nIf you run git status, you can see your dirty state:\n\n```bash\n$ git status\n```\n\nNow you want to switch branches, but you don’t want to commit what you’ve been working on yet; so you’ll stash the changes. To push a new stash onto your stack, run git stash or git stash save:\n\n```bash\n$ git stash\n\n$ git stash save \"Stash message\"\n```\n\nAt this point, you can switch branches and do work elsewhere; your changes are stored on your stack. To see which stashes you’ve stored, you can use git stash list:\n\n```bash\n$ git stash list\n\nOutputs:\nstash@{0}: WIP on master: 049d078 added the index file\nstash@{1}: WIP on master: c264051 Revert \"added file_size\"\nstash@{2}: WIP on master: 21d80a5 added number to log\n```\n\nIn this case, two stashes were done previously, so you have access to three different stashed works. You can reapply the one you just stashed by using the command shown in the help output of the original stash command: git stash apply.\n\nIf you want to apply one of the older stashes, you can specify it by naming it, like this: git stash apply stash@{2}. If you don’t specify a stash, Git assumes the most recent stash and tries to apply it:\n\n```bash\n$ git stash apply\n\n$ git stash apply stash@{1}\n```\n\nDelete a particular stash.\n\n```bash\n$ git stash drop\n\n$ git stash drop stash@{0}\n```\n"])</script>
1<script>self.__next_f.push([1,"95:T1a8a,"])</script>
1<script>self.__next_f.push([1,"\nSpring Boot Web MVC configured to produce an executable WAR and ready for fully fledged web application development. In this tutorial, we will see how to use Apache Tiles3 framework in your Spring Boot Web MVC application.\n\nLet us start by creating an application based on spring-boot-starter-web. You may use spring initializer to create a basic project template.\n\n## 1. Spring Boot Dependencies\n\nAdd dependencies to the POM to pull in Tomcat, Jasper and Apache Tiles\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupid\u003eorg.springframework.boot\u003c/groupid\u003e\n    \u003cartifactid\u003espring-boot-starter-tomcat\u003c/artifactid\u003e\n    \u003cscope\u003eprovided\u003c/scope\u003e\n\u003c/dependency\u003e\n\u003cdependency\u003e\n    \u003cgroupid\u003eorg.apache.tomcat.embed\u003c/groupid\u003e\n    \u003cartifactid\u003etomcat-embed-jasper\u003c/artifactid\u003e\n    \u003cscope\u003eprovided\u003c/scope\u003e\n\u003c/dependency\u003e\n\u003cdependency\u003e\n    \u003cgroupid\u003eorg.apache.tiles\u003c/groupid\u003e\n    \u003cartifactid\u003etiles-jsp\u003c/artifactid\u003e\n    \u003cversion\u003e3.0.4\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nIf you’re using Gradle build system, you can add the following dependency to your `build.gradle` file.\n\n```groovy\ncompile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-jasper', version: '9.0.12'\nprovidedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'\ncompile group: 'org.apache.tiles', name: 'tiles-jsp', version: '3.0.8'\n```\n\nChange the packaging to WAR in the POM\n\n```xml\n\u003cpackaging\u003ewar\u003c/packaging\u003e\n```\n\nOr for gradle\n\n```groovy\napply plugin: 'war'\n```\n\n## 2. Project Directory Structure\n\nCreate Web application structure the Maven way (tree showing all files):\n\n```text\nExampleApp:\n    │   pom.xml\n    ├───src\n    │   ├───main\n    │   │   ├───java\n    │   │   │   └───com\n    │   │   │       └───example\n    │   │   │           └───app\n    │   │   │               │   ExampleApplication.java\n    │   │   │               │   TilesConfig.java\n    │   │   │               └───controller\n    │   │   │                       HelloWorldController.java\n    │   │   ├───resources\n    │   │   │       application.properties\n    │   │   └───webapp\n    │   │       ├───static\n    │   │       └───WEB-INF\n    │   │           └───tiles\n    │   │               │   tiles.xml\n    │   │               ├───layouts\n    │   │               │       basic.jsp\n    │   │               └───views\n    │   │                   │   footer.jsp\n    │   │                   │   header.jsp\n    │   │                   └───home\n    │   │                          greeting.jsp\n    │   │                          home.jsp\n    │   └───test\n    │\n    └───target\n```\n\n## 3. Tiles Configuration for Spring Boot\n\nConfigure tiles by adding a new configuration class – it will be pulled in by classpath scanning:\n\n```java\npackage com.example.app;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.servlet.view.tiles3.TilesConfigurer;\nimport org.springframework.web.servlet.view.tiles3.TilesView;\nimport org.springframework.web.servlet.view.tiles3.TilesViewResolver;\n\n@Configuration\npublic class TilesConfig {\n\n    @Bean\n    public TilesConfigurer tilesConfigurer() {\n        final TilesConfigurer configurer = new TilesConfigurer();\n        configurer.setDefinitions(new String[]{\"WEB-INF/tiles/tiles.xml\"});\n        configurer.setCheckRefresh(true);\n        return configurer;\n    }\n\n    @Bean\n    public TilesViewResolver tilesViewResolver() {\n        final TilesViewResolver resolver = new TilesViewResolver();\n        resolver.setViewClass(TilesView.class);\n        return resolver;\n    }\n}\n```\n\n## 4. Tiles Layout and Views Declaration\n\nCreate the tiles configuration file: `WEB-INF/tiles/tiles.xml`\n\n```xml\n\u003c!--?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?--\u003e\n\n\u003ctiles-definitions\u003e\n\n    \u003c!-- Templates --\u003e\n    \u003cdefinition name=\"layout.basic\" template=\"/WEB-INF/tiles/layouts/basic.jsp\"\u003e\n        \u003cput-attribute name=\"title\" value=\"Spring Web MVC with Tiles 3\"\u003e\n        \u003cput-attribute name=\"header\" value=\"/WEB-INF/tiles/views/header.jsp\"\u003e\n        \u003cput-attribute name=\"body\" value=\"\"\u003e\n        \u003cput-attribute name=\"footer\" value=\"/WEB-INF/tiles/views/footer.jsp\"\u003e\n    \u003c/put-attribute\u003e\u003c/put-attribute\u003e\u003c/put-attribute\u003e\u003c/put-attribute\u003e\u003c/definition\u003e\n\n    \u003c!-- Pages --\u003e\n    \u003cdefinition name=\"site.home\" extends=\"layout.basic\"\u003e\n        \u003cput-attribute name=\"body\" value=\"/WEB-INF/tiles/views/home/home.jsp\"\u003e\n    \u003c/put-attribute\u003e\u003c/definition\u003e\n\n    \u003cdefinition name=\"site.greeting\" extends=\"layout.basic\"\u003e\n        \u003cput-attribute name=\"body\" value=\"/WEB-INF/tiles/views/home/greeting.jsp\"\u003e\n    \u003c/put-attribute\u003e\u003c/definition\u003e\n\u003c/tiles-definitions\u003e\n```\n\nCreate the tiles themselves\n\n**basic.jsp:**\n\n```xml\n\u003c@ taglib uri=\"http://tiles.apache.org/tags-tiles\" prefix=\"tiles\"\u003e\n        \u003ctitle\u003e\u003ctiles:getAsString name=\"title\"/\u003e\u003c/title\u003e\n        \u003ctiles:insertattribute name=\"header\"\u003e\u003c/tiles:insertattribute\u003e\n        \u003ctiles:insertattribute name=\"body\"\u003e\u003c/tiles:insertattribute\u003e\n        \u003ctiles:insertattribute name=\"footer\"\u003e\n\u003c/tiles:insertattribute\u003e\n```\n\n**header.jsp:**\n\n```xml\n\u003cdiv class=\"header\"\u003ePage Header\u003c/div\u003e\n```\n\nfooter.jsp:\n\n```xml\n\u003cdiv class=\"footer\"\u003ePage Footer\u003c/div\u003e\n```\n\n**home.jsp:**\n\n```xml\n\u003cdiv class=\"main-contnet\"\u003e\n     Main page content goes here...\n\u003c/div\u003e\n```\n\n**greeting.jsp:**\n\n```html\n\u003cdiv\u003e\n  Hello ${name}
1\n\u003c/div\u003e\n```\n\n## 5. Spring Boot Controller\n\nAdd a controller class into a controller directory:\n\n```java\npackage com.example.app.controller;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.servlet.ModelAndView;\n\n@Controller\npublic class HelloWorldController {\n\n    @RequestMapping(value = \"/home\", method=RequestMethod.GET)\n    public String home() {\n        return \"site.home\";\n    }\n\n    @RequestMapping(value = \"/greet/{name}\", method=RequestMethod.GET)\n    public ModelAndView greetTwoWays(@PathVariable(value=\"name\") final String name, final Model model) {\n        return new ModelAndView(\"site.greeting\", \"name\", name);\n    }\n}\n```\n\nBuild the project using Maven:\n\n```bash\nmvn clean package\n```\n\nWhen using Gradle:\n\n```bash\ngradle build\n```\n\nNow let us test the controller and confirm that Spring MVC has been configured as expected\n\n```text\nhttp://localhost:8080/home\nhttp://localhost:8080/greet/John\n```\n"])</script>
1<script>self.__next_f.push([1,"96:Ta64,"])</script>
1<script>self.__next_f.push([1,"\nH2 is an Open Source embedded Java SQL database. It is a fast, in-memory database with a very small footprint of a single jar file (around 1.5-megabyte) size. Therefore you can easily embed the H2 database into your application for rapid development.\n\nH2 Database also provides a built-in web console to interact with the database. You can use H2 database as an in-memory database, embedded database or network database.\n\nPlease note, H2 database is not a full-fledged SQL implementation, it supports only a subset of the SQL standard.\n\nYou can find more details about the H2 Database from the [official website](http://www.h2database.com/html/main.html).\n\n## Why do you care?\n\nWhy do I need an in-memory database? Can I not just connect to MySQL or other real databases?\n\nWell yes, you definitely can. But development java application connecting to a real database involves a lot of overhead. Also, during development, your schema is bound to change as the software evolves.\n\nAlso when working on distributed teams, you don’t want your code to fail when someone else in team updates the DB schema. Multiple developers should be able to run the DB tests in parallel.\n\nFor such cases, an in-memory database is an ideal solution. An in-memory database is created when an application starts up and destroyed when the application is stopped.\n\n## **Installing H2 database**\n\nIf you’re using Maven build tools for your Spring boot application, then you need to add the following package dependency in your `pom.xml` file.\n\n```xml\n\u003cdependency\u003e\n        \u003cgroupid\u003ecom.h2database\u003c/groupid\u003e\n        \u003cartifactid\u003eh2\u003c/artifactid\u003e\n        \u003cversion\u003e1.4.197\u003c/version\u003e\n        \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nAnd, if you are on Gradle, you can include the following package dependency in your build.gradle file.\n\n```groovy\ndependencies {\n    // Your dependencies\n    runtime('org.springframework.boot:spring-boot-devtools')\n    runtime('com.h2database:h2')\n    //...\n}\n```\n\n## Accessing H2 Web Console\n\nAs we discussed earlier, H2 database provides a Web console to interact with the database. To enable the console, you need to add the following property to your `application.properties` file.\n\n**/src/main/resources/application.properties**\n\n```properties\n# Enabling H2 Console\nspring.h2.console.enabled=true\n```\n\nOnce you have done the above configurations, you need to restart your Spring boot application. You can launch the H2 database Web console at:\n\n```text\nhttp://localhost:8080/h2-console.\n```\n\nMake sure that you use `jdbc:h2:mem:testdb` as JDBC URL.\n\n[![](/media/articles/17/Using-H2-In-Memory-Database-in-Spring-Boot-620x383.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"97:Ta4f,"])</script>
1<script>self.__next_f.push([1,"\nBefore Java 8, Java interfaces could only have static constants and abstract methods. The implementation of those abstract methods has to be provided by the class that implements an interface. This means that when you modify an interface, it breaks all the implementation classes.\n\nTherefore, to overcome this issue, Java 8 has introduced the concept of default methods (Also known as Extension Methods) which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.\n\nYou can do this by using the `default` keyword.\n\n## Default Method Java8 Example\n\n```java\ninterface Vehicle {\n    String speedUp();\n    String slowDown();\n\n    default String alarmOn() {\n        return \"Turning the alarm on.\";\n    }\n\n    default String alarmOff() {\n        return \"Turning the alarm off.\";\n    }\n}\n\nclass Car implements Vehicle {\n\n    private String brand;\n\n    public Car(String brand){\n        this.brand = brand;\n    }\n\n    @Override\n    public String speedUp(){\n        return \"Speed up!\";\n    }\n\n    @Override\n    public String slowDown(){\n        return \"Slow down!\";\n    }\n\n    public String getBrand(){\n        return brand;\n    }\n}\n```\n\nAs you can notice above, we do not have to provide the implementation for the `alarmOn` and `alarmOff` methods in our `Car` implementation.\n\nLastly, let’s define a typical main class and creates an instance of Car to see how the default methods are called:\n\n```java\npublic class VehicleExmaple {\n\n    public static void main(String[] args) {\n    Car car = new Car(\"Land Rover\");\n    System.out.println(car.getBrand());\n        System.out.println(car.speedUp());\n        System.out.println(car.slowDown());\n\n        //Calling default methods\n        System.out.println(car.alarmOn());\n        System.out.println(car.alarmOff());\n\n    }\n}\n```\n\n## **Default Methods Inheritance \u0026 Diamond Problem**\n\nIf your class implements multiple interfaces that define the same default methods, then the code simply won’t compile, as there’s ambiguity caused by multiple interface inheritance (a.k.a the [Diamond Problem](https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem))\n\nThis can be solved by explicitly overriding the default methods in your implementation class.\n\n```java\nclass Car implements Vehicle1, Vehicle2 {\n\n    // Your code goes here..\n    @Override\n    public String alarmOn() {\n        // Your code goes here..\n        //...\n        return Vehicle2.super.alarmOn();\n    }\n\n    @Override\n    public String alarmOff() {\n        // Your code goes here..\n        //...\n        return Vehicle2.super.alarmOff();\n\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"98:T7cb,"])</script>
1<script>self.__next_f.push([1,"\nWhenever you want to commit a bug or a new feature, you need to create a branch for it, which will be a copy of your master branch. Once your fixes are ready to merge, you typically create a pull request on your new branch. The reason for this is to keep your master branch clean all the time.\n\n## 1. Create a New Git Branch\n\nHere is a list of some useful commands to help you create and manage a new branch. Please note, that before creating a new branch, pull the changes from upstream. Your master needs to be up to date.\n\nCreate the branch on your local machine and switch to this branch:\n\n```bash\n$ git checkout -b \u003cnew branch name\u003e\n```\n\nChange working branch:\n\n```bash\n$ git checkout \u003cnew branch name\u003e\n```\n\nPush the branch to remote git:\n\n```bash\n$ git push origin \u003cnew branch name\u003e\n```\n\nWhen you want to commit something in your branch, be sure to be in your branch. Add -u parameter to set-upstream.\n\n## 2. View Git Branches\n\nYou can see all the local branches by using:\n\n```bash\n$ git branch\n```\n\nView list of all branches, including remote branches:\n\n```bash\n$ git branch -a\n```\n\nView list of only remote branches:\n\n```bash\n$ git branch -r\n```\n\n## 3. Push Branch to Remote\n\nAdd a new remote for your branch:\n\n```bash\n$ git remote add \u003cremote branch name\u003e\n```\n\nPush changes from your commit into your branch:\n\n```bash\n$ git push \u003cnew branch remote name\u003e  \u003cnew branch name\u003e\n```\n\nUpdate your branch when the original branch from the official repository has been updated:\n\n```bash\n$ git fetch \u003cremote branch name\u003e\n```\n\nThen you need to apply to merge changes if your branch is derivated from the develop you need to do:\n\n```bash\n$ git merge \u003cname of remote branch\u003e/develop\n```\n\n## 4. Delete Git Branch\n\nDelete local branch: -d option stands for –delete\n\n```bash\n$ git branch -d \u003cbranch_name\u003e\n```\n\nGit local branch force: -D option stands for –delete –force\n\n```bash\n$ git branch -D \u003cbranch_name\u003e\n```\n\nDelete a remote Git branch\n\n```bash\n$ git push origin --delete \u003cbranch_name\u003e\n```\n"])</script>
1<script>self.__next_f.push([1,"99:Tac1,"])</script>
1<script>self.__next_f.push([1,"\nThe term method chaining refers to both a design and a convention. Each method returns an object, allowing the calls to be chained together in a single statement. Chaining is syntactic sugar which eliminates the need for intermediate variables.\n\nA method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together even though line breaks are often added between methods.\n\nIt applies to classes and methods where:\n\n-   Multiple methods are potentially going to be called on the same object;\n-   The methods in question need no return value.\n\nThe idea of method chaining is that if the methods need no “useful” return value, then the method can return this\n\n### Method Chaining:\n\n```java\nclass User {\n\n    private String name;\n    private int age;\n\n    // In addition to having the side-effect of setting the attributes in question,\n    // the setters return \"this\" (the current Person object) to allow for further chained method calls.\n    public User setName(String name) {\n        this.name = name;\n        return this;\n    }\n\n    public User setAge(int age) {\n        this.age = age;\n        return this;\n    }\n\n    public void getUserDetails() {\n        System.out.println(\"User name is \" + name + \" and \" + age + \" years old.\");\n    }\n\n    public static void main(String[] args) {\n         User user= new User();\n         user.setName(\"skptricks\").setAge(22).getUserDetails();\n    }\n}\n```\n\n**Output :** Username is skptricks and 22 years old.\n\n### Without Method Chaining:\n\n```java\nclass User {\n\n    private String name;\n    private int age;\n\n    // In addition to having the side-effect of setting the attributes in question,\n    // the setters return \"this\" (the current Person object) to allow for further chained method calls.\n    public User setName(String name) {\n        this.name = name;\n        return this;\n    }\n\n    public User setAge(int age) {\n        this.age = age;\n        return this;\n    }\n\n    public void getUserDetails() {\n        System.out.println(\"User name is \" + name + \" and \" + age + \" years old.\");\n    }\n\n    public static void main(String[] args) {\n         User user= new User();\n         user.setName(\"skptricks\").setAge(22).getUserDetails();\n    }\n}\n```\n\n**Output :** Username is skptricks and 22 years old.\n\nHope you like this simple example of method chaining. Thank you for reading this article, and if you have any problem, have another better useful solution for this article, please write in the comment section.\n\n_This story was first published at SKPTRICKS. See the original article [Method chaining in Java](\u003c\\\u003ca href=\u003e). Opinions expressed by Stacktips contributors are their own._\n"])</script>
1<script>self.__next_f.push([1,"9a:T18eb,"])</script>
1<script>self.__next_f.push([1,"\nApplications often consist of similar but different object models, where the data in two models may be similar but the structure and concerns of the models are different.\n\nFor example, if you are creating a Spring Boot API endpoint for adding `Product` data into your DB, it is a best practice to hide your internal DB structure and create a DTO object for the API to pass the JSON payload.\n\n```java\n@PostMapping\npublic Movie createMovie(@RequestBody MovieDto movieDto){\n\n    // Convert movieDto to the movie model\n    Movie movie = new Movie();\n    movie.setTitle(movieDto.getTitle())\n    //So on..\n\n    return repository.save(movie);\n}\n```\n\nIn the above code snippet, the Movie class is a DB model. The data in the DTO object is pretty much a subset of the `Movie` model. Here, in this case, we will have to map every single property of the `MovieDto` object to the `Movie` object before saving it to the Database.\n\nMapping every single property is cumbersome and time taking.\n\nThis is the reason why we need the object mapping framework to convert one model to another seamlessly. There are several Java mapping frameworks available that can help convert one object type to another in Java. Here are some of the popular mapping frameworks.\n\n## Mapping with **Dozer**\n\nDozer is a Java Bean-to-Bean mapper that recursively copies data from one object to another. Typically, these Java Beans can be of the same or different complex types.\n\nDozer supports simple property mapping, complex type mapping, bi-directional mapping, implicit-explicit mapping, as well as re
1cursive mapping. This includes mapping collection attributes that also need mapping at the element level.\n\nIf you’re using Maven build tools, for using the Dozer framework you need to add the following package dependency\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupid\u003ecom.github.dozermapper\u003c/groupid\u003e\n    \u003cartifactid\u003edozer-core\u003c/artifactid\u003e\n    \u003cversion\u003e6.4.1\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nIf you’re using the Gradle build system, you can include the following package dependency in your `build.gradle` file.\n\n```groovy\ncompile group: 'com.github.dozermapper', name: 'dozer-core', version: '6.4.1'\n```\n\nCheck out the Dozer framework documentation [here](http://dozer.sourceforge.net/) for more details.\n\n## Mapping with **MapStruct**\n\nMapStruct is a code generator that greatly simplifies the implementation of mappings between Java bean types based on the annotation approach. It is a Java annotation processor for generating type-safe bean mapping classes.\n\nAll you have to do is to define a mapper interface which declares any required mapping methods. During compilation, MapStruct will generate an implementation of this interface.\n\nThis implementation uses plain Java method invocations for mapping between source and target objects, i.e. no reflection or similar.\n\nThis is probably the simplest and quickest option for writing mapping code. It saves time by generating code which is generally tedious and error-prone to write your own.\n\n**Installing MapStruct**\n\nIf you’re using Maven build tools, for using the MapStruct framework you need to add the following package dependency\n\n```xml\n\u003cproperties\u003e\n    \u003corg.mapstruct.version\u003e1.3.0.Beta1\u003c/org.mapstruct.version\u003e\n\u003c/properties\u003e\n...\n\n\u003cdependency\u003e\n    \u003cgroupid\u003eorg.mapstruct\u003c/groupid\u003e\n    \u003cartifactid\u003emapstruct-processor\u003c/artifactid\u003e\n    \u003cversion\u003e${org.mapstruct.version}\u003c/version\u003e\n    \u003cscope\u003eprovided\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nOptionally, you can add MapStruct your classpath to annotation processor paths as follows.\n\n```xml\n\u003cbuild\u003e\n    \u003cplugins\u003e\n        \u003cplugin\u003e\n            \u003cgroupid\u003eorg.apache.maven.plugins\u003c/groupid\u003e\n            \u003cartifactid\u003emaven-compiler-plugin\u003c/artifactid\u003e\n            \u003cversion\u003e3.5.1\u003c/version\u003e\n            \u003cconfiguration\u003e\n                \u003csource\u003e1.8\n                \u003ctarget\u003e1.8\u003c/target\u003e\n                \u003cannotationprocessorpaths\u003e\n                    \u003cpath\u003e\n                        \u003cgroupid\u003eorg.mapstruct\u003c/groupid\u003e\n                        \u003cartifactid\u003emapstruct-processor\u003c/artifactid\u003e\n                        \u003cversion\u003e${org.mapstruct.version}\u003c/version\u003e\n                    \u003c/path\u003e\n                \u003c/annotationprocessorpaths\u003e\n            \u003c/configuration\u003e\n        \u003c/plugin\u003e\n    \u003c/plugins\u003e\n\u003c/build\u003e\n```\n\nfor gradle,\n\n```groovy\n...\nplugins {\n    ...\n    id 'net.ltgt.apt' version '0.15'\n}\n\ndependencies {\n    compile 'org.mapstruct:mapstruct-jdk8:1.2.0.Final'\n    apt 'org.mapstruct:mapstruct-processor:1.2.0.Final'\n}\n...\n```\n\nCheck out the MapStruct framework documentation [here](http://mapstruct.org/documentation/dev/reference/html/).\n\n## **ModelMapper**\n\nThe ModelMapper is a framework aimed at simplifying the Java object mapping, by automatically determining how one object model maps to another, based on conventions.\n\nIt analyses your Java object model to intelligently determine how data should be mapped without doing any manual mapping.\n\nThe ModelMapper API is type-safe and refactoring-safe, using the actual code, rather than string references, to map properties and values.\n\n**Installing ModelMapper**\n\nIf you’re using Maven build tools, for using the ModelMapper framework, you need to add the following package dependency\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupid\u003eorg.modelmapper\u003c/groupid\u003e\n    \u003cartifactid\u003emodelmapper\u003c/artifactid\u003e\n    \u003cversion\u003e2.2.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nfor gradle,\n\n```groovy\ndependencies {\n    compile('org.modelmapper:modelmapper:2.2.0')\n}\n```\n\nCheck out the MapStruct framework documentation [here](http://modelmapper.org/).\n\n## **JMapper**\n\nJMapper is a Java bean-to-bean mapper framework based n the Javassist framework. It allows you the ability to do dynamic mappings, multi-relational mappings, inherited mapping and other features without compromising on performance.\n\nThe framework allows you to map beans using annotation, XML or API-based configurations.\n\n### **Installing JMapper**\n\nIf you’re using Maven build tools, for using the ModelMapper framework, you need to add the following package dependency\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupid\u003ecom.googlecode.jmapper-framework\u003c/groupid\u003e\n    \u003cartifactid\u003ejmapper-core\u003c/artifactid\u003e\n    \u003cversion\u003e1.6.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nfor gradle,\n\n```groovy\ndependencies {\n    compile('com.googlecode.jmapper-framework:jmapper-core:1.6.0')\n}\n```\n\nCheck out the JMapper framework documentation [here](https://github.com/jmapper-framework/jmapper-core).\n"])</script>
1<script>self.__next_f.push([1,"9b:T17ca,"])</script>
1<script>self.__next_f.push([1,"\nApplication program interfaces (API) are sets of routines, protocols, and tools for describing how software applications and components should interact with each other. They are the key driver in today’s economy for integrating with an eco-system much larger than most companies can build on their own.\n\nToday, many ubiquitous digital platforms and services (think Twitter, Facebook, Salesforce, Airbnb, PayPal) are made available through APIs.\n\nImagine we are building an application to help users with their travel plans. We will require weather information to serve our users with some special offers based on specific weather conditions at a specific location. However, as we do not own any weather data, we can request the information from third-party vendors such as OpenWeatherMap or AccuWeather using their public APIs.\n\nCompanies release and promote their services as part of a larger software development kit (SDK) that includes the APIs and instructions to help developers understand the specifications of how to use them. The API layer abstracts all the underlying platform complexities (i.e. simplifies it) and the value in the data is made available via an easy-to-use readable format.\n\nThere are different data formats used for API communication and information exchange. The most notable and industry-standard data formats are Plain Text, JSON, XML, CSV, and YAML.\n\n## Why do we need an API Gateway?\n\nAPI manager (also referred as API gateway) platforms are used to easily publish, manage and monitor APIs securely in a highly scalable environment. Gateways additionally include features such as the ability to apply security policies and usage policies, collecting and analyzing statistics and other value-adds.\n\nSome of the common features offered by today’s popular API manager platforms are:\n\n-   Allow companies to publish and monitor the API in a secure and scalable environment.\n-   Allow publishers to design, prototype and document APIs in one place. Most of the popular gateways work well with some of the industry standard Open API specifications such as Swagger and RAML.\n-   Offers a clean and pluggable environment to make it easy to switch between production and sandbox environments.\n-   Define common security gateway and authentication protocols for all published APIs.\n-   Monitor and manage traffic for individual users or applications.\n-   Traffic quota management, allows you to define the limits of a free quota and where a premium option kicks in based on the volume of incoming traffic.\n-   Memory management and data caching mechanisms to improve API performance and response times.\n-   API versioning to ensure compatibility between multiple API implementations without any code changes.\n-   Some of the API manager platforms even allow developers to define API mock data using JavaScript or a static response. This helps the API consumer, to develop and test the application without having to wait for the real working APIs.\n-   Define Load balancer reverse proxy and distribution network for splitting application traffic across several servers.\n-   Set up and manage server failover.\n\nIn response to the growing open API movement, some software giants such as Facebook, Twitter, and Google have taken the initiative to build API management software in-house to serve customer data for third-party App developers.\n\nHowever, implementing such a complex API Gateway platform with a wide variety of transports, security features, authentication, monitoring and usage reporting, in-house is very expensive for small and medium enterprises. Hence, some of the big players including Amazon, IBM, and Microsoft have built a business model around it to serve enterprises with their API gateway needs.\n\nOverall, there are numerous tools available in this space and each claim to be more useful than the other. Some of the most popular choices are WSO2, AWS, Azure, IBM API Management, Akamai, MuleSoft and CA’s API Gateway.\n\nDuring our initial experiments in this area, WSO2 arose as one of the best choices and satisfied most/all the criteria of our business case need. Here are some of our experiences with the WSO2 API manager.\n\n-   It is completely free, open source and released under an Apache 2.0 license. The enterprise license is very affordable.\n-   Short learning curve to get started.\n-   WSO2 supports OAuth 2.0 security standards with support for quota management and traffic throttling. As we have our own OAuth 2.0 implementation, the integration with the existing system was a straightforward step with standard Java handlers.\n-   It doesn’t include a load balancer out of the box, but it works well with our existing Nginx plus load balancer setup\n-   It didn’t support importing RAML specification directly (when we started our investigation) but we’ve been able to convert all our RAML to Swagger and everything else has been smooth since then.\n-   As we use micro-services-based distributed architecture, almost all our services communicate using both synchronous (HTTP-based broker-less architecture) and asynchronous (with AMQP message broker) mechanisms. WSO2 works nicely with both.\n-   Native support for Google Analytics was a plus.\n-   Amazing service with extended development support.\n\n## Summary\n\nFor most micro-services-based architectures, it makes great sense to consider using an API Gateway that can act as a single entry point and can provide additional features like authentication, monitoring and, load balancing.\n\nIt’s been a year since we switched to WSO2 and migrated over 12+ API’s and I must say, we have not been disappointed. Clearly, WSO2 was the right choice for us, but what works for you?\n\nIf you have a personal favorite or have had a negative experience with the gateways I mentioned or with any I neglected to list, please let me know in the comments below!\n\n_This story was first published at NESS blog. See the original article [here.](https://www.ness.com/api-gateways-key-benefits-to-consider?utm_source=stacktips.com) Opinions expressed by Stacktips contributors are their own._\n"])</script>
1<script>self.__next_f.push([1,"9c:T1f69,"])</script>
1<script>self.__next_f.push([1,"\nFeeds are one of the traditional and most effective ways to distribute your content to a wider audience. There are thousands of apps, such as Feedly, Apple News, and Google Newsstand, that allow people to follow and read your content whenever new content is published.\n\nFeeds allow webmasters to drive traffic to their websites. Some feed delivery platforms, such as Google FeedBurner, allow you to monetize your feed content by serving ads.\n\n## Generate an RSS Feed in Laravel\n\nAccording to web standards, there are different feed formats that are widely accepted. RSS and Atom are the most popular ones. Feeds are XML-based; however, they differ in specifications.\n\nTo make our lives easier, we will generate valid RSS and Atom feeds using the [roumen/feed](https://github.com/RoumenDamianoff/laravel-feed) open-source Laravel library. In this article, we assume you have a basic knowledge of Laravel and have a project handy to integrate with.\n\n### Adding roumen/feed via Composer\n\nLaravel project dependencies are maintained using [Composer](/articles/intro-to-laravel-php-framework-and-features). We can add the roumen/feed dependency library using the following Artisan command:\n\n```bash\ncomposer require roumen/feed\n```\n\nOr add the following to your `composer.json` file:\n\n```json\n\"roumen/feed\": \"~2.10\"\n```\n\nPlease note, after updating the `composer.json` file, run the `composer install` command to add the dependency to your project.\n\nNow, register the `Roumen\\Feed\\FeedServiceProvider` service provider and class alias in your Laravel `config/app.php` file.\n\n```php\n\u003c?php\nreturn [\n     //...\n    'providers' =\u003e [\n        //...\n        Roumen\\Feed\\FeedServiceProvider::class,\n    ],\n\n    'aliases' =\u003e [\n    //...\n        'Feed'      =\u003e Roumen\\Feed\\Feed::class,\n    ],\n];\n```\n\nOptionally, if you want to alter the Blade layouts, you can publish vendor views using the following Artisan command:\n\n```bash\nartisan vendor:publish --provider=\"Roumen\\Feed\\FeedServiceProvider\"\n```\n\n### Eloquent Models\n\nThis tutorial's scope is limited to generating an RSS feed, and hence we won't cover Eloquent models and database concepts.\n\nThe following code snippets of the Post and User models are illustrated just to give an idea of how the data in the database is stored.\n\n```php\n\u003c?php\nnamespace App\\Models;\nuse App\\User;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Post extends Model\n{\n    protected $table = 'posts';\n    public $timestamps = TRUE;\n    protected $fillable = [\n        'id',\n        'user_id',\n        \"title\",\n        'content',\n        \"excerpt\",\n    ];\n\n    public function user()\n    {\n        return $this-\u003ebelongsTo(User::class);\n    }\n}\n```\n\nLet us now see what the User model looks like.\n\n```php\n\u003c?php\nnamespace App;\nuse App\\Models\\Post;\n\nclass User extends Authenticatable\n{\n    protected $table = 'users';\n    use Notifiable;\n    protected $fillable = [\n        'id',\n        'fname',\n        'lname',\n        'email',\n    ];\n\n    protected $hidden = [\n        'password',\n        'remember_token',\n    ];\n\n    public function post()\n    {\n        return $this-\u003ehasMany(Post::class);\n    }\n}\n```\n\nNotice that in the above relationship, we have an inverse one-to-many relationship between Post and User. A user can have multiple posts, and a post can be associated with one user.\n\n### Routes for Feed\n\nHere is what our routes for posts look like:\n\n```php\n#Post archive\nRoute::get('posts/', ['as' =\u003e 'post.archive', 'uses' =\u003e 'PostController@archive']);\n#Single\nRoute::get('post/{id}/{slug?}', ['as' =\u003e 'post.single', 'uses' =\u003e 'PostController@single']);\n```\n\n### Feed Configuration\n\nWe would like to have some of the feed configurations inside a config file. Create a new file named `feed.php` inside the `config/` directory and add the following snippet:\n\n```php\n\u003c?php\nreturn [\n    'feed_title' =\u003e \"Stacktips\",\n    'feed_description' =\u003e 'Your description',\n    'feed_logo' =\u003e 'http://example.com/images/brand/logo.png',\n    'use_cache' =\u003e FALSE,\n    'cache_key' =\u003e 'laravel-feed-cache-key',\n    'cache_duration' =\u003e 3600,\n    'max_size' =\u003e 30,\n];\n```\n\nIn this example, we have configured the feed to serve 30 items. There is no strict rule on how many items you should serve, but it is recommended to keep your feed sleek. I believe between 20 and 30 is a good number.\n\n### Laravel Routes for Feed\n\nLet us now define routes for RSS feeds. Here, we will define two routes: one for accessing the Atom feed and the other for RSS.\n\n```php\n# Feeds\nRoute::get('feed/{type?}', ['as' =\u003e 'feed.atom', 'uses' =\u003e 'Feed\\FeedsController@getFeed']);\n```\n\nI personally believe in simplicity, so let us define a `getFeed()` method in the controller and abstract most of the business logic into a service class.\n\n### Feed Controller\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers\\Web\\Feed;\n\nuse App\\Http\\Controllers\\Controller;\nuse App\\Services\\Feed\\FeedBuilder;\n\nclass FeedsController extends Controller\n{\n    private $builder;\n\n    public function __construct(FeedBuilder $builder)\n    {\n        $this-\u003ebuilder = $builder;\n    }\n\n    //We're making atom default type\n    public function getFeed($type = \"atom\")\n    {\n        if ($type === \"rss\" || $type === \"atom\") {\n            return $this-\u003ebuilder-\u003erender($type);\n        }\n\n        //If invalid feed requested, redirect home\n        return redirect()-\u003ehome();\n    }\n}\n```\n\nNote that:\n\n-   The feed route defines an optional parameter `type`. This is used to define what type of feed the user wants to access.\n-   Currently, we will support only RSS and Atom, and make Atom the default choice.\n-   If the user passes an invali
1d value for the feed type, instead of showing an error page, we will redirect to the home page.\n\n### FeedBuilder Service\n\nThe next part is where the real fun is. Here, we make use of the roumen/feed library APIs to serve the latest content in the feed.\n\n```php\n\u003c?php\nnamespace App\\Services\\Feed;\n\nuse Illuminate\\Support\\Facades\\App;\nuse App\\Models\\Post;\n\nclass FeedBuilder\n{\n    private $config;\n\n    public function __construct()\n    {\n        $this-\u003econfig = config()-\u003eget('feed');\n    }\n\n    public function render($type)\n    {\n        $feed = App::make(\"feed\");\n        if ($this-\u003econfig['use_cache']) {\n            $feed-\u003esetCache($this-\u003econfig['cache_duration'], $this-\u003econfig['cache_key']);\n        }\n\n        if (!$feed-\u003eisCached()) {\n            $posts = $this-\u003egetFeedData();\n            $feed-\u003etitle = $this-\u003econfig['feed_title'];\n            $feed-\u003edescription = $this-\u003econfig['feed_description'];\n            $feed-\u003elogo = $this-\u003econfig['feed_logo'];\n            $feed-\u003elink = url('feed');\n            $feed-\u003esetDateFormat('datetime');\n            $feed-\u003elang = 'en';\n            $feed-\u003esetShortening(true);\n            $feed-\u003esetTextLimit(250);\n\n            if (!empty($posts)) {\n                $feed-\u003epubdate = $posts[0]-\u003ecreated_at;\n                foreach ($posts as $post) {\n                    $link = route('post.single', [\"id\" =\u003e $post-\u003eid, \"slug\" =\u003e $post-\u003eslug]);\n\n                    $author = \"\";\n                    if(!empty($post-\u003euser)){\n                        $author = $post-\u003euser-\u003ename;\n                    }\n                    // set item's title, author, url, pubdate, description, content, enclosure (optional)*\n                    $feed-\u003eadd($post-\u003etitle, $author, $link, $post-\u003ecreated_at, $post-\u003epitch, $post-\u003eabout);\n                }\n            }\n        }\n\n        return $feed-\u003erender($type);\n    }\n\n    /**\n     * Creating an RSS feed with our most recent posts.\n     * The size of the feed is defined in feed.php config.\n     *\n     * @return mixed\n     */\n    private function getFeedData()\n    {\n        $maxSize = $this-\u003econfig['max_size'];\n        $posts = Post::paginate($maxSize)-\u003ewith['user'];\n        return $posts;\n    }\n}\n```\n\nNotice that if you have multiple feeds for different content, you must have different cache keys.\n\nNow visit any of the following URLs and test if your feeds are working:\n\nhttp://localhost:8080/feed  \nhttp://localhost:8080/feed/atom  \nhttp://localhost:8080/feed/rss\n"])</script>
1<script>self.__next_f.push([1,"9d:T1b75,"])</script>
1<script>self.__next_f.push([1,"\nMany of the cool Android features are remained untouched by app developers. For example, Android SDK has the capabilities to seamlessly integrate the user speech recognition services to turn speech to into text. Apps like Google Keep, Any.DO uses speech to text conversion feature quite creatively. In today’s world, big players like Google, Microsoft, and Apple are betting big on voice assistance software like Google voice command, Cortana, and Siri. This shows how serious and powerful the feature is.\n\nAndroid natively provides converting [Text to Speech](/articles/android-texttospeech-example) and Speech to Text feature, so why not to use it in our app! In this tutorial, we will show you how to integrate Android’s Speech to Text API in your Android app. This simple application will record the user’s voice, convert it into text and display on Android Screen.\n\nAs soon as a user say something, Android will recognize his/her voice and convert it into text. It will do it through [`RecognizerIntent`](https://developer.android.com/reference/android/speech/RecognizerIntent.html). You do not require any internet connection to use the voice to text service. It will work in Offline mode.\n\nWithout much of a fuss, let us now proceed with the example.\n\n### Pre-requisites:\n\n-   [Android Studio](/articles/android-studio-features) IDE on your PC or Mac.\n-   This App doesn’t support Emulator. So you need an Android Smartphone or Tablet.\n-   Basic knowledge of Android app lifecycle, knowledge of building UI layouts.\n\n### Create New Android Project\n\n1.  Open Android Studio and create a new project **Speech to Text** and company domain application.example.com (We have used our own company domain i.e stacktips.com).\n2.  Click Next and choose Min SDK, we have kept the default value. Again Click Next and Choose **Blank Activity**.\n3.  Choose the Activity as **MainActivity** and click next.\n4.  Leave all other things as default and Click Finish.\n\nA new project will be created and gradle will resolve all the dependencies.\n\n### Activity Layout\n\nLet us add an [ImageButton](/articles/android-button-example) representing a mic, and a [TextView](/articles/android-textview-example) to display the converted text in it. The TextView is wrapped inside a [ScrollView](/articles/android-scrollview-example) for allowing longer scrollable content.\n\n**activity\\_main.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:id=\"@+id/activity_main\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    tools:context=\"com.stacktips.speechtotext.MainActivity\"\u003e\n\n    \u003cScrollView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"match_parent\"\n        android:layout_above=\"@+id/btnSpeakContainer\"\n        android:layout_alignParentTop=\"true\"\n        android:layout_marginBottom=\"20dp\"\n        android:padding=\"20dp\"\u003e\n\n        \u003cTextView\n            android:id=\"@+id/voiceInput\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"match_parent\" /\u003e\n    \u003c/ScrollView\u003e\n\n    \u003cLinearLayout\n        android:id=\"@+id/btnSpeakContainer\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentBottom=\"true\"\n        android:background=\"#f5f5f5\"\n        android:gravity=\"center_horizontal\"\n        android:orientation=\"vertical\"\n        android:padding=\"20dp\"\u003e\n\n        \u003cImageButton\n            android:id=\"@+id/btnSpeak\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:background=\"@null\"\n            android:padding=\"16dp\"\n            android:scaleType=\"fitCenter\"\n            android:src=\"@mipmap/ic_microphone_2\" /\u003e\n\n        \u003cTextView\n            android:id=\"@+id/textView\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_below=\"@id/btnSpeak\"\n            android:layout_margin=\"10dp\"\n            android:text=\"@string/hint\" /\u003e\n    \u003c/LinearLayout\u003e\n\u003c/RelativeLayout\u003e\n```\n\n### Inside Android Activity\n\nThis is the main part of voice recognition app where we will user `RecognizerIntent` to convert speech into text. Add following code in MainActivity.java:\n\n**MainActivity.java**\n\n```java\npackage com.stacktips.speechtotext;\n\nimport android.content.ActivityNotFoundException;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.speech.RecognizerIntent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ImageButton;\nimport android.widget.TextView;\nimport java.util.ArrayList;\nimport java.util.Locale;\n\npublic class MainActivity extends AppCompatActivity {\n\n    private static final int REQ_CODE_SPEECH_INPUT = 100;\n    private TextView mVoiceInputTv;\n    private ImageButton mSpeakBtn;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);\n        mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);\n        mSpeakBtn.setOnClickListener(new View.OnClickListener() {\n\n            @Override\n            public void onClick(View v) {\n                startVoiceInput();\n            }\n        });\n    }\n\n    private void startVoiceInput() {\n        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);\n        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);\n        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());\n        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, \"Hello, How can I help you?\");\n        try {\n            startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);\n        } catch (ActivityNotFoundException a) {\n\n        }\n    }\n\n    @Override\n    protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n        super.onActivityResult(requestCode, resultCode, data);\n\n        switch (requestCode) {\n            case REQ_CODE_SPEECH_INPUT: {\n                if (resultCode == RESULT_OK \u0026\u0026 null != data) {\n                    ArrayList\u003cString\u003e result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);\n                    mVoiceInputTv.setText(result.get(0));\n                }\n                break;\n            }\n\n        }\n    }\n}\n```\n\nIn the above code, we are triggering an Intent named `RecognizerIntent` which asks for speech input and then sends it through speech recognizer. It does it through `ACTION_RECOGNIZE_SPEECH`. If request code is `REQ_CODE_SPEECH_INPUT` then corresponding text is written in output screen.\n\nLet us now build and run this example.\n\nAfter you tap the Mic button, second screen will appear that will ask you to speak something. Now if you speak anything, it will be shown on screen.\n"])</script>
1<script>self.__next_f.push([1,"9e:T5cd,"])</script>
1<script>self.__next_f.push([1,"\nChrome Custom Tabs gives apps more control over their web experience and make transitions between native and web content more seamless without having to resort to a WebView.\n\nChrome Custom Tabs allow an app to customize how Chrome looks and feels. An app can change things like:\n\n-   Toolbar color\n-   Enter and exit animations\n-   Add custom actions to the Chrome toolbar, overflow menu and bottom toolbar\n\nChrome Custom Tabs also allow the developer to pre-start Chrome and pre-fetch content for faster loading.\n\nTo use custom chrome tab in Android, you first need to include the following dependency in your build grade file.\n\n```java\ncompile 'com.android.support:customtabs:23.4.0+'\n```\n\nSync the project after adding the dependencies. Now you’re good to go.\n\n```java\n public static void launchChromeTab(Activity activity, String url) {\n        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();\n        builder.setToolbarColor(ContextCompat.getColor(activity, R.color.colorPrimary));\n        builder.setSecondaryToolbarColor(ContextCompat.getColor(activity, R.color.colorPrimaryDark));\n\n        // set start and exit animations\n        builder.setStartAnimations(activity, R.anim.slide_in_right, R.anim.slide_out_left);\n        builder.setExitAnimations(activity, android.R.anim.slide_in_left, android.R.anim.slide_out_right);\n\n        CustomTabsIntent customTabsIntent = builder.build();\n        customTabsIntent.launchUrl(activity, Uri.parse(url));\n    }\n```\n"])</script>
1<script>self.__next_f.push([1,"9f:T172f,"])</script>
1<script>self.__next_f.push([1,"\n## 1. String Length and Trim\n\nCode snippet explains the usage of String class length and trim() method.\n\n-   The `length()` method returns the length of this string.\n-   The `trim()` method returns a copy of the string, with leading and trailing whitespace omitted.\n\n```java\nimport java.util.Scanner;\n\npublic class StringExampleTwo {\n    public static void main(String args[]) {\n\n        Scanner scanner= new Scanner(System.in);\n        System.out.println(\"Enter a string with space\");\n\n        String s1 = scanner.nextLine();\n        System.out.println(\"s1 = \" + s1);\n\n        // Display String Length\n        System.out.println(\"The length of s1 is: \" + s1.length());\n\n        // Removing extra spaces from s1\n        String s2 = s1.trim();\n\n        System.out.println(\"s2 = \" + s2);\n        System.out.println(\"The length of s2 is: \" + s2.length());\n    }\n\n}\n```\n\n**Output**\n\n[![String length and trim string in java](/media/articles/71/String-length-and-trim-string-in-java-620x359.png)](http://stacktips.com)\n\n## 2. String Equality Check\n\nSample program to test String Equality in Java using equals to () operator and String.equals() method.\n\n```java\npublic class StringEqualsTest {\n    public static void main(String[] args) {\n        String str1 = \"hello\";\n        String str2 = str1;\n        String str3 = new String(\"hellp\");\n        String str4 = new String(\"hello 2\");\n        String str5 = \"hello\";\n\n        System.out.println(\"Comparison using == : \" + (str1 == str5));\n        System.out.println(\"Comparison using == : \" + (str1 == str2));\n        System.out.println(\"Comparison Using equals() method : \" + str1.equals(str2));\n        System.out.println(\"Comparison using == : \" + (str3 == str4));\n        System.out.println(\"Comparison Using equals() method : \" + str3.equals(str4));\n    }\n}\n```\n\n**Output**  \n[![How to Test String Equality in Java](/media/articles/71/How-to-Test-String-Equality-in-Java.png)](http://stacktips.com)\n\n## 3. String Concatenation\n\nSample Java program to concatenate two strings using plus (+) concatenation operator.\n\n```java\npublic class StringConcatination {\n    public static void main(String args[]) {\n        String str1 = \"Hello\";\n        String str2 = \"JavaTechig\";\n\n        // Concatenation\n        String str3 = str1.concat(str2);\n\n        System.out.println(\"str1 = \" + str1);\n        System.out.println(\"str2 = \" + str2);\n        System.out.println(\"str3 = \" + str3);\n\n        String str4 = \"Hello\";\n\n        // checking equals\n        if (str4.equals(str1)) {\n            System.out.println(\"str4 is equal to str1\");\n        } else {\n            System.out.println(\"str4 is not equal to str1\");\n        }\n\n    }\n}\n```\n\n**Output**\n\n[![String Concatenation Test in Java](/media/articles/71/String-Concatenation-Test-in-Java.png)](http://stacktips.com)\n\n## 4. Change Uppercase to Lowercase\n\nQuick Java code snippet to change the case of a String in Java. It uses `toUpperCase()` and `toLowerCase()` methods present in java.lang.String class to convert the case.\n\n```java\npublic class StringCase {\n    public static void main(String args[]) {\n        String str = \"This code snippet is brought you by Java Techhig\";\n\n        // toUpperCase() method converts the complete string in upper case\n        String strUpper = str.toUpperCase();\n\n        // toLowerCase() method converts the complete string in lower case\n        String strLower = str.toLowerCase();\n\n        // printing changed case string\n        System.out.println(\"Upper Case: \" + strUpper);\n        System.out.println(\"Lower Case: \" + strLower);\n    }\n}\n```\n\n**Output**  \n[![Change Case of a String in Java](/media/articles/71/Change-Case-of-a-String-in-Java.png)](http://stacktips.com)\n\n## 5. Reverse String\n\n```java\nimport java.util.Scanner;\n\nclass ReverseString\n{\n   public static void main(String args[])\n   {\n      String original, reverse = \"\";\n      Scanner scanner = new Scanner(System.in);\n\n      System.out.println(\"Enter a string to reverse\");\n      original = scanner.nextLine();\n      int length = original.length();\n\n      for ( int i = length - 1 ; i \u003e= 0 ; i-- ){\n         reverse = reverse + original.charAt(i);\n      }\n\n      System.out.println(\"Reverse of entered string is: \"+reverse);\n   }\n}\n```\n\n**Output**  \n[![Reverse String in java](/media/articles/71/Reverse-String-in-java.png)](http://stacktips.com)\n\n## 6. Reverse String using Recursion\n\n```java\nimport java.util.Scanner;\n\npublic class StringRecursiveReverse {\n    public String reverseString(String str) {\n        String reverse = \"\";\n        if (str.length() == 1) {\n            return str;\n        } else {\n            reverse += str.charAt(str.length() - 1) + reverseString(str.substring(0, str.length() - 1));\n            return reverse;\n        }\n    }\n\n    public static void main(String args[]) {\n        StringRecursiveReverse srr = new StringRecursiveReverse();\n        Scanner scanner = new Scanner(System.in);\n        System.out.println(\"Enter a string to reverse\");\n        String original = scanner.nextLine();\n\n        System.out.println(\"Result: \" + srr.reverseString(original));\n    }\n}\n```\n\n**Output**  \n[![Reverse Java String using recursive method](/media/articles/71/Reverse-Java-String-using-recursive-method.png)](http://stacktips.com)\n\n## 7. Compare Strings\n\n```java\nimport java.util.Scanner;\n\nclass CompareStrings {\n     public static void main(String args[]) {\n      String str1, str2;\n      Scanner in = new Scanner(System.in);\n      System.out.println(\"Enter the first string\");\n      str1 = in .nextLine();\n\n      System.out.println(\"Enter the second string\");\n      str2 = in .nextLine();\n\n      if (str1.compareTo(str2) \u003e 0){\n            System.out.println(\"First string is greater than second.\");\n      } else if (str1.compareTo(str2) \u003c 0){\n            System.out.println(\"First string is smaller than second.\");\n      } else{\n            System.out.println(\"Both strings are equal.\");\n      }\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"a0:Td22,"])</script>
1<script>self.__next_f.push([1,"\nLast year, I have published the **[CustomCalendarView](/articles/custom-calendar-view-library-in-android)** Open Source Android library. This library makes it easy to add a Calendar to your Android application.\n\nSince then many people are asking questions like how to use Decorators and how to disable some dates in CustomCalendarView. This post answers that.\n\nIn this example, we will disable all the dates that are past.\n\n```java\npublic class CalendarDayDecoratorActivity extends AppCompatActivity {\n    private CustomCalendarView calendarView;\n    private TextView selectedDateTv;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_calendar_decorator);\n        selectedDateTv = (TextView) findViewById(R.id.selected_date);\n\n        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\n        setSupportActionBar(toolbar);\n        getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n        getSupportActionBar().setDisplayShowHomeEnabled(true);\n\n        //Initialize CustomCalendarView from layout\n        calendarView = (CustomCalendarView) findViewById(R.id.calendar_view);\n\n        //Initialize calendar with date\n        Calendar currentCalendar = Calendar.getInstance(Locale.getDefault());\n\n        //Show monday as first date of week\n        calendarView.setFirstDayOfWeek(Calendar.MONDAY);\n\n        //Show/hide overflow days of a month\n        calendarView.setShowOverflowDate(false);\n\n        //call refreshCalendar to update calendar the view\n        calendarView.refreshCalendar(currentCalendar);\n\n        //Handling custom calendar events\n        calendarView.setCalendarListener(new CalendarListener() {\n            @Override\n            public void onDateSelected(Date date) {\n                if (!CalendarUtils.isPastDay(date)) {\n                    SimpleDateFormat df = new SimpleDateFormat(\"dd-MM-yyyy\");\n                    selectedDateTv.setText(\"Selected date is \" + df.format(date));\n                } else {\n                    selectedDateTv.setText(\"Selected date is disabled!\");\n                }\n            }\n\n            @Override\n            public void onMonthChanged(Date date) {\n                SimpleDateFormat df = new SimpleDateFormat(\"MM-yyyy\");\n                Toast.makeText(CalendarDayDecoratorActivity.this, df.format(date), Toast.LENGTH_SHORT).show();\n            }\n        });\n\n        //adding calendar day decorators\n        List\u003cDayDecorator\u003e decorators = new ArrayList\u003c\u003e();\n        decorators.add(new DisabledColorDecorator());\n        calendarView.setDecorators(decorators);\n        calendarView.refreshCalendar(currentCalendar);\n    }\n\n    @Override\n    public boolean onOptionsItemSelected(MenuItem item) {\n        // handle arrow click here\n        if (item.getItemId() == android.R.id.home) {\n            finish(); // close this activity and return to preview activity (if there is any)\n        }\n        return super.onOptionsItemSelected(item);\n    }\n\n    private class DisabledColorDecorator implements DayDecorator {\n        @Override\n        public void decorate(DayView dayView) {\n            if (CalendarUtils.isPastDay(dayView.getDate())) {\n                int color = Color.parseColor(\"#a9afb9\");\n                dayView.setBackgroundColor(color);\n            }\n        }\n    }\n\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"a1:Te34,"])</script>
1<script>self.__next_f.push([1,"\nFirebase Crash Reporting is yet another Firebase feature announced at Google I/O 2016. It enables you to collect the detailed report of errors in your app.\n\nOnes your app is published, it is difficult the understand the reason why the app is crashed. And hence it becomes very difficult to fix them. Crash reporting frameworks log the crashes and grouped into clusters of similar stack traces, and triaged by the severity of impact on your users.\n\nFirebase crash reporting automatically logs the crashes and you may also log custom events to help capture the steps leading up to a crash.\n\nIn this tutorial, we will see how to configure and use Firebase Crash Reporting platform in your Android application.\n\n## Configure the Firebase SDK.\n\nLet us begin with creating a Firebase project in the [Firebase console](https://console.firebase.google.com). You will be asked to log in with your Google Mail account. Once you logged in, select **Add App** button to create a new project in Firebase Console.\n\n1.  Select the **Android platform** to continue with Android Firebase configuration.\n\n[![Create new project in Firebase console- Select Platform](/media/articles/77/Create-new-project-in-Firebase-console-Select-Platform.png)](http://stacktips.com)\n\n2.  If you have not created any app before, you will be asked to select the **Project Name** and **Country Region**. Provide the details and Continue with the configuration.\n3.  Enter your Android app package name. This should be same as defined in your android `AndroidMaifest.xml` file.\n\n[![Firebase Android Configuration](/media/articles/77/Firebase-Android-Configuration-e1470927322754-620x466.png)](http://stacktips.com)\n\n4.  You may provide the debug `keystore` SHA-1 certificate. However this is optional and hence you may leave it empty.\n5.  Select **Add App** button. This will download the `google-services.json` configuration file for your app. Copy this file into your project’s module folder, typically inside app/ directory.\n\n[![Project Structure](/media/articles/77/Project-Structure.png)](http://stacktips.com)\n\nScreenshot depicts project structure after adding google-services.json file\n\n7.  Now, add the required Firebase SDK dependencies to your project. Modify the project level build.gradle (\u003cproject\u003e/build.gradle) file and add the google-services.\n\n```java\nbuildscript {\n  dependencies {\n    // Add this line\n    classpath 'com.google.gms:google-services:3.0.0'\n  }\n}\n```\n\nAnd, add the following to app module level `build.gradle` file.\n\n```java\napply plugin: 'com.android.application'\nandroid {\n   ....\n}\ndependencies {\n    compile fileTree(dir: 'libs', include: ['*.jar'])\n    ...\n    //Add this\n    compile 'com.google.firebase:firebase-crash:9.4.0'\n}\n\n// Add to the bottom of the file\napply plugin: 'com.google.gms.google-services'\n```\n\nAfter the dependencies are added **Sync** your project with gradle file changes. With this we’re done with the project configuration.\n\n## Reporting Custom Crash\n\nFirebase Crash Reporting automatically generates reports for fatal errors. However, if you want to report your own exception, you can do it using `FirebaseCrash.report(exception)` method. For example:\n\n```java\nException exception = new Exception(\"Oops! Firebase non-fatal error!\");\nFirebaseCrash.report(exception);\n```\n\nOptionally, you can report custom logs by calling `log()` method.\n\n```java\nFirebaseCrash.log(\"Button clicked!\");\n```\n\nPlease note, it usually takes up to 20 minutes to get your error logs on Firebase console.\n\n[![Firebase Crash Reporting Android](/media/articles/77/Firebase-Crash-Reporting-Android-940x423.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"a2:T4a7,\nA Switch is a two-state toggle switch widget that can select between two options. Add Switch control to your Activity or Fragment layout as follows.\n\n```xml\n\u003cSwitch\n        android:id=\"@+id/wifi_switch\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentBottom=\"true\"\n        android:layout_marginBottom=\"10dp\"\n        android:background=\"@android:color/background_dark\"\n        android:checked=\"false\"\n        android:text=\"Wi-Fi Settings\"\n        android:textColor=\"@android:color/white\"\n        android:textOff=\"OFF\"\n        android:textOn=\"ON\" /\u003e\n```\n\nNow you can register switch event using setOnCheckedChangeListener(this) method.\n\n```java\nSwitch toggle = (Switch) findViewById(R.id.wifi_switch);\ntoggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n        if (isChecked) {\n            Toast.makeText(getApplicationContext(), \"Switch on!\", Toast.LENGTH_LONG).show();\n        } else {\n            Toast.makeText(getApplicationContext(), \"Switch off!\", Toast.LENGTH_LONG).show();\n        }\n    }\n});\n```\na3:Tcd3,"])</script>
1<script>self.__next_f.push([1,"\nQuick settings are undoubtedly one of the most popular features in Android devices. It provides a convenient way to quickly change the device settings or key actions directly from the notification panel.\n\nLike always, Google never disappoints developers. This time, Android N introduced the new Quick Settings Tile API and allow developers to add their own quick setting actions. Now Quick Settings Tile adds more room for additional custom actions and you can swipe left/right to access more settings.\n\nPlease note, Quick Settings tiles are reserved for controls or actions that are either urgently required or frequently used, and should not be used as shortcuts to launching an app.\n\nAndroid Quick Settings Tiles can only have icons of a single color. It can be tinted to either white or grey. You can handle click, double-click action on the tiles but the long press is restricted only to few system apps.\n\n### Android Quick Settings API Example\n\nIn this tutorial, we will see how to use the Quick Settings Tile API in Android N to register a custom tile action. The sample application will add a custom action to quick settings and when clicked it will launch an activity.\n\nYou need the following perquisites to run this code sample.\n\n-   Android Studio version 2.0+\n-   A test device or emulator configuration with Android version 6.0+\n\nAdding a tile to quick settings involves two steps. First you need to declareQuick Settings Tile in `AndroidManifest.xml` file. Add the following code snippets inside `\u003capplication\u003e` element.\n\n```xml\n\u003cservice\n    android:name=\"com.stacktips.example.MyAppTileService\"\n    android:icon=\"@drawable/tile_icon\"\n    android:label=\"@string/tile_label\"\n    android:permission=\"android.permission.BIND_QUICK_SETTINGS_TILE\"\u003e\n    \u003cintent-filter\u003e\n        \u003caction android:name=\"android.service.quicksettings.action.QS_TILE\" /\u003e\n    \u003c/intent-filter\u003e\n\u003c/service\u003e\n```\n\nLet us now extend the `TileService` class to respond the Tile events and handle click action to launch an activity when user clicking on the Quick Settings Tile. You can optionally override the following methods to perform different actions when the Tile state changes.\n\n| onTileAdded() | Called when user adds the tile to the quick settings from the edit interface |\n| --- | --- |\n| onTileRemoved() | Called when the tile is removed from the quick settings using the edit interface. |\n| onStartListening() | Called when the tile is brought into the listening state. |\n| onStopListening() | Called when the tile is brought out of the listening state. |\n| onClick() | Called when the tile is clicked. |\
1n\n**MyAppTileService.java**\n\n```java\npublic class MyAppTileService extends TileService {\n    @Override\n    public void onDestroy() {\n        super.onDestroy();\n    }\n\n    @Override\n    public void onTileAdded() {\n        super.onTileAdded();\n    }\n\n    @Override\n    public void onTileRemoved() {\n        super.onTileRemoved();\n    }\n\n    @Override\n    public void onStartListening() {\n        super.onStartListening();\n    }\n\n    @Override\n    public void onStopListening() {\n        super.onStopListening();\n    }\n\n    @Override\n    public void onClick() {\n        super.onClick();\n        //Start main activity\n        startActivity(new Intent(this, MainActivity.class));\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"a4:T2440,"])</script>
1<script>self.__next_f.push([1,"\nThe YouTube Android Player allows you to customize the playback control by setting one of the style defined in YouTubePlayer.PlayerStyle enumeration. It currently support three styles `DEFAULT`, `MINIMAL` or `CHROMELESS`;\n\n-   _YouTubePlayer.PlayerStyle.DEFAULT_ – The default style, showing all interactive player controls.\n-   _YouTubePlayer.PlayerStyle.MINIMAL_ – The minimal style displays only a time bar and play/pause controls.\n-   _YouTubePlayer.PlayerStyle.CHROMELESS_ – A style that shows no interactive player controls. When you use CHROMELESS, you need to write your own controls for play, pause or seek operation.\n\nYou can apply style to YouTubePlayer by calling `setPlayerStyle(PlayerStyle style)` method.\n\n```java\nplayer.setPlayerStyle(PlayerStyle.CHROMELESS);\n```\n\nIn our previous example, we saw How to use [YouTube Android Player API and YouTubePlayerView](/articles/youtube-android-player-api-example). In this example, we will customize the YouTubePlayer with custom player controls.\n\n![Customize YouTubePlayer Controls in Android](/media/articles/97/Customize-YouTubePlayer-Controls-in-Android.png)\n\n### Add YouTubePlayerView to View Hierarchy\n\nLet us first add the YouTubePlayerView view in your activity or fragment view hierarchy.\n\nactivity\\_custom\\_player.xml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    tools:context=\"com.stacktips.youtube.MainActivity\"\u003e\n\n    \u003ccom.google.android.youtube.player.YouTubePlayerView\n        android:id=\"@+id/youtube_player_view\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:background=\"#ebeff2\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\nLet us now add the player controls right below `YouTubePlayerView` in `activity_custom_player.xml` layout.\n\n```xml\n\u003cLinearLayout\n    android:id=\"@+id/video_control\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:background=\"#444\"\n    android:gravity=\"center_vertical\"\n    android:orientation=\"horizontal\"\n    android:visibility=\"gone\"\n    android:weightSum=\"10\"\u003e\n\n    \u003cImageButton\n        android:id=\"@+id/play_video\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"5dp\"\n        android:layout_weight=\"1\"\n        android:background=\"@null\"\n        android:src=\"@drawable/ic_play\" /\u003e\n\n    \u003cImageButton\n        android:id=\"@+id/pause_video\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"5dp\"\n        android:layout_weight=\"1\"\n        android:background=\"@null\"\n        android:src=\"@drawable/ic_pause\" /\u003e\n\n    \u003cSeekBar\n        android:id=\"@+id/video_seekbar\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"10dp\"\n        android:layout_weight=\"6\"\n        android:max=\"100\"\n        android:progress=\"0\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/play_time\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"5dp\"\n        android:layout_weight=\"2\"\n        android:text=\"--:--\"\n        android:textColor=\"@android:color/white\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\n### 2. Add INTERNET Permission in AndroidManifest\n\nINTERNET permission is required to play video over internet. Add the following permission in your application `AndroidManifest.xml` file.\n\n```xml\n\u003cuses-permission android:name=\"android.permission.INTERNET\" /\u003e\n```\n\n### Initialize YouTubePlayerView\n\nWhen using YouTubePlayerView, your activity needs to extend `[YouTubeBaseActivity](https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubeBaseActivity.html)`. Now let us create an Activity that extends YouTubeBaseActivity and initialize the YouTubePlayerView. We will add our own Play, Pause and Seek playback control.\n\n```java\npublic class CustomPlayerControlActivity extends YouTubeBaseActivity\n        implements OnInitializedListener, View.OnClickListener {\n    private static final Str
1ing TAG = \"CustomPlayerControlActivity\";\n\n    public static final String API_KEY = \"AIzaSyBx7v0YOb140fDO732fMx4l87raxezDWFw\";\n\n    //https://www.youtube.com/watch?v=\u003cVIDEO_ID\u003e\n    public static final String VIDEO_ID = \"-m3V8w_7vhk\";\n\n    private YouTubePlayer mPlayer;\n\n    private View mPlayButtonLayout;\n    private TextView mPlayTimeTextView;\n\n    private Handler mHandler = null;\n    private SeekBar mSeekBar;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        // attaching layout xml\n        setContentView(R.layout.activity_custom_player);\n\n        // Initializing YouTube player view\n        YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player_view);\n        youTubePlayerView.initialize(API_KEY, this);\n\n        //Add play button to explicitly play video in YouTubePlayerView\n        mPlayButtonLayout = findViewById(R.id.video_control);\n        findViewById(R.id.play_video).setOnClickListener(this);\n        findViewById(R.id.pause_video).setOnClickListener(this);\n\n        mPlayTimeTextView = (TextView) findViewById(R.id.play_time);\n        mSeekBar = (SeekBar) findViewById(R.id.video_seekbar);\n        mSeekBar.setOnSeekBarChangeListener(mVideoSeekBarChangeListener);\n\n        mHandler = new Handler();\n    }\n\n    @Override\n    public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {\n        Toast.makeText(this, \"Failed to initialize.\", Toast.LENGTH_LONG).show();\n    }\n\n    @Override\n    public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {\n        if (null == player) return;\n        mPlayer = player;\n\n        displayCurrentTime();\n\n        // Start buffering\n        if (!wasRestored) {\n            player.cueVideo(VIDEO_ID);\n        }\n\n        player.setPlayerStyle(PlayerStyle.CHROMELESS);\n        mPlayButtonLayout.setVisibility(View.VISIBLE);\n\n        // Add listeners to YouTubePlayer instance\n        player.setPlayerStateChangeListener(mPlayerStateChangeListener);\n        player.setPlaybackEventListener(mPlaybackEventListener);\n    }\n\n    PlaybackEventListener mPlaybackEventListener = new PlaybackEventListener() {\n        @Override\n        public void onBuffering(boolean arg0) {\n        }\n\n        @Override\n        public void onPaused() {\n            mHandler.removeCallbacks(runnable);\n        }\n\n        @Override\n        public void onPlaying() {\n            mHandler.postDelayed(runnable, 100);\n            displayCurrentTime();\n        }\n\n        @Override\n        public void onSeekTo(int arg0) {\n            mHandler.postDelayed(runnable, 100);\n        }\n\n        @Override\n        public void onStopped() {\n            mHandler.removeCallbacks(runnable);\n        }\n    };\n\n    PlayerStateChangeListener mPlayerStateChangeListener = new PlayerStateChangeListener() {\n        @Override\n        public void onAdStarted() {\n        }\n\n        @Override\n        public void onError(ErrorReason arg0) {\n        }\n\n        @Override\n        public void onLoaded(String arg0) {\n        }\n\n        @Override\n        public void onLoading() {\n        }\n\n        @Override\n        public void onVideoEnded() {\n        }\n\n        @Override\n        public void onVideoStarted() {\n            displayCurrentTime();\n        }\n    };\n\n    SeekBar.OnSeekBarChangeListener mVideoSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {\n        @Override\n        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {\n            long lengthPlayed = (mPlayer.getDurationMillis() * progress) / 100;\n            mPlayer.seekToMillis((int) lengthPlayed);\n        }\n\n        @Override\n        public void onStartTrackingTouch(SeekBar seekBar) {\n\n        }\n\n        @Override\n        public void onStopTrackingTouch(SeekBar seekBar) {\n\n        }\n    };\n\n    @Override\n    public void onClick(View v) {\n        switch (v.getId()) {\n            case R.id.play_video:\n                if (null != mPlayer \u0026\u0026 !mPlayer.isPlaying())\n                    mPlayer.play();\n                break;\n            case R.id.pause_video:\n                if (null != mPlayer \u0026\u0026 mPlayer.isPlaying())\n                    mPlayer.pause();\n                break;\n        }\n    }\n\n    private void displayCurrentTime() {\n        if (null == mPlayer) return;\n        String formattedTime = formatTime(mPlayer.getDurationMillis() - mPlayer.getCurrentTimeMillis());\n        mPlayTimeTextView.setText(formattedTime);\n    }\n\n    private String formatTime(int millis) {\n        int seconds = millis / 1000;\n        int minutes = seconds / 60;\n        int hours = minutes / 60;\n\n        return (hours == 0 ? \"--:\" : hours + \":\") + String.format(\"%02d:%02d\", minutes % 60, seconds % 60);\n    }\n\n    private Runnable runnable = new Runnable() {\n        @Override\n        public void run() {\n            displayCurrentTime();\n            mHandler.postDelayed(this, 100);\n        }\n    };\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"a5:T4df,\nThe following code snippet shows how to get a unique file name when saving the file in java. It first checks if already a file exists with the specified name, then it appends a number to the end.\n\n```java\npublic static File getUniqueFilePath(String parent, String child, String fileName) {\n    File dir = new File(parent, child);\n    String uniqueName = getUniqueFileName(parent, child, fileName);\n    return new File(dir, uniqueName);\n}\n\npublic static String getUniqueFileName(String parent, String child, String fileName) {\n     final File dir = new File(parent, child);\n     if (!dir.exists()) {\n         dir.mkdirs();\n     }\n\n     int num = 0;\n     final String ext = getFileExtension(fileName);\n     final String name = getFileName(fileName);\n     File file = new File(dir, fileName);\n     while (file.exists()) {\n         num++;\n         file = new File(dir, name + \"-\" + num + ext);\n     }\n     return file.getName();\n}\n\npublic static String getFileExtension(final String path) {\n     if (path != null \u0026\u0026 path.lastIndexOf('.') != -1) {\n         return path.substring(path.lastIndexOf('.'));\n     }\n     return null;\n}\n\npublic static String getFileName(String fileName) {\n     return fileName.substring(0, fileName.lastIndexOf('.'));\n}\n```\na6:T5b3,"])</script>
1<script>self.__next_f.push([1,"\nThe following code snippet will help you to disables the SSL certificate checking for new instances of HttpsURLConnection in Android.\n\nNote: You can use this code for testing purpose only and remove when moving to production. Trusting all certificate in production will expose your box for hackers.\n\n```java\npublic void trustAllCertificates() {\n    try {\n        TrustManager[] trustAllCerts = new TrustManager[]{\n                new X509TrustManager() {\n                    public X509Certificate[] getAcceptedIssuers() {\n                        X509Certificate[] myTrustedAnchors = new X509Certificate[0];\n                        return myTrustedAnchors;\n                    }\n\n                    @Override\n                    public void checkClientTrusted(X509Certificate[] certs, String authType) {\n                    }\n\n                    @Override\n                    public void checkServerTrusted(X509Certificate[] certs, String authType) {\n                    }\n                }\n        };\n\n        SSLContext sc = SSLContext.getInstance(\"SSL\");\n        sc.init(null, trustAllCerts, new SecureRandom());\n        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());\n        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {\n            @Override\n            public boolean verify(String arg0, SSLSession arg1) {\n                return true;\n            }\n        });\n    } catch (Exception e) {\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"a7:T2c63,"])</script>
1<script>self.__next_f.push([1,"\nThe YouTube Player API for Android provides a ready to use a fragment and an embedded view to play YouTube videos. The API provides methods to customize and control the video playback. You can play, pause, or seek video to specific play time. The API also provides the helper functions to support orientation changes as well as transitions to full-screen playback.\n\nThis tutorial demonstrates how to use `YouTubePlayerView` and `YouTubePlayerFragement` in Android to play YouTube videos.\n\n![YouTubePlayerView Example](/media/articles/113/YouTubePlayerView-Example-620x316.png)\n\nNote: Users need to run version 4.2.16 of the mobile YouTube app (or higher) to use the YouTube Android Player API.\n\nIntegrating YouTube Player API in your Android application involves tharee key steps:\n\n1.  Download and Configure YouTube Android Player API in Android Studio\n2.  Register your Application in Google Developer Console and obtain Android API key\n3.  Integrating YouTube Android Player API in your Android Application\n\n## Download YouTube Android Player API\n\nThe YouTube Android Player API is currently not supported via Gradle dependency. You need to download it from the official download source and add it to your project manually.\n\nDownload YouTube Player API from [developer.google.com](https://developers.google.com/youtube/android/player/downloads/).\n\nOnce your download is completed, extract the bundle. You will notice several directories including docs, libs, and sample. Now copy `YouTubeAndroidPlayerApi.jar` file and paste it into your Android Studio project libs directory.\n\nThe following image depicts the project structure after YouTubeAndroidPlayerApi.jar is added to the project.\n\n![YouTube Android Player API Example](/media/articles/113/YouTube-Android-Player-API-Example.png)\n\nNow that the library is added, just make sure you have the following declaration in your app `build.gradle` file.\n\n```groovy\ndependencies {\n    compile fileTree(dir: 'libs', include: ['*.jar'])\n    //... other dependencies\n}\n```\n\nNow select **Tools \u003e Android \u003e “Sync Project** **with Gradle Files**” option on Android Studio menu to sync project after adding jar file.\n\n## Register in Google Dev Console\n\nFor using Youtube Player API in your Android application, you need to register your application in Google Developers Console and obtain an Android API key.\n\nPlease note, the API key is a unique value for your application. Do not disclose this to others.  \nThe following steps explain how to register your application in the Google Developer Console and get your application’s authorization credentials.\n\n-   Visit Google Developers Console. If you’re not logged already, you will be asked to login with your Google Mail account.\n-   Select a project, or create a new one.\n-   In the sidebar on the left, expand APIs \u0026 auth. Next, click APIs. In the list of APIs, make sure the status is Enabled for the YouTube Data API v3.\n-   In the sidebar on the left, select Credentials \u003e Add Credential.\n\n![Add Credential Google Developer Console](/media/articles/113/Add-Credential-Google-Developer-Console.png)\n\n-   Select “Android” and “Public data option and follow the screen instruction to create your API Credentials.\n\n![Add Credential Google Developer Console](/media/articles/113/Add-Credential-Google-Developer-Console2.png)\n\nNow copy your API credentials. You need it from your Android code.\n\n## YouTubePlayerView Android Example\n\nNow that we are ready with the basic configurations, we can start using the YouTube Player API in our application. The API offers two methods to integrate and play embedded YouTube video in Android; YouTubePlayerView or YouTubePlayerFragment. Let us first see how to integrate YouTubePlayerView.\n\nYouTubePlayerView takes care of Android Configuration Change events. It saves and restore the state of the YouTubePlayer associated with the view as part of the onSaveInstanceState/onRestoreInstanceState.\n\n### Add YouTubePlayerView to View Hierarchy\n\nLet us first add the YouTubePlayerView view in your activity or fragment view hierarchy.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n   xmlns:tools=\"http://schemas.android.com/tools\"\n   android:layout_width=\"match_parent\"\n   android:layout_height=\"match_parent\"\n   android:orientation=\"vertical\"\n   tools:context=\"com.stacktips.youtube.MainActivity\"\u003e\n\n   \u003ccom.google.android.youtube.player.YouTubePlayerView\n       android:id=\"@+id/youtube_player_view\"\n       android:layout_width=\"match_parent\"\n       android:layout_height=\"wrap_content\"/\u003e\n\u003c/LinearLayout\u003e\n```\n\n### Add INTERNET Permission\n\nINTERNET permission is required to play video over internet. Add the following permission in your application `AndroidManifest.xml` file.\n\n```xml\n\u003cuses-permission android:name=\"android.permission.INTERNET\" /\u003e\n```\n\n### Initialize YouTubePlayerView\n\nWhen using YouTubePlayerView, your activity needs to extend `[YouTubeBaseActivity](https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubeBaseActivity.html)`. Now let us create an Activity that extends YouTubeBaseActivity and initialize the YouTubePlayerView.\n\nOnce the initialization is successful, you will get the `onInitializationSuccess()` callback with YouTubePlayerView instance. You can add additional listeners to handle the playback control events.\n\n```java\npublic class MainActivity extends YouTubeBaseActivity implements OnInitializedListener {\n    public static final Str
1ing API_KEY = \"YOUR_API_KEY\";\n\n    //https://www.youtube.com/watch?v=\u003cVIDEO_ID\u003e\n    public static final String VIDEO_ID = \"-m3V8w_7vhk\";\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        // attaching layout xml\n        setContentView(R.layout.activity_main);\n\n        // Initializing YouTube player view\n        YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player_view);\n        youTubePlayerView.initialize(API_KEY, this);\n    }\n\n    @Override\n    public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {\n        Toast.makeText(this, \"Failed to initialize.\", Toast.LENGTH_LONG).show();\n    }\n\n    @Override\n    public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {\nif(null== player) return;\n\n        // Start buffering\n        if (!wasRestored) {\n            player.cueVideo(VIDEO_ID);\n        }\n    }\n}\n```\n\nIn the above code snippet, we are calling `initialize(String, OnInitializedListener)` method on YouTubePlayerView to instantiate YouTubePlayer. Ones YouTubePlayer instance is ready, it can be used to to load videos into this YouTubePlayerView. You may now build and run the app now to see the YouTube player in action.\n\n### 4.4. Handling YouTubePlayer Events\n\nYou may attach `PlaybackEventListener` or `PlayerStateChangeListener` listeners to player instance for error handling or advanced configurations.\n\n```java\n// Add listeners to YouTubePlayer instance\nplayer.setPlayerStateChangeListener(new PlayerStateChangeListener() {\n    @Override\n    public void onAdStarted() { }\n\n    @Override\n    public void onError(ErrorReason arg0) { }\n\n    @Override\n    public void onLoaded(String arg0) { }\n\n    @Override\n    public void onLoading() { }\n\n    @Override\n    public void onVideoEnded() { }\n\n    @Override\n    public void onVideoStarted() { }\n});\n\nplayer.setPlaybackEventListener(new PlaybackEventListener() {\n    @Override\n    public void onBuffering(boolean arg0) { }\n\n    @Override\n    public void onPaused() { }\n\n    @Override\n    public void onPlaying() { }\n\n    @Override\n    public void onSeekTo(int arg0) { }\n\n    @Override\n    public void onStopped() { }\n});\n```\n\n## 5. Customising YouTubePlayer Controls\n\nThe YouTube Android Player allows you to customize the playback control by setting one of the style defined in `YouTubePlayer.PlayerStyle` enumeration. It currently support three styles `DEFAULT`, `MINIMAL` or `CHROMELESS`;\n\n-   _YouTubePlayer.PlayerStyle.DEFAULT_ – The default style, showing all interactive player controls.\n-   _YouTubePlayer.PlayerStyle.MINIMAL_ – The minimal style displays only a time bar and play/pause controls.\n-   _YouTubePlayer.PlayerStyle.CHROMELESS_ – A style that shows no interactive player controls. When you use CHROMELESS, you need to write your own controls for play, pause or seek operation.\n\nYou can apply style to YouTubePlayer by calling `setPlayerStyle(PlayerStyle style)` method.\n\n```java\nplayer.setPlayerStyle(PlayerStyle.CHROMELESS);\n```\n\nCheckout our Part-II tutorial to learn more about [how to customise YouTubePlayer](/articles/how-to-customize-youtubeplayer-controls-in-android) by adding your own custom playback controls.\n\n## 6. YouTubePlayerFragment Example\n\nIntegrating YouTubePlayerFragment is relatively easy. The following section demonstrates how to use YouTubePlayerFragment.\n\nLet us declare the Activity layout where the YouTubePlayerFragment will be added.  \n**activity\\_youtube\\_player\\_fragment.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cFrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:id=\"@+id/content\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\u003e\n\u003c/FrameLayout\u003e\n```\n\nNow let us create an activity and extend it form `YouTubeBaseActivity`. We will now create an instance of YouTubePlayerFragment and add the fragment to activity.\n\n**YouTubePlayerFragmentActivity.java**\n\n```java\npublic class YouTubePlayerFragmentActivity extends YouTubeBaseActivity {\n    public static final Str
1ing API_KEY = \"AIzaSyBx7v0YOb1404fDO7EbfMx4l87raxezDWFw\";\n\n    //https://www.youtube.com/watch?v=\u003cVIDEO_ID\u003e\n    public static final String VIDEO_ID = \"-m3V8w_7vhk\";\n\n    @Override\n    protected void onCreate(@Nullable Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_youtube_player_fragment);\n\n        //Initializing and adding YouTubePlayerFragment\n        FragmentManager fm = getFragmentManager();\n        String tag = YouTubePlayerFragment.class.getSimpleName();\n        YouTubePlayerFragment playerFragment = (YouTubePlayerFragment) fm.findFragmentByTag(tag);\n        if (playerFragment == null) {\n            FragmentTransaction ft = fm.beginTransaction();\n            playerFragment = YouTubePlayerFragment.newInstance();\n            ft.add(android.R.id.content, playerFragment, tag);\n            ft.commit();\n        }\n\n        playerFragment.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {\n            @Override\n            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {\n                youTubePlayer.cueVideo(VIDEO_ID);\n            }\n\n            @Override\n            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {\n                Toast.makeText(YouTubePlayerFragmentActivity.this, \"Error while initializing YouTubePlayer.\", Toast.LENGTH_SHORT).show();\n            }\n        });\n    }\n}\n```\n\nNotice that, the player initialization process is remains same. You still have to call `initialize()` method to get your YouTubePlayer instance.\n"])</script>
1<script>self.__next_f.push([1,"a8:T964,"])</script>
1<script>self.__next_f.push([1,"\nEnable deep links for App content in Android, you need to fist add intent filters for the relevant activities in your application manifest. The intent filters allow deep linking to the content in any of your activities.\n\n### Add Intent Filters for Links\n\nFor example, a user clicks on a website link `http://stacktips.com` on the browser, that will resolve the link and open the content in installed activity.\n\n```xml\n\u003cactivity\n    android:name=\"com.example.MainActivity\"\n    android:label=\"@string/my_app\" \u003e\n    \u003cintent-filter android:label=\"@string/my_app\"\u003e\n\n        \u003caction android:name=\"android.intent.action.VIEW\" /\u003e\n        \u003ccategory android:name=\"android.intent.category.DEFAULT\" /\u003e\n        \u003ccategory android:name=\"android.intent.category.BROWSABLE\" /\u003e\n\n        \u003c!-- Accepts URIs that begin with \"http://stacktips.com/articles” --\u003e\n        \u003cdata android:scheme=\"http\" android:host=\"stacktips.com\" android:pathPrefix=\"/articles\" /\u003e\n    \u003c/intent-filter\u003e\n\u003c/activity\u003e\n```\n\nOnce the above intent filters are added, Android will be able to route any Intent that has matching URIs to your app at runtime.\n\n### Read Data from Incoming Intents\n\nOnce Android system starts the routed activity through an intent filter. You can get the data bundle from Intent to determine what you which activity or fragment to render. Call the `getData()` and `getAction()` methods to retrieve the data and action associated with the incoming Intent. You can call these methods at any time during the lifecycle of the activity, but you should generally do so during early callbacks such as `onCreate()` or `onStart()`.\n\nThe following code snippet shows how to retrieve data from an Intent\n\n```java\n@Override\npublic void onCreate(Bundle savedInstanceState) {\n    super.onCreate(savedInstanceState);\n    setContentView(R.layout.main);\n\n    Intent intent = getIntent();\n    String action = intent.getAction();\n    Uri data = intent.getData();\n}\n```\n\n### Test Your Deep Links\n\nYou can use the Android Debug Bridge with the activity manager tool to test that the intent filter URIs you specified for deep linking resolve to the correct app activity. You can run the adb command against a device or an emulator.\n\nThe following command tries to view a target app activity that is associated with the specified URI.\n\n```bash\n$ adb shell am start -W -a android.intent.action.VIEW -d http://stacktips.com/articles com.example\n```\n"])</script>
1<script>self.__next_f.push([1,"a9:T48d,\nThe following code snippet will help you to take a screenshot programmatically in Android. First you need to add the write file permission to save the captured screenshot.\n\n```xml\n\u003cuses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/\u003e\n```\n\nAdd the following Java code to capture the screenshot of running in an Activity.\n\n```java\nprivate void captureScreenshot() {\n    try {\n        // image saving sd card path\n        String mPath = Environment.getExternalStorageDirectory().toString() + \"/\" + System.currentTimeMillis() + \".jpg\";\n\n        // create bitmap screen capture\n        View view = getWindow().getDecorView().getRootView();\n        view.setDrawingCacheEnabled(true);\n\n        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());\n        view.setDrawingCacheEnabled(false);\n\n        File imageFile = new File(mPath);\n        FileOutputStream outputStream = new FileOutputStream(imageFile);\n\n        int quality = 100;\n        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);\n        outputStream.flush();\n        outputStream.close();\n\n    } catch (Throwable e) {\n        e.printStackTrace();\n    }\n}\n```\naa:T54a,\nThe Activity class provides two methods onSaveInstanceState() and onRestoreInstanceState(), for saving and restoring activity state. The onSaveInstanceState( ) method is a callback method that is used to save the application state.\n\n```java\n@Override\npublic void onSaveInstanceState(Bundle savedInstanceState) {\n  super.onSaveInstanceState(savedInstanceState);\n  // Save UI state changes to the savedInstanceState.\n  // This bundle will be passed to onCreate if the process is killed and restarted.\n  savedInstanceState.putBoolean(\"key1\", true);\n  savedInstanceState.putDouble(\"key2\", 1.9);\n  savedInstanceState.putInt(\"key3\", 1);\n  savedInstanceState.putString(\"key4\", \"Welcome back to Android\");\n}\n```\n\nThe Bundle is essentially a way of storing a Key value map. And it will get passed in to onCreate() and also onRestoreInstanceState() where you can extract the values as follows.\n\n```java\n@Override\npublic void onRestoreInstanceState(Bundle savedInstanceState) {\n  super.onRestoreInstanceState(savedInstanceState);\n  // Restore UI state from the savedInstanceState.\n  // This bundle has also been passed to onCreate.\n  boolean myBoolean = savedInstanceState.getBoolean(\"key1\");\n  double myDouble = savedInstanceState.getDouble(\"key2\");\n  int myInt = savedInstanceState.getInt(\"key3\");\n  String myString = savedInstanceState.getString(\"key4\");\n}\n```\nab:Td41,"])</script>
1<script>self.__next_f.push([1,"\nEditText in Android is one of the basic UI widget used for user data input. An `InputFilter` can be attached to an EditText to constrain the changes that can be made to them. For example, you want to allow the maximum of 10 characters to be entered, or you want to allow only uppercase characters.\n\nAndroid SDK comes handy with set of basic filters such as `AllCaps` and `LengthFilter`. However, you can always write your own filter implementation using `InputFilter` interface.\n\nYou can use attach a filter to Editables by calling `setFilters()` method.\n\n```java\n//Set Length filter. Restricting to 10 characters only\neditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_LENGTH)});\n\n//Allowing only upper case characters\neditText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});\n\n//Attaching multiple filters\neditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_LENGTH), new InputFilter.AllCaps()});\n```\n\n### Min and Max Value Range Filter Example\n\nFor defining your own custom filter, you need to implements `InputFilter` interface and override the `filter()` method.\n\n-   The filter() method is called when the buffer is going to replace the range dStart to dEnd of dest with the new text from the range start to end of the source.\n-   Return the CharSequence that you would like to have placed there instead, including an empty string if appropriate, or null to accept the original replacement.\n-   Be careful to not to reject 0-length replacements, as this is what happens when you delete text.\n-   Also beware that you should not attempt to make any changes to dest from this method; you may only examine it for context.\n\nLet us now create a custom filter to define the Min and Max value range. The min max range can be set by setting values to constructor initialization.\n\n```java\nimport android.text.InputFilter;\nimport android.text.Spanned;\n\npublic class CustomRangeInputFilter implements InputFilter {\n    private double minValue;\n    private double maxValue;\n\n    public CustomRangeInputFilter(double minVal, double maxVal) {\n        this.minValue = minVal;\n        this.maxValue = maxVal;\n    }\n\n    @Override\n    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dStart, int dEnd) {\n        try {\n            // Remove the string out of destination that is to be replaced\n            String newVal = dest.toString().substring(0, dStart) + dest.toString().substring(dEnd, dest.toString().length());\n            newVal = newVal.substring(0, dStart) + source.toString() + newVal.substring(dStart, newVal.length());\n            double input = Double.parseDouble(newVal);\n\n            if (isInRange(minValue, maxValue, input)) {\n                return null;\n            }\n        } catch (NumberFormatException e) {\n            e.printStackTrace();\n        }\n        return \"\";\n    }\n\n    private boolean isInRange(double a, double b, double c) {\n        return b \u003e a ? c \u003e= a \u0026\u0026 c \u003c= b : c \u003e= b \u0026\u0026 c \u003c= a;\n    }\n}\n```\n\nYou can use this filter using;\n\n```java\n//Define Min, Max range value using custom input filter\neditText.setFilters(new InputFilter[]{new CustomRangeInputFilter(0f, 10.0f)});\n```\n\nWelcome to EditPad.org – your online plain text editor. Enter or paste your text here. To download and save it, click on the button below.\n\nmore » Edit Pad – Free Online Text EditorEdit Pad © 2018\n"])</script>
1<script>self.__next_f.push([1,"ac:T1118,"])</script>
1<script>self.__next_f.push([1,"\nIn this post, we will take a look at what are the API’s Xamarin Android facilitates to support multipart upload. For the sake of simplicity, in this example, we will upload a bitmap image to the server.\n\nThe Multipart upload is a mechanism that enables you to upload large objects in chunks. In a mobile application context, it is useful when you capture a video or a photo using the device camera and want to upload it to your server.\n\nIn a multi-part request, each chunk/parts are separated by a delimiter. A delimiter is also known as a boundary that separates each part of a multi-part message. Each part of the message can define its own standard headers such as Content-Type and content disposition providing the name of the file whose value it contains. The multi-part delimiters and header fields are always 7-bit ASCII in any case.\n\nFor more detailed information on multi part content type search for RFC1341(MIME) or visit [http://www.w3.org/](http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html)\n\n## 1. Convert the Bitmap to stream\n\nLet us first convert the bitmap image into byte array to send it as ByteArrayContent via multi part form upload.\n\n```csharp\npublic async Task\u003cString\u003e UploadBitmapAsync(Bitmap bitmap)\n{\n    //converting bitmap into byte stream\n    byte[] bitmapData;\n    var stream = new MemoryStream();\n    bitmap.Compress(Bitmap.CompressFormat.Jpeg, 0, stream);\n    bitmapData = stream.ToArray();\n    var fileContent = new ByteArrayContent(bitmapData);\n}\n```\n\nNotice that the `bitmap.Compress()` write a compressed version of the bitmap to the specified stream. The second integer argument indicates the compress quality ranging from 0 being low quality and to 100 maximum.\n\n## 2. Add request headers\n\nAdd the following additional content header such as media content type and content disposition. The `\"my_uploaded_image.jpg\"` is the name of image sent to server.\n\n```csharp\nfileContent.Headers.ContentType = MediaTypeHeaderValue.Parse (\"application/octet-stream\");\nfileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue(\"form-data\")\n{\n    Name = \"file\",\n    FileName = \"my_uploaded_image.jpg\"\n};\n```\n\n## 3. Add content chunks\n\nNow let us initialize `MultipartFormDataContent` and add the chunks. The boundary is a random string used as a delimiter to separate each part of the message body.\n\n```csharp\nstring boundary = \"---8d0f01e6b3b5dafaaadaada\";\nMultipartFormDataContent multipartContent= new MultipartFormDataContent (boundary);\nmultipartContent.Add (fileContent);\n//multipartContent.Add(fileContent2);\n//multipartContent.Add(fileContent3);\n```\n\nDeclare a string constant that represents the web service endpoint to upload the poi image using multi part.\n\n## 4. Upload Bitmap using HttpClient\n\nLet us now proceed to upload the form content to server using HttpClient class PostAsync() method. The following code snippet demonstrates using HttpClient class for posting data to server.\n\n```csharp\nHttpClient httpClient = new HttpClient ();\nHttpResponseMessage response = await httpClient.PostAsync (UPLOAD_IMAGE, multipartContent);\nif (response.IsSuccessStatusCode) {\n      string content = await response.Content.ReadAsStringAsync();\n     return content;\n}\nreturn null;\n```\n\n## 5. Complete example code\n\n```csharp\nprivate const string UPLOAD_IMAGE = “http://YOUR_SERVER/api/poi/upload”\npublic async Task\u003cString\u003e UploadBitmapAsync (Bitmap bitmap){\n    byte[] bitmapData;\n    var stream = new MemoryStream();\n    bitmap.Compress(Bitmap.CompressFormat.Jpeg, 0, stream);\n    bitmapData = stream.ToArray();\n    var fileContent = new ByteArrayContent(bitmapData);\n\n    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse (\"application/octet-stream\");\n    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue(\"form-data\")\n    {\n        Name = \"file\",\n        FileName = \"my_uploaded_image.jpg\"\n    };\n\n    string boundary = \"---8d0f01e6b3b5dafaaadaad\";\n    MultipartFormDataContent multipartContent= new MultipartFormDataContent (boundary);\n    multipartContent.Add (fileContent);\n\n    HttpClient httpClient = new HttpClient ();\n    HttpResponseMessage response = await httpClient.PostAsync (UPLOAD_IMAGE, multipartContent);
1\n    if (response.IsSuccessStatusCode) {\n        string content = await response.Content.ReadAsStringAsync ();\n        return content;\n    }\n    return null;\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"ad:T9ce,"])</script>
1<script>self.__next_f.push([1,"\nJava POJO can contain simple primitive data types or collections. Like the primitive types, the Spring IoC container can instantiate POJOs with Java collection attributes. Java provides different types of collection types including set, list, map, etc. All of the collection types have their specific characteristics.\n\nIn Spring all these collection types can be configured using a set of built-in XML tags such as , , and\n\n. In this example, we will discuss how to configure the List collection. However, the same concept will apply to other collection types.\n\nLet us first declare the following POJOs.\n\n**User.java**\n\n```java\npublic class User {\n    private String name;\n    private String email;\n    private List cars;\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public String getEmail() {\n        return email;\n    }\n\n    public void setEmail(String email) {\n        this.email = email;\n    }\n\n    public List getCars() {\n        return cars;\n    }\n\n    public void setCars(List cars) {\n        this.cars = cars;\n    }\n\n    @Override\n    public String toString() {\n        return \"Name=\" + name + \" , Email=\" + email + \" , Car=\" + cars.toString();\n    }\n}\n```\n\n**Car.java**\n\n```java\npublic class Car {\n    private String model;\n    private double price;\n\n    public String getModel() {\n        return model;\n    }\n\n    public void setModel(String model) {\n        this.model = model;\n    }\n\n    public double getPrice() {\n        return price;\n    }\n\n    public void setPrice(double price) {\n        this.price = price;\n    }\n\n    @Override\n    public String toString() {\n        return model + \" \" + price;\n    }\n}\n```\n\nAs you can notice, a user can own a list of Cars. Let us now configure the bean inside `beans.xml` file.\n\nTo define a property of the interface `java.util.List` in the bean configuration, you specify a tag that contains the elements. The elements allowed inside the tag can be a simple constant value specified by .\n\nbeans.xml\n\nNow from the main class you can test the above configuration as follows.\n\nMain.java\n\n```java\npublic class Main {\n    public static void main(String[] args) throws Exception {\n        ApplicationContext context = new GenericXmlApplicationContext(\"beans.xml\");\n        User user = (User) context.getBean(\"userBean\");\n        System.out.println(user.toString());\n    }\n}\n```\n\nIf you want to configure the list by referring to other beans, you can do it using element.\n"])</script>
1<script>self.__next_f.push([1,"ae:T107d,"])</script>
1<script>self.__next_f.push([1,"\nIn our [previous tutorial](http://www.stacktips.com/articles/java-spring-jdbc-using-jdbctemplate-example), we have discussed how to use JdbcTemplate to access the MySQL database and perform insert and delete operation. In this tutorial, we will focus on how to query data database using the following approaches.\n\nThe JdbcTemplate class provides different overloaded `query()` methods to control the overall query process. A JDBC query operation involves the following tasks.\n\n-   Obtain a database connection from the data source.\n-   Create a PreparedStatement and Bind the parameters\n-   Execute the PreparedStatement object.\n-   Iterate the returned result set to extract data from the result set.\n-   Clean up the statement object and connection.\n\n## 1.0. Using RowCallbackHandler\n\nThe `RowCallbackHandler` is the is the primary interface that allows you to process the current row of the result set. One of the query() methods iterates the result set for you and calls your RowCallbackHandler for each row. So, the `processRow()` method will be called once for each row of the returned result set.\n\nThe following code snippet depicts how to query the database using RowCallbackHandler interface.\n\n```java\npublic Car selectCar(int id) {\n    final String sql = \"select * from cars where id = ?\";\n    final Car car = new Car();\n    RowCallbackHandler callback = new RowCallbackHandler() {\n\n        public void processRow(ResultSet rs) throws SQLException {\n            car.setId(rs.getInt(\"id\"));\n            car.setModel(rs.getString(\"model\"));\n            car.setPrice(rs.getDouble(\"price\"));\n        }\n    };\n\n    jdbcTemplate.query(sql, callback, id);\n    return car;\n}\n```\n\n## 2.0. Using RowMapper\n\nThe `RowMapper\u003cT\u003e` interface is more general than `RowCallbackHandler`. It maps a single row of the result set to a custom object. So this can be applied to a single row result set as well as a multiple row result set. In the `mapRow()` method of this interface, you have to construct the object that represents a row and return it as the methods return value.\n\n```java\npublic Car selectCar(int id) {\n    final String sql = \"select * from cars where id = ?\";\n    return jdbcTemplate.queryForObject(sql, new RowMapper\u003cCar\u003e() {\n\n        public Car mapRow(ResultSet rs, int rowNum) throws SQLException {\n            final Car car = new Car();\n            car.setId(rs.getInt(\"id\"));\n            car.setModel(rs.getString(\"model\"));\n            car.setPrice(rs.getDouble(\"price\"));\n            return car;\n        }\n\n    }, id);\n}\n```\n\nAlthough the above code works well, spring offers class `BeanPropertyRowMapper` for your convenience. The BeanPropertyRowMapper class automatically maps a row to a new instance of the specified class.\n\nThis method requires that the resultant class should have a default constructor. It does exactly the same thing as what we have done in the above code snippet. It first instantiates the class using Java reflection and then maps each column value to a property by matching their names.\n\n## 3.0. Using BeanPropertyRowMapper\n\nThe following code snippet depicts how to use `BeanPropertyRowMapper` implementation to query form database.\n\n```java\npublic Car selectCar(int id) {\n    final String sql = \"select * from cars where id = ?\";\n    return jdbcTemplate.queryForObject(sql, BeanPropertyRowMapper.newInstance(Car.class), id);\n}\n```\n\n## 4.0. Querying for Multiple Rows\n\nNow that we understand how to query single record, we can now have a look at querying list of cars from the database. This can be achieved using the `queryForList()` method by passing the SQL statement. The returned result will be a list of maps. Each map stores a row of the result set with the column names as the keys.\n\n```java\npublic List\u003cCar\u003e getAllCars() {\n    final String sql = \"select * from cars\";\n    final List\u003cCar\u003e vehicles = new ArrayList\u003cCar\u003e();\n    final List\u003cMap\u003cString, Object\u003e\u003e rows = jdbcTemplate.queryForList(sql);\n\n    for (Map\u003cString, Object\u003e row : rows) {\n        Car car = new Car();\n        car.setId((Integer) row.get(\"id\"));\n        car.setModel((String) row.get(\"model\"));\n        car.setPrice((Double) row.get(\"price\"));\n        vehicles.add(car);\n    }\n    return vehicles;\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"af:T817,"])</script>
1<script>self.__next_f.push([1,"\nIn the previous example, we have discussed how to use [JdbcTemplate to access the MySQL database](/articles/java-spring-jdbc-using-jdbctemplate-example) and perform insert and delete operation. In this tutorial, we will focus on how to insert a list of cars into the database.\n\nFor inserting the batch of cars, you need to call `insert()` method multiple times, the update will be very slow as the SQL statement will be compiled repeatedly. Instead, we can add a new method `insertCars()` in CarsDao for inserting a batch of Cars.\n\n## Batch Operation Using Spring JdbcTemplate\n\nThe `JdbcTemplate` class offers the `batchUpdate()` template method for batch update operations. It requires two arguments, a SQL statement and a `BatchPreparedStatementSetter` object. Using `batchUpdate()` method, the SQL statement is compiled only ones and executed multiple times.\n\nThe following snippet shows how to perform batch insert operation using JdbcTemplate.\n\n```java\npublic void insertCars(final List cars) {\n    final String inserQuery = \"insert into cars (id, model, price) values (?, ?, ?) \";\n    jdbcTemplate.batchUpdate(inserQuery,\n                new BatchPreparedStatementSetter() {\n        public void setValues(PreparedStatement ps, int i) throws SQLException {\n            Car car = cars.get(i);\n            ps.setInt(1, car.getId());\n            ps.setString(2, car.getModel());\n            ps.setDouble(3, car.getPrice());\n        }\n\n        public int getBatchSize() {\n            return cars.size();\n        }\n    });\n}\n```\n\nLet us now write the main class and test the above code.\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        ApplicationContext appContext = new GenericXmlApplicationContext(\"beans.xml\");\n        ICarsDao dao = appContext.getBean(\"carsDao\", ICarsDao.class);\n\n        //Batch update statement\n        List cars = new ArrayList();\n        for (int i = 1; i \u003c= 20; i++) {\n            Car car = new Car(i, \"Mercedes-Benz\" + i, 1*300);\n            cars.add(car);\n        }\n        dao.insertCars(cars);\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"b0:T891,"])</script>
1<script>self.__next_f.push([1,"\nIn our previous example, we have seen how to create [POJO Instances from the IoC Container](/articles/create-and-manage-pojos-with-spring-ioc-container). In this tutorial, we will examine how to create a POJO instance or bean in the Spring IoC container by invoking its constructor.\n\nCreating bean instance by invoking constructor is the common and direct way of creating beans. It is similar to creating the class instance using the new operator. All you have to do is to define a POJO class with a constructor and use the configuration.\n\nIn this example, I will use the following POJO class to demonstrate how to create POJOs by invoking the constructor.\n\n```java\npublic class Car {\n    private String model;\n    private double price;\n\n    public Car() { }\n\n    public Car(String model, double price) {\n        this.model = model;\n        this.price = price;\n    }\n\n    public String getModel() {\n        return model;\n    }\n\n    public void setModel(String model) {\n        this.model = model;\n    }\n\n    public double getPrice() {\n        return price;\n    }\n\n    public void setPrice(double price) {\n        this.price = price;\n    }\n}\n```\n\nTo define the above Car bean in the Spring IoC container, you can add the following code snippet to `bean.xml` configuration file.\n\n-   Note that, if more then one elements is specified, Spring invokes the most appropriate constructor that matches your arguments.\n-   Use Spring’s element to define constructor arguments, then for each element Spring injects the value through the setter method.\n-   If no is specified to the bean configuration, the default constructor with no arguments is invoked.\n-   You can specify the type and index attributes or the name attribute for the element to avoid constructor ambiguity.\n\nYou can write the following Main class to test your Cars bean initialization by retrieving the bean instance from the Spring IoC container:\n\n```java\npublic class Main {\n    public static void main(String[] args) throws Exception {\n        ApplicationContext context = new GenericXmlApplicationContext(\"beans.xml\");\n        Car car = (Car) context.getBean(\"carBean\");\n        System.out.println(car.toString());\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"b1:T1560,"])</script>
1<script>self.__next_f.push([1,"\nThere are various data access technologies to perform persistence operations in Java enterprise applications. JDBC is among the most popular one. This tutorial explains how to initialize a database and access data using Spring JDBC.  \n\nSpring offers two ways connect to a database. Data source or the `DriverManager`. The DriverManager is the legacy approach and data source is newer one. It is recommended to use the new DataSource facility to connect to databases and other resources.\n\nDataSource facility has several advantages over DriverManager facility like DataSource increases portability, enables connection pooling and distributed transactions, the DriverManager does not allow such techniques.\n\nHere in this example, we are using data source to communicate with MySQL database. We will create the `Cars` table with the following attributes.\n\n```sql\nCREATE TABLE `Cars` (\n  `id` int(11) NOT NULL,\n  `model` varchar(45) DEFAULT NULL,\n  `price` double(10,2) DEFAULT NULL,\n  PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n```\n\n## 1. Configuring Bean\n\nThe corresponding Java bean class for the above Cars table will look like the following code:\n\n```java\npublic class Car {\n    private int id;\n    private String model;\n    private double price;\n\n    public Car() { }\n\n    public Car(int id, String model, double price) {\n        this.id = id;\n        this.model = model;\n        this.price = price;\n    }\n\n    public int getId() {\n        return id;\n    }\n\n    public void setId(int id) {\n        this.id = id;\n    }\n\n    public String getModel() {\n        return model;\n    }\n\n    public void setModel(String model) {\n        this.model = model;\n    }\n\n    public double getPrice() {\n        return price;\n    }\n\n    public void setPrice(double price) {\n        this.price = price;\n    }\n}\n```\n\nNow, let us configure the Car bean declaration to `beans.xml` file for Spring IoC to locate, initialize and manage to Car bean instance.\n\n## 2. Configuring data source object\n\nAs discussed above, we will be using Spring data source approach to connect to MySQL database. For this you need to add the `BasicDataSource` bean configuration to your `bean.xml` file.\n\nNotice that in the above bean configuration the `localhost` indicated the location of MySQL database. Currently it is located on my development machine. Don’t forget to change the username and password of your own, if you configured differently while installing your MySQL server.\n\n## 3. Understanding Spring JdbcTemplate\n\nSpring JdbcTemplate is a class that takes care of all the boilerplate code required for creating a database connection and closing the resources. It makes our life a lot easier by saving the effort and development time. Add the following bean declaration to initialize the JdbcTemplate instance.\n\nNotice that we are injecting the datasource bean instance defined above to initialize the JdbcTemplate bean.\n\n## 4. Executing SQL statements\n\nSpring JdbcTemplate exposes many helpful methods for performing CRUD operations on database. Following are most common methods that we use from JdbcTemplate.\n\n-   **execute(String sql)** – Issue a single SQL execute, typically a DDL statement.\n-   **queryForList(String sql, Object\\[\\] args)** – Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list.\n-   **update(String sql)** – Issue a single SQL update operation (such as an insert, update or delete statement).\n\nNow lets bring our JdbcTemplate to action. We will use the JdbcTemplate bean in our DAO class or any class that will communicate with our database. Let us create a DAO interface with the following methods:\n\n```java\npublic interface ICarsDao {\n    int insertCar(Car car);\n    void deleteCar(int id);\n}\n```\n\nNow let us implement ICarDao interface and provide the logic to insert and delete a user form database.\n\n```java\npublic class CarsDao implements ICarsDao {\n    private JdbcTemplate jdbcTemplate;\n\n    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {\n        this.jdbcTemplate = jdbcTemplate;\n    }\n\n    public int insertCar(Car car) {\n        String inserQuery = \"
1insert into cars (id, model, price) values (?, ?, ?) \";\n        Object[] params = new Object[] { car.getId(), car.getModel(), car.getPrice() };\n        int[] types = new int[] { Types.INTEGER, Types.VARCHAR, Types.INTEGER };\n\n        return jdbcTemplate.update(inserQuery, params, types);\n    }\n\n    public void deleteCar(int model) {\n        String delQuery = \"delete from cars where id = ?\";\n        int count = jdbcTemplate.update(delQuery, new Object[] { model });\n        if (count != 0)\n            System.out.println(\"Car deleted successfully.\");\n        else\n            System.out.println(\"Car with given id as it doesn't exist\");\n    }\n\n}\n```\n\nNow that we are ready with the DAO implementation, let us test those methods. Create a Java class TestMain.java and add the following code snippets\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n\n        ApplicationContext appContext = new GenericXmlApplicationContext(\"beans.xml\");\n        ICarsDao dao = appContext.getBean(\"carsDao\", ICarsDao.class);\n        Car car = new Car(1, \"Volkswgen\", 300);\n        dao.insertCar(car);\n\n        System.out.println(\"User inserted with id= \" + 2);\n        dao.deleteCar(3);\n    }\n}\n```\n\nIf all your configurations are fine, you should be able to insert and delete data from Cars table.\n"])</script>
1<script>self.__next_f.push([1,"b2:Ta3d,"])</script>
1<script>self.__next_f.push([1,"\nThere are various data access technologies to perform persistence operations in Java enterprise applications. JDBC is among the most popular one. Spring provides data access operations performed with JDBC using three main approaches:\n\n1.  **Using Template Method pattern** based utility classes, namely JdbcTemplate and NamedParameterJdbcTemplate, to perform JDBC operations more easily by removing repetitive data access code blocks in the application, properly handling resource cleanups, and so on.\n2.  **Using database** meta data to simplify queries using classes such as SimpleJdbcInsert and SimpleJdbcCall. That way you need to provide only a table or stored procedure name and a map of parameters corresponding to column names to perform an SQL operation.\n3.  **Using MappingSqlQuery**, SqlUpdate, and StoredProcedure classes to represent database operations as reusable Java objects so that you can use them over and over again by providing only different query parameters each time.\n\nTo start working with JDBC from Spring application, you first need to obtain the data- base connection. Spring offers two ways to obtain database connections within the JDBC API. `Data source` or the `DriverManager`.\n\nThe DriverManager is the legacy approach and DataSource is newer one. It is recommended to use the new DataSource facility to connect to databases and other resources. DataSource facility has several advantages over DriverManager facility like DataSource increases portability, enables connection pooling and distributed transactions, the DriverManager does not allow such techniques.\n\nIf you’re using Maven project configuration, you need to add the following Spring dependencies elements into your `pom.xml`:\n\n#### Maven dependency\n\n```xml\n    org.springframework\n    spring-jdbc\n    4.2.1.RELEASE\n\n    commons-dbcp\n    commons-dbcp\n    1.4\n```\n\n#### Gradle dependency\n\n```groovy\n'org.springframework:spring-jdbc:4.2.1.RELEASE'\n'commons-dbcp:commons-dbcp:1.4'\n```\n\nThe core class of Spring’s JDBC support is `JdbcTemplate`. It simplifies the use of JDBC and helps to avoid common errors. JdbcTemplate can be used to execute SQL queries or insert, update, and delete statements. It executes core JDBC work flow, initiating iteration over ResultSets and catching JDBC exceptions and translating them to the generic, more informative DataAccessException hierarchy defined by Spring. Application code only needs to provide SQL and ResultSet processing logic if necessary.\n\nNow that we understood the basics of Spring JDBC, in the next post we will continue with creating our first Spring JDBC application.\n"])</script>
1<script>self.__next_f.push([1,"b3:T16da,"])</script>
1<script>self.__next_f.push([1,"\n| # | Custom ListView ScrollView Implementation – Android |\n| --- | --- |\n| 1 | Pinned section listviewEasy to use ListView with pinned sections for Android.https://github.com/beworker/pinned-section-listview |\n| 2 | PullToRefresh-ListViewA generic, customizable, open source Android ListView implementation that has ‘Pull to Refresh’ functionality.https://github.com/erikwt/PullToRefresh-ListView |\n| 3 | FlabbyListViewAndroid library to display a ListView whose cells are not rigid but flabby and react to ListView scroll.https://github.com/jpardogo/FlabbyListView |\n| 4 | XListView-AndroidListView supports pull refresh and pull up to load more feature.https://github.com/Maxwin-z/XListView-Android |\n| 5 | PinterestListViewPinterest style ListView for Androidhttps://github.com/vladexologija/PinterestListView |\n| 6 | Android-pulltorefresh-and-loadmoreAndroid custom list view, with interaction pattern load more and pull to refresh to load data dynamicallyhttps://github.com/shontauro/android-pulltorefresh-and-loadmore |\n| 7 | PinnedHeaderListViewA ListView with pinned section headers for Androidhttps://github.com/JimiSmith/PinnedHeaderListView |\n| 8 | ParallaxScrollParallax ScrollView and ListView for Androidhttps://github.com/nirhart/ParallaxScroll |\n| 9 | Android-HorizontalListViewHorizontalListView is an Android ListView widget which scrolls in a horizontal manner (in contrast with the SDK-provided ListView which scrolls vertically).https://github.com/MeetMe/Android-HorizontalListView |\n| 10 | LinearListViewAndroid library that allows you to bind a LinearLayout with a ListAdapter.https://github.com/frankiesardo/LinearListView |\n| 11 | ParallaxListViewAn Android ListView Demo with a parallax effect header like Path.https://github.com/Gnod/ParallaxListView |\n| 12 | PagedHeadListViewAndroid boosted ListView supporting paginated header with a new material page indicator.https://github.com/JorgeCastilloPrz/PagedHeadListView |\n| 13 | PullZoomViewAn Android custom ListView and ScrollView with pull to zoom-in.https://github.com/Frank-Zhu/PullZoomView |\n| 14 | HeaderListViewAndroid ListView with sticky headershttps://github.com/applidium/HeaderListView |\n| 15 | ListviewFilterAwesome Listview filter functionality in Android.https://github.com/bhavyahmehta/ListviewFilter |\n| 16 | android-accordion-viewSimple ListView based Android AccordionViewhttps://github.com/hamsterready/android-accordion-view |\n| 17 | DragNDropListAn easy to use Drag \u0026 Drop List for Android. Direct replacement of the android ListView.https://github.com/terlici/DragNDropList |\n| 18 | QuickReturnAndroid ListView that implements the QuickReturn UI pattern. Written from scratch with focus on performance.https://github.com/felipecsl/QuickReturn |\n| 19 | ZrcListView一个顺滑又漂亮的Android下拉刷新与加载更多列表组件。https://github.com/zarics/ZrcListView |\n| 20 | android-swipelistviewAn Android List View implementation with support for drawable cells and many other swipe related featureshttps://github.com/47deg/android-swipelistview |\n| 21 | android-pulltorefreshThis project aims to provide a reusable pull to refresh widget for Android.https://github.com/johannilsson/android-pulltorefresh |\n| 22 | StickyListHeadersAn android library for section headers that stick to the tophttps://github.com/emilsjolander/StickyListHeaders |\n| 23 | LazyListLazy load of images in Androidhttps:/github.com/thest1/LazyList |\n| 24 | Floating Group Expandable ListViewAn open source Android library that provides a floating group view at the top of the ExpandableListViewhttps://github.com/diegocarloslima/FloatingGroupExpandableListView |\n| 25 | PullSeparateListView到顶部或底部时拉动,item分离效果https://github.com/chiemy/PullSeparateListView |\n| 26 | Android-SlideExpandableListViewA better ExpandableListView, with animated expandable views for each list itemhttps://github.com/tjerkw/Android-SlideExpandableListView |\n| 27 | HorizontalVariableListViewHorizontal list view for Android which allows variable items widthshttps://github.com/sephiroth74/HorizontalVariableListView |\n| 28 | ListBuddiesAndroid library to achieve in an easy way, the behaviour of the home page in the Expedia app, with a pair of auto-scroll circular parallax ListViews.https://github.com/jpardogo/ListBuddies |\n| 29 | Android-Tiling-ScrollViewA tiling scrollview to display large picture (similar to iOS “CATiledLayerâ€
1)https://github.com/ened/Android-Tiling-ScrollView |\n| 30 | PullScrollView1.仿照新浪微博Android客户端个人中心的ScrollView,下拉背景伸缩回弹效果。 2.ScrollView仿IOS回弹效果。https://github.com/MarkMjw/PullScrollView |\n| 31 | DiscrollviewScroll + discover = DiscrollViewhttps://github.com/flavienlaurent/discrollview |\n| 32 | StickyScrollViewItemsA small android library for tagging views inside a ScrollView as “sticky” making them stick to the top of the scroll container until a new sticky view comes and takes it’s placehttps://github.com/emilsjolander/StickyScrollViewItems |\n| 33 | SwipeMenuListViewSwipeMenuListViewhttps://github.com/baoyongzhang/SwipeMenuListView |\n| 34 | Android-ObservableScrollViewAndroid library to observe scroll events on scrollable views.https://github.com/ksoichiro/Android-ObservableScrollView |\n| 35 | Pull-to-Refresh.Rentals-AndroidThis project aims to provide a simple and customizable pull to refresh implementation. Made in Yalantishttps://github.com/Yalantis/Pull-to-Refresh.Rentals-Android |\n| 36 | StikkyHeaderThis is a very simple library for Android that allows you to stick an header to a scrollable view and easly apply animation to ithttps://github.com/carlonzo/StikkyHeader |\n| 37 | QuickscrollBringing extended scrolling features to Android’s native ListView and ExpandableListView.https://github.com/andraskindler/quickscroll |\n"])</script>
1<script>self.__next_f.push([1,"b4:T778,"])</script>
1<script>self.__next_f.push([1,"\nSpring POJOs are initialized and managed by Spring IoC Container. Sometimes, you may need perform some initialization code before a POJO is used. A typical example is to open a database or network connection. Similarly you may want to perform the corresponding destruction tasks at the end of their life cycle. Therefore, sometimes it is necessary to customize bean initialization and destruction in the Spring IoC container.\n\nThe POJO life cycle tasks can be created using callback methods. A typical life cycle of a bean can be explained as follows:\n\n1.  Create the bean instance either by a constructor injection or by a factory method.\n2.  Set the values and bean references to the bean properties.\n3.  Call the bean initialization callback methods.\n4.  The bean is ready to be used.\n5.  When the container is shut down, call the bean destruction callback methods are called.\n\nSpring initialization and destruction callback methods can be configured by setting the values for `init-method` and `destroy-method` attributes in the bean declaration. You need to specify the callback method names as follows.\n\nNotice that in the above code snippet, we have specified `onStart` and `onDestroy` callback methods to control POJO initialization and destruction. Here is how, you can configure the callback methods to your POJO class.\n\n```java\npublic class Pizza {\n    private String name;\n    private double price;\n\n    public Pizza() { }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public double getPrice() {\n        return price;\n    }\n\n    public void setPrice(double price) {\n        this.price = price;\n    }\n\n    public void onStart() throws IOException {\n        System.out.println(\"Inside onStart\");\n    }\n\n    public void onDestroy() throws IOException {\n        System.out.println(\"Inside onDestroy\");\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"b5:Tba7,"])</script>
1<script>self.__next_f.push([1,"\nMost commercial websites are targeted for global users. This means that you need to make your application to support different languages. Spring provides built in support for localizing strings used across application.\n\nThe string message for different locale are stored in separate properties files. These properties files are also called as resource bundles. Spring application context can resolve text messages for target locales by keys. By convention the Java resource bundle files are named as `__.properties`.\n\nSpring uses the `MessageSource` interface to resolve the resource bundles. The ApplicationContext interface extends MessageSource interface so that all application contexts are able to resolve text messages. An application context delegates the message resolution to a bean with the name `messageSource`. `ResourceBundleMessageSource` is the most common MessageSource implementation that resolves messages from resource bundles for different locales.\n\nCreate a properties file containing your static strings in your default locale i.e English. In our example we will create `message.properties` file.\n\n**message.properties**\n\n```text\nmessage.hello = Hello\nmessage.welcome = {0}. {1} {2} welcome to stacktips.com.\n```\n\nNext thing we will do is to add translated strings in a separate file. By convention the file names are append the name of the file with an “underscore” sign followed by the locale code of the language you are translating it to.\n\nIn this example, we will crate the French translation of the above strings. Create a new file named `message_fr.properties` and paste the following strings.\n\n**message\\_fr.properties**\n\n```text\nmessage.hello = Bonjour\nmessage.welcome = {0}. {1} {2} Bienvenue a stacktips.com.\n```\n\nPlease note that, I have used Google translator to translate the above messages in to French version.\n\nNow we need to tell Spring to handle the localization by using the above two files. This can be done by adding the `ResourceBundleMessageSource` bean in `beans.xml` declaration.\n\nNotice that in the above bean configuration, the basename is used to tell the Spring IoC controller, which file to look for for resolving the localized string.\n\nNow, let us load the strings form different files based on the selected locale.\n\n```java\npublic class Main {\n    public static void main(String[] args) throws Exception {\n        ApplicationContext context = new GenericXmlApplicationContext(\"beans.xml\");\n\n        String helloEn = context.getMessage(\"message.hello\", null, Locale.ENGLISH);\n        String welcomeEn = context.getMessage(\"message.welcome\", new String[] { \"Mrs\", \"Sally\", \"Peterson\" }, Locale.ENGLISH);\n        System.out.println(helloEn +  welcomeEn);\n\n        String helloFr = context.getMessage(\"message.hello\", null, Locale.FRENCH);\n        String welcomeFr = context.getMessage(\"message.welcome\", new String[] { \"Mr\", \"Sally\", \"Peterson\" }, Locale.FRENCH);\n        System.out.println(helloFr  + welcomeFr);\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"b6:Taf8,"])</script>
1<script>self.__next_f.push([1,"\nIn our previous tutorial, we have seen how to create and manage POJOs With Spring IoC container using XML configuration and `@Configuration` and `@Bean` Annotations. In this example, we will examine how to initialize spring POJO by reading data from external resources such as property file.\n\nIn regular Java applications, you need to write your own code to read file, but Spring offers the the `PropertySourcesPlaceholderConfigurer` class that facilitates to load the contents of external file.\n\nIn this example, we will initialize the POJO by reading the data from a .properties file. Let us first create a bean class `Car.java` with two properties name and model.\n\n```java\npublic class Car {\n    private String model;\n    private double price;\n\n    public Car() { }\n\n    public String getModel() {\n        return model;\n    }\n\n    public void setModel(String model) {\n        this.model = model;\n    }\n\n    public double getPrice() {\n        return price;\n    }\n\n    public void setPrice(double price) {\n        this.price = price;\n    }\n}\n```\n\nLet us assume you have a series of values in a properties file you want to access and initialize the bean properties. Create a property file named `car.properties` with the following data.\n\n```properties\ncar.model=Volkswagen Polo\ncar.price=5000.00\n```\n\nTo make the contents of the car.properties file accessible to set up other beans, you can use the `PropertySourcesPlaceholderConfigurer` class read its value. Add the following configuration to your `beans.xml` file.\n\n```xml\n        classpath:car.properties\n```\n\nNotice that in the above code snippet, the location property for the bean is defined with `classpath:car.properties`. The classpath: prefix tells Spring to look for the car.properties file in the Java class path.\n\nThe above configuration is enough, but this can throw an exception if the file is not found. This can be avoided using `ignoreResourceNotFound` and `ignoreUnresolvablePlaceholders` properties as follows.\n\n```xml\n        classpath:car.properties\n```\n\nAfter declaring the `PropertySourcesPlaceholderConfigurer` bean, you can access the values of the `car.properties` file as follows.\n\nThe syntax to read the values form the file is `${yy:default_value}`. If value for a key is is found in the properties file, the corresponding value is assigned to the bean property. Otherwise it loads the default value.\n\nNow you can initialize the bean and test the code as follows.\n\n```java\npublic class Main {\n\n    public static void main(String[] args) throws Exception {\n        ApplicationContext context = new GenericXmlApplicationContext(\"beans.xml\");\n        Car car = (Car) context.getBean(\"carDetailsBean\");\n        System.out.println(car.getModel()); // Volkswagen Polo\n        System.out.println(car.getPrice()); // 5000\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"b7:T55a,\nWhen you declare a POJO instance or bean in the configuration file, you are actually defining a template for bean creation, not an actual bean instance. The actual bean instance is created when the `getBean()` method is called. While bean is instantiated by the Spring IoC, the framework decides the scope of the instance.\n\nFollowing are the different bean instance scopes supported in Spring.\n\n-   **singleton** – Creates at most one bean instance per Spring IoC container\n-   **prototype** – Creates a new instance each requested\n-   **request** – Creates a single bean instance per HTTP request;\n-   **session** – Creates a single bean instance per HTTP session;\n-   **global session-** Creates a single bean instance per global HTTP session\n\nYou can set the bean scope using the element scope attribute. The default scope fro bean is set to Singleton. This means that only one instance of bean can be created in the IoC container and the same instance can be shared across.\n\nThe following code snippet shows how to define the bean scope using XML configuration.\n\nYou can also specifying bean scope from Java code using `@Scope` annotation as follows:\n\n```java\n@Configuration\npublic class MyBeanConfig {\n    @Bean\n    @Scope(value = BeanDefinition.SCOPE_SINGLETON)\n    public Crayon crayonToy() {\n        return new Crayon(\"Yellow crayon\", 50);\n\n    }\n}\n```\nb8:T81a,"])</script>
1<script>self.__next_f.push([1,"\nIn our previous tutorial, we have declared and configured Spring bean classes using XML configuration file. If you want to reduce the number of XML configuration files, you can do so by configuring the Spring POJO for the Spring IoC container using `@Configuration` and `@Bean` annotation.\n\n## @Configuration \u0026 @Bean Annotations\n\nAnnotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.\n\nThe @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.\n\nLet us examine how to use the @Configuration and @Bean annotation to configure the following bean class.\n\n```java\npublic class Toy {\n    private String name;\n    private double price;\n\n    public Toy() { }\n    public Toy(String name, double price) {\n        this.name = name;\n        this.price = price;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public double getPrice() {\n        return price;\n    }\n\n    public void setPrice(double price) {\n        this.price = price;\n    }\n}\n```\n\nThe above bean class can be configured using the following XML configuration.\n\nThe following code snippet shows the simplest form of bean declaration using @Configuration and @Bean annotation.\n\n```java\n@Configuration\npublic class MyBeanConfig {\n\n    @Bean\n    public Toy crayonToy() {\n        return new Toy();\n    }\n}\n```\n\nHere the method name annotated with @Bean works as bean ID and it creates and returns actual bean instance. Your configuration class can have declaration for more than one @Bean.\n\nOnce your configuration classes are defined, you can load \u0026 provide them to Spring container using `AnnotationConfigApplicationContext` class.\n\n```java\nAnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();\ncontext.register(MyBeanConfig.class);\ncontext.refresh();\n\nCrayon myService = context.getBean(Crayon.class);\n```\n"])</script>
1<script>self.__next_f.push([1,"b9:T17b6,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we will examine how to design and configure POJO instance values for the Spring IoC container in an XML file. Next, instantiate the Spring IoC container to access to the POJO instance values defined in an XML file.\n\nFor the sake of simplicity, in this example we will declare a class NameGenerator which will generate full name from initial, firstname and surname.\n\nLet us first began with creating a new eclipse Maven project.\n\n## 1. Add the required dependencies\n\nAdd the following Maven depandencies to your project pom.xml file.\n\n```xml\n    4.0.0\n    com.javatechig\n    SpringBeanExample\n    0.0.1-SNAPSHOT\n\n\n        4.0.2.RELEASE\n        3.0.3\n        3.2.3.RELEASE\n\n\n\n\n            org.springframework\n            spring-core\n            ${org.springframework.version}\n\n\n\n            org.springframework\n            spring-beans\n            ${org.springframework.version}\n\n\n\n            org.springframework\n            spring-context\n            ${org.springframework.version}\n```\n\n## 2. Create the POJO Class\n\nLet us create a NameGenerator class that has three properties— prefix, firstName, and surName.\n\n```java\npublic class NameGenerator {\n    private String firstName;\n    private String surName;\n    private String initial;\n\n    public NameGenerator() {}\n\n    public NameGenerator(String initial, String firstName, String surName) {\n        this.firstName = firstName;\n        this.surName = surName;\n        this.initial = initial;\n    }\n\n    public String getFullName() {\n        return initial + \" \" + firstName + \" \" + surName;\n    }\n\n    public String getFirstName() {\n        return firstName;\n    }\n\n    public void setFirstName(String firstName) {\n        this.firstName = firstName;\n    }\n\n    public String getSurName() {\n        return surName;\n    }\n\n    public void setSurName(String surName) {\n        this.surName = surName;\n    }\n\n    public String getInitial() {\n        return initial;\n    }\n\n    public void setInitial(String initial) {\n        this.initial = initial;\n    }\n}\n```\n\nNotice that, in the above code snippet the NameGenerator class has a method `getFullName(),` that is used to generate the fullname.\n\nThe NameGenerator class can be instantiated by using standard Java constructorn call. When you use the Spring IoC container to initialize POJOs, if you use the standard Java constructor the mechanism is called constructor injection, where as if you use setter methods the mechanism is called setter injection.\n\n## 3. Create a XML Configuration for your POJO\n\nTo define instances of a POJO class in the Spring IoC container, you have to create an XML configuration and initialize the properties.\n\nCreate a new xml file named `bean.xml` under the root of the project classpath for easier testing with in an IDE. The following code snippet explains how to configure bean in Spring.\n\n```xml\n            Mr.\n\n\n            Steve\n\n\n            Peterson\n```\n\n**Notes:**\n\n-   Spring XML configuration file can have any name, in this example we have created beans.xml.\n-   Each POJO instances must have a unique name or id per context. The id will be used to to uniquly identify the beans.\n-   The value for class attribute should contain a fully qualified POJO class name so the Spring IoC container can instantiate it.\n-   If you want to configure the bean property via setter injection, you use the element and specify the property name in its name attribute. A requires that the underlying POJO class contain a corresponding setter method.\n-   The Spring bean properties can be initialized via constructor injection by declaring them in the elements.\n\nThe following example shows how to use the constructor-arg element to initialize bean via constructor injection.\n\n```xml\n            Mr.\n\n\n            Steve\n\n\n            Peterson\n```\n\nNote that the constructor arguments are order based, so you have to be careful about the order while declaring in `bean.xml` file.\n\nAlthough a bean’s name can be defined by the name attribute of the element, the preferred way of identifying a bean is through the standard XML id attribute. In this way, if your text editor is XML-aware, it can help to validate each bean’s uniqueness at design time.\n\n## 4. Instantiate the Spring IoC Container\n\nTo create bean instances, we first need to instantiate the Spring IoC container by reading the XML configuration files (in our case `beans.xml`). Once IoC container is initialized, you can get the bean instances from the IoC container using bean name or id.\n\nSpring provides two types of IoC container implementations.\n\n-   Using bean factory (BeanFactory class)\n-   Using application context (ApplicationContext interface)\n\nThe application context provides some of the advance features than the bean factory. We recommend using the application context for every application unless it is intended. The `ApplicationContext` is an interface, so will use `GenericXmlApplicationContext` class which is an implementation of ApplicationContext interface.\n\nThe following code snippet shows how to load the XML configuration file from the classpath.\n\n```java\nApplicationContext context = new GenericXmlApplicationContext(\"beans.xml\");\n```\n\nOnce the application context is instantiated, we can get the POJO instance and access the properties.\n\n## 5. Get Bean Instance from the IoC Container\n\nTo get the bean instance, you need to call the `getBean()` method by pasing unique bean name.  \nLet us create a new class with a main method so that we can instantiate the bean and call the `getFullName()` method.\n\n```java\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.GenericXmlApplicationContext;\n\npublic class Main {\n    public static void main(String[] args) {\n        ApplicationContext context = new GenericXmlApplicationContext(\"beans.xml\");\n        NameGenerator generator = (NameGenerator) context.getBean(\"nameGenerator\");\n        System.out.println(generator.getFullName());\n    }\n}\n```\n\n**Output:**\n\nThe application will initialize the bean and print the full name on console.\n"])</script>
1<script>self.__next_f.push([1,"ba:T1206,"])</script>
1<script>self.__next_f.push([1,"\nIn the [previous tutorial](/articles/introduction-to-spring-mvc-and-dispatcher-servlet), we have discussed the role of a Dispatcher Servlet and the steps required to create a Spring MVC application. In this tutorial, we will discuss different type of request mapping to Spring controllers.\n\nDispatcher Servlet is used to handle all incoming requests and route them through Spring. When `DispatcherServlet` receives a web request, it determines which controllers should handle the incoming request.\n\nIt first scans for all classes that are declared with the `@Controller` annotation. The dispatching process depends on the various `@RequestMapping` annotations declared in a controller class and its handler methods. There are three levels of request mapping can be defined in Spring controller.\n\n### Handler Level mapping\n\nThe simplest strategy for using @RequestMapping annotations is to decorate the handler methods directly. In this method, you need to declare mapping for each handler method with the @RequestMapping annotation containing a URL pattern. If a handler’s @RequestMapping annotation matches the request URL, DispatcherServlet it dispatches the request to this handler for it to process the request.\n\nFollowing are the different mapping types supported.\n\n-   **By path**  \n    @RequestMapping(“path”)\n-   **By HTTP method**  \n    @RequestMapping(“path”, method=RequestMethod.GET). Other Http methods such as POST, PUT, DELETE, OPTIONS, and TRACE are also supported.\n-   **By query parameter**  \n    @RequestMapping(“path”, method=RequestMethod.GET, params=”param1”)\n-   **By the presence of request header**  \n    @RequestMapping(“path”, header=”content-type=text/\\*”)\n\nThe request mapping for methods can be defined as follows:\n\n```java\n@Controller\npublic class Employee {\n\n    @RequestMapping(\"/employee/add\")\n    public ModelAndView add(\n            @RequestParam(value = \"firstName\") String firstName,\n            @RequestParam(value = \"surName\") String surName) {\n        //....\n        //....\n        return null;\n    }\n\n    @RequestMapping(value={\"/employee/remove\",\"/employee/delete\"})\n    public ModelAndView delete(\n            @RequestParam(value = \"uuid\") String uuid) {\n        //....\n        //....\n        return null;\n    }\n}\n```\n\nIn the above code snippet, the controller `add()` method is declared with `@RequestMapping(\"/employee/add\")`. If the incoming request path to matches is,`/employee/add` then the add() handler method will be invoked to process the request.\n\nHandler mappings match URLs according to their paths relative to the context path (i.e., the path where the web application is deployed) and the servlet path (i.e., the path mapped to DispatcherServlet).\n\n### Mapping at Controller Class level\n\nThe @RequestMapping annotation can also be used to decorate a controller class. This is helpful to take the control at the top level and filter the incoming requests. If the incoming request matches the pattern defined in the controller class, then it searches the controller methods mappings.\n\nThe following code snippet describes how to define Spring @RequestMapping at the controller class level.\n\n```java\n@Controller\n@RequestMapping(\"/employee/*\")\npublic class Employee {\n\n    @RequestMapping(\"add\")\n    public ModelAndView add(\n            @RequestParam(value = \"firstName\") String firstName,\n            @RequestParam(value = \"surName\") String surName) {\n        //....\n        //....\n        return null;\n    }\n\n    @RequestMapping(value={\"remove\",\"delete\"})\n    public ModelAndView delete(\n            @RequestParam(value = \"uuid\") String uuid) {\n        //....\n        //....\n\n        return null;\n    }\n}\n```\n\nNotice that, we have used the wildcard (\\*) for the @RequestMapping annotation for broader URL matching.\n\n### Mapping Request Type\n\nThe `@RequestMapping` annotation handles all types of incoming HTTP request including GET, POST, PUT, DELETE, PATCH etc. By default, it’s assumed all incoming requests to URLs are of the HTTP GET kind. To differentiate the mapping by HTTP request type, we need to explicitly specify the HTTP request method in the @RequestMapping declaration.\n\nThe following code snippet describes how to declare Spring mappings by HTTP request methods.\n\n```java\n@Controller\n@RequestMapping(\"/employee/*\")\npublic class Employee {\n\n    @RequestMapping(value = { \"remove\", \"delete\" }, method = { RequestMethod.POST,  RequestMethod.DELETE })\n        public ModelAndView delete(@RequestParam(value = \"uuid\") String uuid) {\n            // ....\n            // ....\n\n            return null;\n        }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"bb:T1bc0,"])</script>
1<script>self.__next_f.push([1,"\nIn the course of this tutorial, we will learn how to create your first Spring MVC application using eclipse IDE using Maven build type.\n\n## Prerequisites\n\n-   Java version 1.7\n-   Latest Spring STS\n-   Apache Tomcat 7.0.x\n\nThis tutorial assumes that, you have downloaded and installed the above mentioned softwares on your computer. If you have not installed Java on your development machine, you can follow the official oracle documentation for the installation for your configuration.\n\nWithout spending any further time, let us jump straight into creating the project in eclipse.\n\n## Create a Maven Project\n\n-   **File** -\u003e **New** -\u003e **Other**… It will open the eclipse select wizard.\n\n[![Create Maven Spring project](/media/articles/163/Introduction-to-Spring-MVC-and-Dispatcher-Servlet-620x398.png)](http://stacktips.com)\n\n-   Select **Maven** -\u003e **Maven Project** and click **Next**.\n-   Again click **Next** on New Maven Project dialog.\n-   Select an Archetype either by filtering **webapp** or selecting from the available artifacts and click **Next**.\n\n[![Create new eclipse maven project](/media/articles/162/Create-new-eclipse-maven-project.png)](http://stacktips.com)\n\n-   Provide the details for Group Id and Artifact Id and click **Finish**. As a general practice, the group id is your company domain name (i.e. com.javatechig) and artifact id is the name of your application.\n-   This will create a basic Maven project template in eclipse.\n\n## Create a Server Instance\n\nIn this example we will be using **Apache** **Tomcat** application server for deploying our Spring MVC application. Now let us add a server instance on eclipse.\n\n-   **File** -\u003e **New** -\u003e **Other**… It will open the eclipse select wizard.\n\n[![Add Tomcat Server Eclipse](/media/articles/162/Add-Tomcat-Server-Eclipse.png)](http://stacktips.com)\n\n-   Select Server -\u003e Server and click **Next**.\n-   Select Apache -\u003e **Tomcat v7.0 Server** and click **Next**. In this example, we will be using Apache Tomcat version 7.0. However, the similar steps will work for other tomcat versions.\n-   Browse and select the **Apache Tomcat v7.0** server installation directory and click **Finish**.\n\n## 4. Update Project Build Path\n\nYou might notice a error on your project. This is due to the project Build path problem. To fix this you need to right click on project -\u003e **Properties** to open project Java Build Path settings.\n\nSelect **Libraries** tab and click on **Add Library**…-\u003e **Server Runtime** -\u003e **Apache Tomcat** -\u003e **Finish**.\n\n## 5. Configure Spring Dependency\n\nBefore we develop Spring MVC web application, we need to configure the project by adding the required Maven dependencies. Add the following Maven dependencies into your `pom.xml` file.\n\n##### pom.xml\n\n```xml\n    4.0.0\n    com.javatechig\n    HelloMVC\n    war\n    0.0.1-SNAPSHOT\n    HelloMVC Maven Webapp\n    http://maven.apache.org\n\n\n\n        4.2.1.RELEASE\n\n\n\n\n\n\n            org.springframework\n            spring-core\n            ${spring.version}\n\n\n\n            org.springframework\n            spring-webmvc\n            ${spring.version}\n\n\n\n            org.springframework\n            spring-web\n            ${spring.version}\n\n\n\n\n            junit\n            junit\n            3.8.1\n            test\n\n\n\n        HelloMVC\n```\n\nWith this the basic Spring project configuration is complete. Your project structure should look like as the following screenshot.\n\n[![Spring MVC Eclipse Maven Project Structure](/media/articles/162/Spring-MVC-Eclipse-Maven-Project-Structure.png)](http://stacktips.com)\n\nThe following steps will take you through the rest of the steps to create and deploy Spring MVC HelloWorld app.\n\n## 6. Configure Dispatcher Servlet\n\nThe `DispatcherServlet` must be configured as normal in `web.xml` to bootstrap a Spring WebApplicationContext. Edit the default `web.xml` file and add the following.\n\n##### web.xml\n\n```xml\n    Archetype Created Web Application\n\n        contextConfigLocation\n        /WEB-INF/dispat
1cher-servlet.xml\n\n\n\n\n            org.springframework.web.context.ContextLoaderListener\n\n\n\n\n        dispatcher\n\n            org.springframework.web.servlet.DispatcherServlet\n\n        1\n\n\n\n        dispatcher\n        /\n```\n\n## 7. Mapping Requests\n\nCreate an xml file `dispatcher-servlet.xml` under the same directory of `web.xml`.\n\n##### dispatcher-servlet.xml\n\n```xml\n            /WEB-INF/views/\n\n\n            .jsp\n```\n\nIn the above xml file, base-package specifies the package of the controllers. prefix specifies the directory of views, and it is set to be `/WEB-INF/views/`, which means views directory should be created under WEB-INF. suffix specifies the file extension of views. For example, given a view `hello`, the view will be located as `/WEB-INF/views/hello.jsp`.\n\n## 8. Create Controller class\n\nCreate the HelloWorldController under src/main/java/ directory.\n\n##### HelloWorldController.java\n\n```java\npackage com.javatechig.controller;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.servlet.ModelAndView;\n\n@Controller\npublic class HelloWorldController {\n\n    @RequestMapping(\"/hello\")\n    public ModelAndView welcomeMessage(\n            @RequestParam(value = \"name\", required = false) String name) {\n        // Name of your jsp file as parameter\n        ModelAndView view = new ModelAndView(\"hello\");\n        view.addObject(\"name\", name);\n        return view;\n    }\n}\n```\n\nIn the code above, @RequestMapping annotation maps web requests onto specific handler classes and/or handler methods, in this case, welcomeMessage(). It provides a consistent style between Servlet environments, with the semantics adapting to the concrete environment.\n\nRequestParam indicates that a method parameter should be bound to a web request parameter. In this case, we also make it not required and give it a default value. The ModelAndView(“hello”) determines that hello is the target view.\n\n## 9. Working with Views\n\nEdit the default index.jsp and add the following code snippets.\n\n##### index.jsp\n\n```html\n    Hello World\n    Click here...\n```\n\nAdd a JSP files `hello.jsp` file under `/WEB-INF/views/` directory.\n\n##### hello.jsp\n\n```html\n\u003c%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\"\n    pageEncoding=\"ISO-8859-1\"%\u003e\n\nSpring 4 MVC\n\u003c%@ page isELIgnored=\"false\"%\u003e\n\n    Hello, ${name}. Welcome to Spring MVC!\n```\n\nNow we are done with our first HelloWorld example. To deploy it on Tomcat application server, Right click on the project -\u003e select **Run as**. Choose **Tomcat server**, select **Next** and **Finish**. It will deploy the project and to see the output visit http://localhost:8080/HelloMVC on your browser. you will see the following output on your browser.\n\n[![Spring MVC HelloWorld usign Eclipse Maven2](/media/articles/162/Spring-MVC-HelloWorld-usign-Eclipse-Maven2.png)](http://stacktips.com)\n\n[![Spring MVC HelloWorld usign Eclipse Maven](/media/articles/162/Spring-MVC-HelloWorld-usign-Eclipse-Maven.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"bc:T11a7,"])</script>
1<script>self.__next_f.push([1,"\nSpring is a **model-view-controller** (MVC) framework for Java web application. Spring is build on the powerful Spring IoC container and makes extensive use of the container features to simplify the project configuration.\n\n## Model View Controller\n\nThe Model-view-controller (MVC) is a common design pattern used to decouple business logic from UIs. Models are responsible for encapsulating application data for views. Views should only be responsible to present data, without any business logic.\n\nControllers are responsible for receiving requests from users and invoking back-end services for business processing. After processing, back-end services may return some data for views to present.\n\nControllers collect this data and prepare models for views to present. The core idea of the MVC pattern is to separate business logic from UIs to allow them to change independently without affecting each other.\n\nIn a Spring MVC application, models usually consist of domain objects that are processed by the service layer and persisted by the persistence layer. Views are usually JSP templates written with Java Standard Tag Library (JSTL).\n\n## Why use Spring MVC?\n\nFollowing are some of the distinct advantages of Spring MVC architecture.\n\n-   Spring is capable of convention over configuration. For most purposes you only have to define one Servlet in `web.xml`\n-   Similar to Ruby on Rails or other popular web frameworks that work with dynamic languages\n-   Normal business objects can be used to back to front end view forms\n-   No need to duplicate objects just to implement an MVC’s command object interface\n-   Can by used to map .json, .xml, .atom, etc to the same business logic code in one controller and simply output the type of data requested\n-   Enforces good software engineering principles\n\n## How it works?\n\nThe central component of Spring MVC is a Spring controller. A controller is the only servlet you need to configure in a Java web deployment descriptor `web.xml` file.\n\nA Spring MVC controller is otherwise called as front controller generally referred to a single servlet called Dispatcher Servlet. The front controller manages the entire request handling process and every web request must go through it.\n\nWhen a web request is sent to a Spring MVC application, a controller first receives the request. Then it organizes the different components configured in Spring’s web application context or annotations present in the controller itself, all needed to handle the request.\n\nThe following images depicts the Spring MVC architecture and flow of request handling in Spring MVC.\n\n[![Introduction to Spring MVC and Dispatcher Servlet](/media/uploads/articles/163/Introduction-to-Spring-MVC-and-Dispatcher-Servlet-620x398.png)](http://stacktips.com)\n\n## Role of a Dispatcher Servlet\n\n-   Dispatcher Servlet is used to handle all incoming requests and route them through Spring\n-   Uses customizable logic to determine which controllers should handle which incoming requests\n-   Forwards all responses to through view handlers to determine the correct views to route responses to\n-   Exposes all beans defined in Spring to controllers for dependency injection\n\nA controller class in Spring 4.0 should be marked with the `@Controller` annotation. A Spring controller class need shouldn’t extend framework-specific base class or implement a framework-specific interface.\n\nA Controller class defines a specific handler method to handle each request. When a Controller class receives a request, it looks for the appropriate handler mapping methods. The mapping is defined using the `@RequestMapping` annotation.\n\nFor example in the following code syntax, the `showMessage()` handler will handle the request comes form `/hello` endpoint.\n\n```java\n@RequestMapping(\"/hello\")\npublic ModelAndView showMessage(\n        @RequestParam(value = \"name\", required = false, defaultValue = \"World\") String name) {\n\n    ModelAndView modelView = new ModelAndView(\"helloworld\");\n    modelView.addObject(\"message\", \"Welcome to Spring MVC\");\n    modelView.addObject(\"name\", name);\n    return modelView;\n}\n```\n\nWhen controller class picks the appropriate handler method, it then invokes the handler method’s backend logic with the request. After a handler method has finish processing the request, it returns the instance of ModelAndView class. The ModelAndView instance represents a view.\n\nIn the course of this tutorial, we have explained the basic flow of how Spring MVC works and the role of Dispatcher Servlet.\n"])</script>
1<script>self.__next_f.push([1,"bd:Tbf9,"])</script>
1<script>self.__next_f.push([1,"\nAndroid `RenderScript` framework API can be used for performing computationally intensive tasks at high performance. RenderScript was primarily developed to use with data-parallel computation, although serial computationally intensive workloads can benefit as well. The RenderScript runtime will parallelize work across all processors available on a device, such as multi-core CPUs, GPUs, or DSPs, allowing you to focus on expressing algorithms rather than scheduling work or load balancing.\n\nRenderScript is especially useful for applications performing image processing, computational photography, or computer vision. There are two ways we can access the Android RenderScript framework APIs:\n\n-   Directly using `android.renderscript` API classes. These classes are available from Android 3.0 (API level 11) and higher.\n-   Alternatively, you can use `android.support.v8.renderscript` support package classes. The support library classes are available for devices running Android 2.2 (API level 8) and higher.\n\n## How to use RenderScript\n\nIn order to use the Support Library RenderScript APIs, you must have Android SDK Tools revision 22.2 or higher and SDK Build-tools revision 18.1.0 or higher.\n\nAfter you have the above two minimum development tools, you need to update the settings for the Android build process to include the RenderScript APIs. In Android Studio project add the following configurations to project `build.gradle` file.\n\n```java\ndefaultConfig {\n    applicationId \"com.javatechig\"\n    minSdkVersion 14\n    targetSdkVersion 23\n    versionCode 1\n    versionName \"1.0\"\n\n    // Add the following two lines\n    renderscriptTargetApi 18\n    renderscriptSupportModeEnabled true\n}\n```\n\nThe following code snippets can be used create a bitmap blur effect in Android using RenderScript API.\n\n```java\n//Set the radius of the Blur. Supported range 0 \u003c radius \u003c= 25\nprivate static final float BLUR_RADIUS = 25f;\n\npublic Bitmap blur(Bitmap image) {\n    if (null == image) return null;\n\n    Bitmap outputBitmap = Bitmap.createBitmap(image);\n    final RenderScript renderScript = RenderScript.create(this);\n    Allocation tmpIn = Allocation.createFromBitmap(renderScript, image);\n    Allocation tmpOut = Allocation.createFromBitmap(renderScript, outputBitmap);\n\n    //Intrinsic Gausian blur filter\n    ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));\n    theIntrinsic.setRadius(BLUR_RADIUS);\n    theIntrinsic.setInput(tmpIn);\n    theIntrinsic.forEach(tmpOut);\n    tmpOut.copyTo(outputBitmap);\n    return outputBitmap;\n}\n```\n\nYou can use the above code snippet to blur an ImageView as follows.\n\n```java\nImageView imageView = (ImageView) findViewById(R.id.imageView);\nBitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.nature);\nBitmap blurredBitmap = blur(bitmap);\nimageView.setImageBitmap(blurredBitmap);\n```\n\n#### Result:\n\n[![Bitmap Blur Effect In Android Using RenderScript](/media/articles/164/Bitmap-Blur-Effect-In-Android-Using-RenderScript-620x930.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"be:T1749,"])</script>
1<script>self.__next_f.push([1,"\nThe **CustomCalendarView** is an open source library that provides ability to create a calendar view in Android. It displays the days of a month in a grid layout and allows navigating between months and is highly customizable.\n\n## Custom Calendar View Features\n\nCurrently it allows the following features:\n\n-   Next and previous month navigation\n-   Allow various customization including background color for day, week and title\n-   Set custom typeface using setCustomTypeFace() method.\n-   Show hide next previous month overflow days\n-   Set custom day options for start day of week. By default it is set to `Calendar.SUNDAY`\n-   Unlimited customizations for day of the month using custom Decorators.\n-   Allow you to handle event when user changes month and day selection.\n\n[![Custom Calendar View Android](/media/articles/168/Custom-Calendar-View-Android.png)](http://stacktips.com)\n\n## Library Compatibility\n\nThis library is compatible from API 14.\n\n## Add CustomCalendarView Library\n\nTo use the **CustomCalendarView** in your application, you first need to add the library to your application. You can do this by either from Gradle, Maven or by directly downloading the source code form [GitHub](https://github.com/npanigrahy/Custom-Calendar-View).\n\n#### Gradle\n\n**Step 1.** Add the JitPack repository to your build file\n\nStep-1 Add it in your build.gradle at the end of repositories:\n\n```groovy\nrepositories {\n    maven { url \"https://jitpack.io\" }\n}\n```\n\nStep-2 Add the dependency in the form\n\n```groovy\ndependencies {\n    compile 'com.github.npanigrahy:Custom-Calendar-View:v1.1'\n}\n```\n\n#### Maven\n\n```xml\n\u003crepository\u003e\n     \u003cid\u003ejitpack.io\u003c/id\u003e\n     \u003curl\u003ehttps://jitpack.io\u003c/url\u003e\n\u003c/repository\u003e\n```\n\nStep 2. Add the dependency in the form\n\n```xml\n\u003cdependency\u003e\n     \u003cgroupId\u003ecom.github.npanigrahy\u003c/groupId\u003e\n     \u003cartifactId\u003eCustom-Calendar-View\u003c/artifactId\u003e\n     \u003cversion\u003ev1.1\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n#### Sbt\n\nStep-1 Add it in your build.sbt at the end of resolvers:\n\n```text\nresolvers += \"jitpack\" at \"https://jitpack.io\"\n```\n\nStep-2 Add the dependency in the form\n\n```text\nlibraryDependencies += \"com.github.npanigrahy\" % \"Custom-Calendar-View\" % \"v1.1\"\n```\n\n## Using CustomCalendarView Library\n\nThe GitHub project source includes a sample application, that is used for demonstrating the various features currently supported by this library. Once the library is added to your project, you can include the CustomCalendarView into your activity/fragment layout using the following code snippets.\n\n```xml\n\u003ccom.stacktips.view.CustomCalendarView\n    android:id=\"@+id/calendar_view\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:background=\"@color/off_white\"\u003e\n\u003c/com.stacktips.view.CustomCalendarView\u003e\n```\n\nThe above code snippet will show the simple Calendar View with default design. Now, you can use the following attributes, to customize the appearance of calendar.\n\n```xml\n\u003ccom.stacktips.view.CustomCalendarView\n    android:id=\"@+id/calendar_view\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:background=\"@color/off_white\"\n    app:calendarBackgroun
1dColor=\"@color/off_white\"\n    app:calendarTitleTextColor=\"@color/black\"\n    app:currentDayOfMonthColor=\"@color/blue\"\n    app:dayOfMonthTextColor=\"@color/black\"\n    app:dayOfWeekTextColor=\"@color/black\"\n    app:disabledDayBackgroundColor=\"@color/off_white\"\n    app:disabledDayTextColor=\"@color/grey\"\n    app:selectedDayBackgroundColor=\"@color/blue\"\n    app:titleLayoutBackgroundColor=\"@color/white\"\n    app:weekLayoutBackgroundColor=\"@color/white\"\u003e\n\u003c/com.stacktips.view.CustomCalendarView\u003e\n```\n\nLet us now, initialize the calendar view to control the various other appearance and behavior of calendar using the following methods.\n\n```java\n//Initialize CustomCalendarView from layout\ncalendarView = (CustomCalendarView) findViewById(R.id.calendar_view);\n\n//Initialize calendar with date\nCalendar currentCalendar = Calendar.getInstance(Locale.getDefault());\n\n//Show Monday as first date of week\ncalendarView.setFirstDayOfWeek(Calendar.MONDAY);\n\n//Show/hide overflow days of a month\ncalendarView.setShowOverflowDate(false);\n\n//call refreshCalendar to update calendar the view\ncalendarView.refreshCalendar(currentCalendar);\n\n//Handling custom calendar events\ncalendarView.setCalendarListener(new CalendarListener() {\n    @Override\n    public void onDateSelected(Date date) {\n        SimpleDateFormat df = new SimpleDateFormat(\"dd-MM-yyyy\");\n        Toast.makeText(MainActivity.this, df.format(date), Toast.LENGTH_SHORT).show();\n    }\n\n    @Override\n    public void onMonthChanged(Date date) {\n        SimpleDateFormat df = new SimpleDateFormat(\"MM-yyyy\");\n        Toast.makeText(MainActivity.this, df.format(date), Toast.LENGTH_SHORT).show();\n    }\n});\n```\n\n## Using Custom TypeFace\n\n```java\n//Setting custom font\nfinal Typeface typeface = Typeface.createFromAsset(getAssets(), \"fonts/Arch_Rival_Bold.ttf\");\nif (null != typeface) {\n    calendarView.setCustomTypeface(typeface);\n    calendarView.refreshCalendar(currentCalendar);\n}\n```\n\n[![Custom Calendar View Library in Android Custom Font](/media/articles/168/Custom-Calendar-View-Library-in-Android-Custom-Font-300x507.png)](http://stacktips.com)\n\n## Using Day Decorators\n\n**Example2:** How to Disable Past Dates in CustomCalendarView [using Decorators](/articles/disable-past-dates-in-custom-calendar-view-android).\n\n```java\n//adding calendar day decorators\nList decorators = new ArrayList\u003c\u003e();\ndecorators.add(new ColorDecorator());\ncalendarView.setDecorators(decorators);\ncalendarView.refreshCalendar(currentCalendar);\n```\n\n[![Custom Calendar View Library in Android Decorator](/media/articles/168/Custom-Calendar-View-Library-in-Android-Decorator-300x507.png)](http://stacktips.com)\n\n_If you enjoy this library, don’t forget to like our [Facebook](http://facebook.com/stacktips) page or follow us on twitter [@Stacktips](http://twitter.com/stacktips)._\n"])</script>
1<script>self.__next_f.push([1,"bf:T1a46,"])</script>
1<script>self.__next_f.push([1,"\nMost of the form-based applications often need to customize the default behavior of the Android soft keyboard. Often it is required to control the type of keyboard you want to present the user for data input, or customize the appearance of keyboard **“Enter”** key action.\n\nOver the course of this tutorial, we will explain the various code hacks used to control the appearance and behavior of Android soft keyboard. This tutorial covers the following topics:\n\nLet us first began with controlling the type keyboard to display while editing the form data.\n\n## Set TextView input type\n\nThere are different types of keyboard designed for user convenience. For example, if for entering a number you must display the numerical keyboard. This can be controlled by `InputType` property of `TextView`. The InputType controls aspects such as the type of data allowed to enter in a text field. Generally, you can select a single value, though some can be combined together as indicated.\n\nIt is important to note that, setting `InputType` property attribute to anything besides `none` implies that the text is editable.\n\nSome of the most used input type constants includes, `none`, `text`, `textCapCharacters`, `textCapWords`, `textCapSentences`, `textAutoCorrect`, `textAutoComplete`, `textMultiLine`, `textImeMultiLine`, `textUri`, `textEmailAddress`, `textPassword`, `textWebEditText`, `textPhonetic`, `textWebEmailAddress`, `number`, `phone`, `datetime`, `date`, and `time`.\n\nYou can set the inputType property in the layout declaration as follows:\n\n```xml\n\u003cEditText\n   android:id=\"@+id/text1\"\n   android:layout_width=\"fill_parent\"\n   android:layout_height=\"wrap_content\"\n   android:imeOptions=\"actionSearch\"\n   android:singleLine=\"true\"\n   android:inputType=\"number\" /\u003e\n```\n\n## Hide the soft keyboard\n\nThe following code snippet will help you to hide or dismiss the soft keyboard from the screen and take the input focus out form the editable view.\n\n```java\nInputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);\nimm.hideSoftInputFromWindow(view.getWindowToken(), 0);\n```\n\nThe `hideSoftInputFromWindow()` takes an `IBinder` window token as a parameter. This can be retrieved from any View object currently attached to the window via `View.getWindowToken()`.\n\n## Customize the input method\n\nNow that we understand the different keyboard types based on the TextView `inputType` property let us customize the appearance of keyboard **“Enter”** action.\n\nWhen the keyboard is visible on screen, the text on the Enter key typically indicates its action based on the order of focusable items in the view. While unspecified, the keyboard by default display a **“Next”** action if there are more focusable views to move to, otherwise it shows **“Done”** action if the last item is currently focused on. In the case of a multiline field, this action is a line return.\n\nThis can be customized using `android:imeOptions` value in the TextView XML declaration. The `android:imeOptions` attribute access the following possible values:\n\n-   **actionUnspecified:** This property displays action of the device’s choice Action event is IME\\_NULL. This is the default keyboard action.\n-   **actionGo:** This displays Go as the Enter key. Action event is **IME\\_ACTION\\_GO**\n-   **actionSearch:** Displays a search icon as the Enter key Action event is **IME\\_ACTION\\_SEARCH**\n-   **actionSend:** Displays Send as the Enter key. Action event is **IME\\_ACTION\\_SEND**\n-   **actionNext:** Displays Next as the Enter key. Action event is **IME\\_ACTION\\_NEXT**\n-   **actionDone:** Displays Done as the Enter key. Action event is **IME\\_ACTION\\_DONE**\n\nAll the above set of action event constants are defined in `EditorInfo` class.\n\nLet us look at the following example layout with two editable text fields. The first EditText will display the search icon for the Enter key, and the second will display Go. The resulting output may vary depending on current keyboard installed on the device.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cEditText\n        android:id=\"@+id/text1\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:imeOptions=\"actionSearch\"\n        android:singleLine=\"true\" /\u003e\n\n    \u003cEditText\n        android:id=\"@+id/text2\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:imeOptions=\"actionGo\"\n        android:singleLine=\"true\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\nNote that, the custom editor options apply only to the appearance of soft input methods. Changing this value will not affect the events that get generated 
1when the user presses on a physical hardware keyboard button.\n\n## Adding Custom Action\n\nCustomizing what happens when the user presses the **Enter** key can be just as important as adjusting its appearance. For overriding the default behavior we need to attach an `OnEditorActionListener` to `EditText` instance.\n\nThe following code snippet shows how to create a custom action for EditTexts.\n\n```java\npublic class MainActivity extends Activity implements OnEditorActionListener {\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        //Add the listener to the views\n        EditText editText1 = (EditText) findViewById(R.id.text1);\n        editText1.setOnEditorActionListener(this);\n\n        EditText editText2 = (EditText) findViewById(R.id.text2);\n        editText2.setOnEditorActionListener(this);\n    }\n\n    @Override\n    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n        if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n            //Handle search key click\n            return true;\n        }\n        if (actionId == EditorInfo.IME_ACTION_GO) {\n            //Handle go key click\n            return true;\n        }\n        return false;\n    }\n}\n```\n\nThe boolean return value of `onEditorAction()` tells the system whether you are consuming the event or it should be passed on to the next possible responder if any. It is important for you to return true when you handle the event yourself, so no other processing occurs. You can return false when you are not handling the event so your application does not steal key events from the rest of the system.  \nWelcome to EditPad.org – your online plain text editor. Enter or paste your text here. To download and save it, click on the button below.  \n2\n\nmore » Edit Pad – Free Online Text EditorEdit Pad © 2018\n"])</script>
1<script>self.__next_f.push([1,"c0:T1fb2,"])</script>
1<script>self.__next_f.push([1,"\n## Introduction to ViewGroup\n\nA `ViewGroup` in Android a special view that can contain other Views. A ViewGroup can contain one or multiple child. All other standard layout managers such as [LinearLayout](http://stacktips.com/android/android-linearlayout-example), [FrameLayout](http://stacktips.com/android/android-framelayout-example), [RelativeLayout](http://stacktips.com/android/android-relativelayout-example) are specialized sub classes of ViewGroup class that layout their child in specific format. For example, LinearLayout layout its child one adjacent to other either vertically or horizontally.\n\nSometimes, due to the specific nature of the requirement, the standard layout managers are not enough. You need to extend the ViewGroup class to create your own custom layout manager.\n\nThis post will help you to deal with creating a custom Layout manager class TagLayout that will be used to display the list of tags as shown in the following screenshot.\n\n[![Create Custom Layout in Android by Extending ViewGroup Class](/media/articles/174/Create-Custom-Layout-in-Android-by-Extending-ViewGroup-Class-300x533.png)](http://stacktips.com)\n\nYou have to perform the following steps while creating a custom Layout manager.\n\n1.  Extend your class from `ViewGroup` class.\n2.  You must override the `onLayout()` method. This method is used to place child views.\n3.  Override `onMeasure()` method. The onMeasure() method will be used to for parent to determine the size of the view group based on calculating the child view size.\n4.  The onMeasure() and onLayout() method, will contain the logic to organize the child views with in parent layout.\n\nYou can measure each of the child view height and width by calling `getMeasuredWidth()` and `getMeasuredHeight()` methods.\n\n## Creating Custom ViewGroup\n\n```java\npublic class TagLayout extends ViewGroup {\n    int deviceWidth;\n\n    public TagLayout(Context context) {\n        this(context, null, 0);\n    }\n\n    public TagLayout(Context context, AttributeSet attrs) {\n        this(context, attrs, 0);\n    }\n\n    public TagLayout(Context context, AttributeSet attrs, int defStyleAttr) {\n        super(context, attrs, defStyleAttr);\n        init(context);\n    }\n\n    private void init(Context context) {\n        final Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();\n        Point deviceDisplay = new Point();\n        display.getSize(deviceDisplay);\n        deviceWidth = deviceDisplay.x;\n    }\n\n    @Override\n    protected void onLayout(boolean changed, int l, int t, int r, int b) {\n        final int count = getChildCount();\n        int curWidth, curHeight, curLeft, curTop, maxHeight;\n\n        //get the available size of child view\n        final int childLeft = this.getPaddingLeft();\n        final int childTop = this.getPaddingTop();\n        final int childRight = this.getMeasuredWidth() - this.getPaddingRight();\n        final int childBottom = this.getMeasuredHeight() - this.getPaddingBottom();\n        final int childWidth = childRight - childLeft;\n        final int childHeight = childBottom - childTop;\n\n        maxHeight = 0;\n        curLeft = childLeft;\n        curTop = childTop;\n\n        for (int i = 0; i \u003c count; i++) {\n            View child = getChildAt(i);\n\n            if (child.getVisibility() == GONE)\n                return;\n\n            //Get the maximum size of the child\n            child.measure(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.AT_MOST));\n            curWidth = child.getMeasuredWidth();\n            curHeight = child.getMeasuredHeight();\n            //wrap is reach to the end\n            if (curLeft + curWidth \u003e= childRight) {\n                curLeft = childLeft;\n                curTop += maxHeight;\n                maxHeight = 0;\n            }\n            //do the layout\n            child.layout(curLeft, curTop, curLeft + curWidth, curTop + curHeight);\n            //store the max height\n            if (maxHeight \u003c curHeight)\n                maxHeight = curHeight;\n            curLeft += curWidth;\n        }\n    }\n\n    @Override\n    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n        int count = getChildCount();\n        // Measurement will ultimately be computing these values.\
1n        int maxHeight = 0;\n        int maxWidth = 0;\n        int childState = 0;\n        int mLeftWidth = 0;\n        int rowCount = 0;\n\n        // Iterate through all children, measuring them and computing our dimensions\n        // from their size.\n        for (int i = 0; i \u003c count; i++) {\n            final View child = getChildAt(i);\n\n            if (child.getVisibility() == GONE)\n                continue;\n\n            // Measure the child.\n            measureChild(child, widthMeasureSpec, heightMeasureSpec);\n            maxWidth += Math.max(maxWidth, child.getMeasuredWidth());\n            mLeftWidth += child.getMeasuredWidth();\n\n            if ((mLeftWidth / deviceWidth) \u003e rowCount) {\n                maxHeight += child.getMeasuredHeight();\n                rowCount++;\n            } else {\n                maxHeight = Math.max(maxHeight, child.getMeasuredHeight());\n            }\n            childState = combineMeasuredStates(childState, child.getMeasuredState());\n        }\n\n        // Check against our minimum height and width\n        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());\n        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());\n\n        // Report our final dimensions.\n        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),\n                resolveSizeAndState(maxHeight, heightMeasureSpec, childState \u003c\u003c MEASURED_HEIGHT_STATE_SHIFT));\n    }\n}\n```\n\n## Add Custom ViewGroup to Activity Layout\n\nNow that we are ready with the view group, let us add it to the activity layout.\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\u003e\n\n    \u003ccom.javatechig.taglayout.TagLayout\n        android:id=\"@+id/tagLayout\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:background=\"#ffff00\"/\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n## Define Child View Layout\n\nYou may have notice from the layout above, we will create custom layout for view group child. In this case the tag item.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"wrap_content\"\n    android:layout_height=\"wrap_content\"\u003e\n\n    \u003cTextView\n        android:id=\"@+id/tagTextView\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"5dp\"\n        android:background=\"#a000\"\n        android:padding=\"10dp\"\n        android:textColor=\"#fff\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n## Adding Child View to Custom ViewGroup\n\nHere is what it goes in my activity. For the sake of simplicity, I am inflating 20 child views from inside for loop. You may have some complex logic to get the data from some other source.\n\n```java\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        TagLayout tagLayout = (TagLayout) findViewById(R.id.tagLayout);\n        LayoutInflater layoutInflater = getLayoutInflater();\n        String tag;\n        for (int i = 0; i \u003c= 20; i++) {\n            tag = \"#tag\" + i;\n            View tagView = layoutInflater.inflate(R.layout.tag_layout, null, false);\n\n            TextView tagTextView = (TextView) tagView.findViewById(R.id.tagTextView);\n            tagTextView.setText(tag);\n            tagLayout.addView(tagView);\n        }\n    }\n}\n```\n\nhttps://github.com/javatechig/TagLayout-ViewGroup\n"])</script>
1<script>self.__next_f.push([1,"c1:Ta07,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we will see how to monitor the text changes in Android TextView or EditText.\n\nSome form based applications needs to continuously monitor for the text changes to perform the front end form validations. This can be achieved by implementing the `android.text.TextWatcher` interface. The TextWatcher interface provides the following three callback methods, that are called while the textview is being updated.\n\n```java\npublic void beforeTextChanged(CharSequence s, int start, int count, int after);\npublic void onTextChanged(CharSequence s, int start, int before, int count);\npublic void afterTextChanged(Editable s);\n```\n\nThe `beforeTextChanged()` and `onTextChanged()` methods are provided mainly as notifications, as shouldn’t make changes to the CharSequence in either of these methods. If you are attempting to intercept the text entered into the view, changes may be made when `afterTextChanged()` is called.\n\nFirst, you need to register a TextWatcher instance with a TextView, call the `textView.addTextChangedListener()` method. Notice from the syntax that more than one TextWatcher can be registered with a TextView. Now that we understand the methods to be used, let us examine the sample for the usage.\n\n##### Count Characters on TextView Changes\n\nA simple use of TextWatcher is to create a live character counter that follows an EditText as the user types or deletes information.\n\n```java\npublic class MyActivity extends Activity implements TextWatcher {\n    private EditText text;\n    private int textCount;\n    private static final String TAG = \"MyActivity\";\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        //Create an EditText widget and add the watcher\n        editText = new EditText(this);\n        editText.addTextChangedListener(this);\n        setContentView(editText);\n    }\n\n    /* TextWatcher Implementation Methods */\n    @Override\n    public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n    }\n\n    @Override\n    public void onTextChanged(CharSequence s, int start, int before, int count) {\n        textCount = editText.getText().length();\n        setTitle(String.valueOf(textCount));\n        Log.e(TAG, String.valueOf(textCount))\n    }\n\n    @Override\n    public void afterTextChanged(Editable s) {\n\n    }\n}\n```\n\nBecause our needs do not include modifying the text being inserted, we can read the count from `onTextChanged()`, which happens as soon as the text change occurs. The other methods are unused and left empty.\n"])</script>
1<script>self.__next_f.push([1,"c2:T982,"])</script>
1<script>self.__next_f.push([1,"\nA Monkey is a tool you run on your device to generate a random system level user events. It generates the specified number of events without any user interaction. This is generally helpful for performing the stress test. This tool generates the random events from a set of commands and collects the crashes or memory reports.\n\nNote that this tool is not used for automation testing. This only helps to find the crashes that may not appear during regular use of the application.\n\nThis tool uses an Android Device Bridge ADB toolkit. To run this command you need to provide the application package name and a total number of random events that you want to generate. The following command shows how to start monkey tool.\n\n```bash\n$ adb shell monkey -p com.javatechig.myapp 5000\n```\n\nWhen you run this test, you can watch your device or emulator. You will notice random events on UI elements are being generated. When the application crashes, it will stop the exerciser and prints the report on the terminal window. The following screenshot depicts a crash report while testing my application.  \n[![Performing Stress Test in Android Using  Monkey Application Exerciser](/media/articles/181/Performing-Stress-Test-in-Android-Using-Monkey-Application-Exerciser.png)](http://stacktips.com)\n\nThere are a variety of ways to control the behavior of Monkey tool by passing different arguments. Let us go through some of the important ones.\n\nYou can see a complete list of all options by typing:\n\n```bash\n$ adb shell monkey --help\n```\n\nYou must have noticed in the previous command, when the Monkey starts, it always starts the default application of the package specified. However, in some cases, your application may depend on some other third party apps such as device native camera to capture the photo or integrating with Google Maps. For such cases, an event that launches something external will be dropped by default by Monkey tool.\n\nThis behavior can be controlled by providing an additional package -p argument to the Monkey command.\n\n```bash\n$ adb shell monkey -p com.javatechig.myapp -p com.google.map 5000\n```\n\nNow let us run the Monkey tool more intelligently by controlling the type of events that are triggered. For example, if you want to ensure that 30 percent of the events are touch events, you need to specify the –pct-touch argument as follows.\n\n```bash\n$ adb shell monkey --pct-touch 30 -p com.javatechig.myapp 5000\n```\n"])</script>
1<script>self.__next_f.push([1,"c3:T1d5d,"])</script>
1<script>self.__next_f.push([1,"\nDialog is like any other window that pops up in front of current window, used to show some short message, taking user input or to ask user decisions. Unlike `Toast`, a dialog is generally used where user attention is mandate. Android supports several different ways to create a dialog such as `AlertDialog` and `FragmentDialog`. In this example we will cover all the aspect of AlertDialog and DialogFragment.\n\n## 1. Using AlertDialog in Xamarin.Android\n\n`AlertDialog` is the subclass of `Dialog` that can display one, two or three buttons. If you only want to display a String in this dialog box, use the `SetMessage()` method.\n\nThe following code snippet can be used to create a simple AlertDialog with two buttons Delete and Cancel.\n\n```cs\n//set alert for executing the task\nAlertDialog.Builder alert = new AlertDialog.Builder (this);\nalert.SetTitle (\"Confirm delete\");\nalert.SetMessage (\"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\");\nalert.SetPositiveButton (\"Delete\", (senderAlert, args) =\u003e {\n    Toast.MakeText(this ,\"Deleted!\" , ToastLength.Short).Show();\n});\n\nalert.SetNegativeButton (\"Cancel\", (senderAlert, args) =\u003e {\n    Toast.MakeText(this ,\"Cancelled!\" , ToastLength.Short).Show();\n});\n\nDialog dialog = alert.Create();\ndialog.Show();\n```\n\nThe above code snippet will produce the output as shown in the following screenshot.\n\n[![AlertDialog in Xamarin Android](/media/articles/183/AlertDialog-in-Xamarin-Android-300x533.png)](http://stacktips.com)\n\n## 2. Using DialogFragment in Xamarin.Android\n\nSince the release of **Android 3.0 (API level 11)**, fragment can show as a dialog and called as `DialogFragment`. If you’re supporting older android versions, you can make use of fragment-compatibility support library.\n\nTo create a dialog fragment, we will be using DialogFragment class. This class is derived from the Fragment and behaves much like a fragment with all available fragment life cycle methods. Android recemends to use DialogFragment over AlerDialog.\n\nYou need to perfrom the following steps to create a DialogFragment\n\n-   Create a new class that extends from DialogFragment class.\n-   Like regular Fragments, override `OnCreateView()` callback to attach the dialog layout.\n-   Alternatively, you can override `OnCreateDialog()` method and return a Dialog instance. This method is used to port your old AlertDialog code without much of modification.\n\nIn this example, we will see both OnCreateView() and OnCreateDialog() callback.\n\n## 3. Dialog fragment using OnCreateDialog()\n\nThe following code snipept shows how to create dialog by overriding OnCreateDialog() method.\n\n```cs\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Android.App;\nusing Android.Content;\nusing Android.OS;\nusing Android.Runtime;\nusing Android.Util;\nusing Android.Views;\nusing Android.Widget;\n\nnamespace DialogExample\n{\n    public class DialogFragment2 : DialogFragment\n    {\n        public static DialogFragment2 NewInstance(Bundle bundle){\n            DialogFragment2 fragment = new DialogFragment2 ();\n            fragment.Arguments = bundle;\n            return fragment;\n        }\n\n        public override Dialog OnCreateDialog (Bundle savedInstanceState)\n        {\n            AlertDialog.Builder alert = new AlertDialog.Builder (Activity);\n            alert.SetTitle (\"Confirm delete\");\n            alert.SetMessage (\"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\");\n            alert.SetPositiveButton (\"Delete\", (senderAlert, args) =\u003e {\n                Toast.MakeText(Activity ,\"Deleted!\" , ToastLength.Short).Show();\n            });\n\n            alert.SetNegativeButton (\"Cancel\", (senderAlert, args) =\u003e {\n                Toast.MakeText(Activity ,\"Cancelled!\" , ToastLength.Short).Show();\n            });\n\n            return alert.Create();\n        }\n    }\n}\n```\n\n## 4. Dialog fragment using OnCreateView()\n\nDialogFragment is like any other fragment, the same lifecycle rules are applied. Now we have to override onCreateView method to attach the layout to view hierarchy and construct the dialog fragment.\n\nLet us first define the layout for your fragment. In this example, I have used two TextViews and Button. My layout looks as follows:\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:orientation=\"vertical\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:padding=\"10dp\"\u003e\n    \u003cTextView\n        android:text=\"Lorem ipsum\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:id=\"@+id/textView1\" /\u003e\n    \u003cTextView\n        android:text=\"Lorem ipsum dolor sit amet, consectetuer adipiscing elit....\"\n        android:textAppearance=\"?android:attr/textAppearanceSmall\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:id=\"@+id/textView2\"\n        android:layout_marginTop=\"10dp\" /\u003e\n    \u003cButton\n        android:text=\"Close\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:id=\"@+id/CloseButton\"\n        android:layout_marginTop=\"10dp\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\nNow let us inflate the layout from OnCreateView() method. My DialogFragment class looks as follows:\n\n```cs\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Android.App;\nusing Android.Content;\nusing Android.OS;\nusing Android.Runtime;\nusing Android.Util;\nusing Android.Views;\nusing Android.Widget;\n\nnamespace DialogExample\n{\n    public class DialogFragment1 : DialogFragment\n    {\n        public static DialogFragment1 NewInstance(Bundle bundle){\n            DialogFragment1 fragment = new DialogFragment1 ();\n            fragment.Arguments = bundle;\n            return fragment;\n        }\n\n        public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)\n        {\n            // Use this to return your custom view for this Fragment\n            View view =  inflater.Inflate(Resource.Layout.DialogFragment1Layout, container, false);\n            Button button = view.FindViewById\u003cButton\u003e (Resource.Id.
1CloseButton);\n            button.Click += delegate {\n                Dismiss();\n                Toast.MakeText(Activity ,\"Dialog fragment dismissed!\" , ToastLength.Short).Show();\n            };\n\n            return view;\n        }\n    }\n}\n```\n\nThe above code snippet will produce the output as shown in the following screenshot.  \n[![DialogFragment in Xamarin Android](/media/articles/183/DialogFragment-in-Xamarin-Android-300x533.png)](http://stacktips.com)\n\n## 5. Adding DialogFragment\n\nWe are pretty much done!. Add the following code snippet in your Activity to instantiate and display the dialog;\n\n```cs\nFragmentTransaction ft = FragmentManager.BeginTransaction();\n//Remove fragment else it will crash as it is already added to backstack\nFragment prev = FragmentManager.FindFragmentByTag(\"dialog\");\nif (prev != null) {\n    ft.Remove(prev);\n}\n\nft.AddToBackStack(null);\n\n// Create and show the dialog.\nDialogFragment1 newFragment = DialogFragment1.NewInstance(null);\n\n//Add fragment\nnewFragment.Show(ft, \"dialog\");\n```\n\nThe above code snippet will produce the output as shown in the following screenshot.  \n[![AlertDialog in Xamarin Android](/media/articles/183/AlertDialog-in-Xamarin-Android-300x533.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"c4:T1037,"])</script>
1<script>self.__next_f.push([1,"\nThe recent release of Android support library `(v7:21.0.+)` has introduced two new user interface widget: `RecyclerView` and `CardView` that helps in building rich Android apps.\n\nThe `RecyclerView` is more advanced and flexible and efficient version of ListView. RecyclerView ViewGroup is a container for larger data set of views that can be recycled and scrolled very efficiently.\n\nRecyclerView can be used for larger datasets to be rendered on the UI like a list. RecyclerView provides maximum flexibility to design a different kind of views.\n\nClick here to read more about [Android RecyclerView](/articles/android-recyclerview-example) example.\n\nIn the other hand the `CardView` widget, is an extension of existing FrameLayout class. This helps to wrap other UI elements as Google style cards. CardView widgets can have shadows and rounded corners. The following image shows example Google card design used Google Now application.  \n[![Google Now Cards](/media/articles/184/Googe-Now-Cards.jpg)](http://stacktips.com)\n\n### Add CardView Support Library\n\nAndroid SDK doesn’t includes the CardView class, and hence for using CardView in your project you need to add the following dependency in your `build.graddle` file.\n\n```java\ndependencies {\n   compile 'com.android.support:cardview-v7:21.0.+'\n}\n```\n\n### Declare CardView Layout\n\nNow that we have added the build dependencies to project, let us go ahead to declare the CardView layout. In this example, we will add an ImageView and two TextViews as shown in the following screenshot.\n\n```xml\n\u003candroid.support.v7.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:id=\"@+id/card_view\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"380dp\"\n    android:layout_margin=\"8dp\"\u003e\n\n    \u003cRelativeLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\u003e\n\n        \u003cImageView\n            android:id=\"@+id/thumbnail\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"250dp\"\n            android:layout_alignParentTop=\"true\"\n            android:scaleType=\"centerCrop\"\n            android:src=\"@drawable/wallpaper\" /\u003e\n\n        \u003cTextView\n            android:id=\"@+id/title\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_below=\"@+id/thumbnail\"\n            android:maxLines=\"3\"\n            android:padding=\"8dp\"\n            android:text=\"@string/title\"\n            android:textColor=\"#222\"\n            android:textStyle=\"bold\"\n            android:textSize=\"22dp\" /\u003e\n\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_below=\"@+id/title\"\n            android:maxLines=\"3\"\n            android:padding=\"8dp\"\n            android:text=\"@string/description\"\n            android:textColor=\"#666\"\n            android:textSize=\"14dp\" /\u003e\n\n    \u003c/RelativeLayout\u003e\n\u003c/android.support.v7.widget.CardView\u003e\n```\n\nThe output of the above code is as follows  \n[![Android CardVeiw Example](/media/articles/184/Android-CardVeiw-Example-e1435760917628-300x329.png)](http://stacktips.com)\n\n### Customize CardView Appearance\n\nThe CardView layout declaration is pretty straight forward. CardView widget allows you to control the background color, shadow, corner radius etc.\n\nFor using the custom attributes in XML, you need to add the following namespace declaration to your layout parent.\n\n```xml\n\u003candroid.support.v7.widget.CardView\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    xmlns:cardView=\"http://schemas.android.com/apk/res-auto\"\n    ... \u003e\n\n        ...\n        ....\n\u003c/android.support.v7.widget.CardView\u003e\n```\n\nNow let us use the following `CardView` properties to customize the appearance of the CardView\n\n-   To set the corner radius in your layouts, use the `cardView:cardCornerRadius` attribute. To set the corner radius in your code, use the `cardView.setRadius` method.\n-   To set the background color of a card, use the `cardView:cardBackgroun
1dColor` attribute.\n"])</script>
1<script>self.__next_f.push([1,"c5:T1d36,"])</script>
1<script>self.__next_f.push([1,"\nIn this example, we will see how to create custom window animation that makes sense to the user. We will extend our previous [GridView example,](/article/download-and-display-image-in-android-gridview) to create custom bitmap scale animation when user clicks on a thumbnail in GridView.\n\nLet us now take a look at the following demo. Notice that when we click on the thumbnail on GridView, it opens the sub-activity that displays an `ImageView` and `TextView`. The thumbnail image gets zoomed up and scales to full view in details activity. When the user clicks the back button to return to `GridView`, it again scales down to the original position.\n\n{{\u003c youtube smIWHeXZmFU \u003e}}\n\nTo achieve this kind of animation, we need to follow the following steps\n\n-   Override the default window animation with our own custom animation for both enter and exit transitions.\n-   When user clicks on a GridView item, capture the details of thumbnail such as top and left distance, width, height, title and the url of the image to display. Package all the details and pass the extra information to `DetailsActivity`.\n-   Launch activity transparently so that we see the thumbnail gets zoomed. We can control the background alpha animation to set the image background.\n-   Write your own enter and exit transition on DetailsActivity.\n\n## 1. Capture and send the thumbnail details\n\nLet us implement mGridView.setOnItemClickListener to handle click event on GridView. When user clicks on any grid items, get the image thumbnail at that position. Extract the information such as position, width and height and pass to DetailsActivity `intent` bundle.\n\n```java\nmGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n    public void onItemClick(AdapterView\u003c?\u003e parent, View v, int position, long id) {\n        GridItem item = (GridItem) parent.getItemAtPosition(position);\n        ImageView imageView = (ImageView) v.findViewById(R.id.grid_item_image);\n\n        Intent intent = new Intent(GridViewActivity.this, DetailsActivity.class);\n        int[] screenLocation = new int[2];\n        imageView.getLocationOnScreen(screenLocation);\n\n        //Pass the image title and url to DetailsActivity\n        intent.putExtra(\"left\", screenLocation[0]).\n                putExtra(\"top\", screenLocation[1]).\n                putExtra(\"width\", imageView.getWidth()).\n                putExtra(\"height\", imageView.getHeight()).\n                putExtra(\"title\", item.getTitle()).\n                putExtra(\"image\", item.getImage());\n\n        startActivity(intent);\n    }\n});\n```\n\n## 2. Read bundle data passed form intent\n\nThis is straight forward. Just read all the bundle data passed form GridView activity.\n\n```java\n//retrieves the thumbnail data\nBundle bundle = getIntent().getExtras();\nthumbnailTop = bundle.getInt(\"top\");\nthumbnailLeft = bundle.getInt(\"left\");\nthumbnailWidth = bundle.getInt(\"width\");\nthumbnailHeight = bundle.getInt(\"height\");\n\nString title = bundle.getString(\"title\");\nString image = bundle.getString(\"image\");\n```\n\n## 3. Make DetailsActivity window transparent\n\nMake the DetailsActivity background as transparent by adding the `android:windowBackground` color as transparent. This can be done using custom themes to your activity.\n\n```xml\n\u003cstyle name=\"Transparent\" parent=\"AppTheme\"\u003e\n        \u003citem name=\"android:windowNoTitle\"\u003etrue\u003c/item\u003e\n        \u003citem name=\"android:windowIsTranslucent\"\u003etrue\u003c/item\u003e\n        \u003citem name=\"android:windowBackground\"\u003e@android:color/transparent\u003c/item\u003e\n\u003c/style\u003e\n```\n\nNow, set the above theme to your activity in AndroidManifest.xml file.\n\n```xml\n\u003cactivity android:name=\".DetailsActivity\"\n            android:theme=\"@style/Transparent\" /\u003e\n```\n\n## 4. Set color drawable to main background\n\nWe have made the activity default background as transparent. Now let us set the main parent view background as follows.\n\n```java\n//Set the background color to black\n frameLayout = (FrameLayout) findViewById(R.id.main_background);\ncolorDrawable = new ColorDrawable(Color.BLACK);
1\nframeLayout.setBackground(colorDrawable);\n```\n\n## 5. Implement .addOnPreDrawListener\n\nRegister `ViewTreeObserver.addOnPreDrawListener` callback in DetailsActivity. This callback will be invoked when the view tree is about to be drawn. This is the best place to run our window enter animation.\n\n```java\n// Only run the animation if we're coming from the parent activity, not if\n// we're recreated automatically by the window manager (e.g., device rotation)\nif (savedInstanceState == null) {\n    ViewTreeObserver observer = imageView.getViewTreeObserver();\n    observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {\n\n        @Override\n        public boolean onPreDraw() {\n            imageView.getViewTreeObserver().removeOnPreDrawListener(this);\n\n            int[] screenLocation = new int[2];\n            imageView.getLocationOnScreen(screenLocation);\n            mLeftDelta = thumbnailLeft - screenLocation[0];\n            mTopDelta = thumbnailTop - screenLocation[1];\n\n            // Scale factors to make the large version the same size as the thumbnail\n            mWidthScale = (float) thumbnailWidth / imageView.getWidth();\n            mHeightScale = (float) thumbnailHeight / imageView.getHeight();\n\n            enterAnimation();\n            return true;\n        }\n    });\n}\n```\n\n## 6. Create custom enter and exit animation\n\nThe enter animation scales the picture in from its previous thumbnail size/location. In parallel, the background of the activity is fading in.\n\n```java\npublic void enterAnimation() {\n    imageView.setPivotX(0);\n    imageView.setPivotY(0);\n    imageView.setScaleX(mWidthScale);\n    imageView.setScaleY(mHeightScale);\n    imageView.setTranslationX(mLeftDelta);\n    imageView.setTranslationY(mTopDelta);\n\n    // interpolator where the rate of change starts out quickly and then decelerates.\n    TimeInterpolator sDecelerator = new DecelerateInterpolator();\n\n    // Animate scale and translation to go from thumbnail to full size\n    imageView.animate().setDuration(ANIM_DURATION).scaleX(1).scaleY(1).\n            translationX(0).translationY(0).setInterpolator(sDecelerator);\n\n    // Fade in the black background\n    ObjectAnimator bgAnim = ObjectAnimator.ofInt(colorDrawable, \"alpha\", 0, 255);\n    bgAnim.setDuration(ANIM_DURATION);\n    bgAnim.start();\n}\n```\n\nThe exit animation is basically a reverse of the enter animation. This Animate image back to thumbnail size/location as relieved from bundle. The endAction param, indicates the action gets run after the animation completes.\n\n```java\npublic void exitAnimation(final Runnable endAction) {\n    TimeInterpolator sInterpolator = new AccelerateInterpolator();\n    imageView.animate().setDuration(ANIM_DURATION).scaleX(mWidthScale).scaleY(mHeightScale).\n        translationX(mLeftDelta).translationY(mTopDelta)\n        .setInterpolator(sInterpolator).withEndAction(endAction);\n\n    // Fade out background\n    ObjectAnimator bgAnim = ObjectAnimator.ofInt(colorDrawable, \"alpha\", 0);\n    bgAnim.setDuration(ANIM_DURATION);\n    bgAnim.start();\n}\n```\n\n## 7. Override onBackPressed() method\n\nOverride `onBackPressed()` method to run our exit animation first, then exiting the activity when it is complete.\n\n```java\n@Override\npublic void onBackPressed() {\n    exitAnimation(new Runnable() {\n        public void run() {\n            finish();\n        }\n    });\n}\n```\n\n## 8. Download Complete Source\n\n[Download source](https://github.com/javatechig/Android-GridView-Advance-Tutorial)\n"])</script>
1<script>self.__next_f.push([1,"c6:T42ea,"])</script>
1<script>self.__next_f.push([1,"\nThis example is an improved version of my previous example [Android GridView Example](http://stacktips.com/articles/android-gridview-example-building-image-gallery-in-android). Instead of using static images to display the grid items, let’s make this example more realistic by downloading the data in real-time from the server and render the grid items. The following video depicts the output of this example.\n\n{{\u003c youtube fIX4SnBLaZg \u003e}}\n\nWithout wasting much time, let us jump straight into what it takes to build this kind of GridView. You need to follow the following steps to complete this example.\n\n## 1. Add GridView in Activity Layout\n\nFirst, create a new android project. For this example, I prefer to use **Android Studio**. Create a new layout file to your project `res/layout` folder and name it as `activity_grid_view.xml`. And add the following code blocks.\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:background=\"#f0f0f0\"\u003e\n\n    \u003cGridView\n        android:id=\"@+id/gridView\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"5dp\"\n        android:columnWidth=\"100dp\"\n        android:drawSelectorOnTop=\"true\"\n        android:gravity=\"center\"\n        android:numColumns=\"auto_fit\"\n        android:stretchMode=\"columnWidth\"\n        android:verticalSpacing=\"5dp\"\n        android:focusable=\"true\"\n        android:clickable=\"true\"/\u003e\n\n    \u003cProgressBar\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:id=\"@+id/progressBar\"\n        android:layout_centerInParent=\"true\"\n        android:visibility=\"gone\"/\u003e\n\u003c/RelativeLayout\u003e\n```\n\nThe above layout is pretty straight forward. We have declared an `GridView` and a `ProgressBar` in activity layout. The progress bar will be displayed when the data is being downloaded.\n\n## 2. Declare GridView Item Layout\n\nLet us now add another file named `grid_item_layout.xml` to `res/layout` folder. This layout will be used by custom grid adapter for laying out individual grid item. For the sake of simplicity, we are adding an `ImageView` and a `TextView`.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"wrap_content\"\n    android:layout_height=\"wrap_content\"\n    android:layout_marginTop=\"5dp\"\n    android:background=\"@drawable/grid_color_selector\"\n    android:orientation=\"vertical\"\n    android:padding=\"5dp\"\u003e\n\n    \u003cImageView\n        android:id=\"@+id/grid_item_image\"\n        android:layout_width=\"100dp\"\n        android:layout_height=\"100dp\"\n        android:scaleType=\"centerCrop\"/\u003e\n\n    \u003cTextView\n        android:id=\"@+id/grid_item_title\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginTop=\"5dp\"\n        android:gravity=\"center\"\n        android:maxLines=\"2\"\n        android:ellipsize=\"marquee\"\n        android:textSize=\"12sp\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n## 3. Adding Internet Permission\n\nYou might be aware that, Android application must declare all the permissions that are required for application. As we need to download the data form server, we need to add the `INTERNET` permission. Add the following line to `AndroidManifest.xml` file.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cmanifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.javatechig.gridviewexample\"\u003e\n\n    \u003cuses-permission android:name=\"android.permission.INTERNET\" /\u003e\n\n    \u003capplication\n        android:allowBackup=\"true\"\n        android:icon=\"@mipmap/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:theme=\"@style/AppTheme\"\u003e\n        \u003cactivity\n            android:name=\".GridViewActivity\"\n            android:label=\"@string/app_name\"\u003e\n            \u003cintent-filter\u003e\n                \u003caction android:name=\"android.intent.action.MAIN\" /\u003e\n\n                \u003ccategory android:name=\"android.intent.category.LAUNCHER\" /\u003e\n            \u003c/intent-filter\u003e\n        \u003c/activity\u003e\n\n        \u003cactivity android:name=\".DetailsActivity\" /\u003e\n    \u003c/application\u003e\n\n\u003c/manifest\u003e\n```\n\nNotice that we have also declared all the activities used in the application.\n\n## 4. Adding Picasso Image Downloading Library\n\nAndroid open source developer community brings some of the interesting libraries that can be integrated easily to Android applications. They serves a great deal of purpose and saves lot of time. Here in this example, I am talking about **`Picasso`** image loading library. We will add Picasso library for downloading and caching of images. Visit here to learn more about how to use Picasso library in Android.\
1n\nYou can add the Picasso library by adding the following dependency to the build.gradle file.\n\n```java\ndependencies {\n    compile fileTree(dir: 'libs', include: ['*.jar'])\n    compile 'com.android.support:appcompat-v7:21.0.3'\n    compile 'com.squareup.picasso:picasso:2.5.2'\n}\n```\n\n## 5. Create a GridView Custom Adapter\n\nA grid view is an adapter view. It requires an adapter to render the collection of data items. Add a new class named `GridViewAdapter.java` to your project and add the following code snippets.\n\n```java\npackage com.javatechig.gridviewexample;\n\nimport java.util.ArrayList;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.text.Html;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.squareup.picasso.Picasso;\n\npublic class GridViewAdapter extends ArrayAdapter\u003cGridItem\u003e {\n\n    private Context mContext;\n    private int layoutResourceId;\n    private ArrayList\u003cGridItem\u003e mGridData = new ArrayList\u003cGridItem\u003e();\n\n    public GridViewAdapter(Context mContext, int layoutResourceId, ArrayList\u003cGridItem\u003e mGridData) {\
1n        super(mContext, layoutResourceId, mGridData);\n        this.layoutResourceId = layoutResourceId;\n        this.mContext = mContext;\n        this.mGridData = mGridData;\n    }\n\n    /**\n     * Updates grid data and refresh grid items.\n     * @param mGridData\n     */\n    public void setGridData(ArrayList\u003cGridItem\u003e mGridData) {\n        this.mGridData = mGridData;\n        notifyDataSetChanged();\n    }\n\n    @Override\n    public View getView(int position, View convertView, ViewGroup parent) {\n        View row = convertView;\n        ViewHolder holder;\n\n        if (row == null) {\n            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();\n            row = inflater.inflate(layoutResourceId, parent, false);\n            holder = new ViewHolder();\n            holder.titleTextView = (TextView) row.findViewById(R.id.grid_item_title);\n            holder.imageView = (ImageView) row.findViewById(R.id.grid_item_image);\n            row.setTag(holder);\n        } else {\n            holder = (ViewHolder) row.getTag();\n        }\n\n        GridItem item = mGridData.get(position);\n        holder.titleTextView.setText(Html.fromHtml(item.getTitle()));\n\n        Picasso.with(mContext).load(item.getImage()).into(holder.imageView);\n        return row;\n    }\n\n    static class ViewHolder {\n        TextView titleTextView;\n        ImageView imageView;\n    }\n}\n```\n\nNotice the following in the above code snippets,\n\n-   The `setGridData()` method updates the data display on GridView.\n-   The `Picasso.with().load()` method is used to download the image from url and display on image view.\n-   The GridViewAdapter class constructor requires the id of the grid item layout and the list of data to operate on.\n-   You might be surprised, where is the `GridItem` class came from. Its not a magic, we need to add `GridItem.java` class to our project. The GridItem class looks as follows.\n\n## 6. Download Data and Hook it to Activity\n\nNow we will be heading towards hooking the adapter to GridView and make it functional. Create a new Java class and name it as `GridViewActivity.java` and perform the following steps.\n\n-   Override the `onCreate()` method and set the layout by calling `setContentView()` method\n-   Initialize the GridView and ProgressBar component by using their declared layout id.\n-   Initialize the `CustomGridView` adapter by passing the grid row layout id and the list of `GridItem` objects.\n-   Use AsyncTask to download data from server, once download is successful read the stream JSON response.\n-   Parse the JSON string into the list of GridItem objects. Once downloading and parsing is completed, in `onPostExecute()` callback update the UI elements.\n\nThe following code does all the above steps as described. Add the following code to GridViewActivity class.\n\n```java\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport android.content.Intent;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.support.v7.app.ActionBarActivity;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.GridView;\nimport android.widget.ProgressBar;\nimport android.widget.Toast;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\npublic class GridViewActivity extends ActionBarActivity {\n    private static final String TAG = GridViewActivity.class.getSimpleName();\n    private GridView mGridView;\n    private ProgressBar mProgressBar;\n    private GridViewAdapter mGridAdapter;\n    private ArrayList\u003cGridItem\u003e mGridData;\n    private String FEED_URL = \"http://stacktips.com/?json=get_recent_posts\u0026count=45\";\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_gridview);\n\n        mGridView = (GridView) findViewById(R.id.gridView);\n        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);\n\n        //Initialize with empty data\n        mGridData = new ArrayList\u003c\u003e();\n        mGridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, mGridData);\n        mGridView.setAdapter(mGridAdapter);\n\n        //Start download\n        new AsyncHttpTask().execute(FEED_URL);\n        mProgressBar.setVisibility(View.VISIBLE);\n    }\n\n    //Downloading data asynchronously\n    public class AsyncHttpTask extends AsyncTask\u003cString, Void, Integer\u003e {\n\n        @Override\n        protected Integer doInBackgroun
1d(String... params) {\n            Integer result = 0;\n            try {\n                // Create Apache HttpClient\n                HttpClient httpclient = new DefaultHttpClient();\n                HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));\n                int statusCode = httpResponse.getStatusLine().getStatusCode();\n\n                // 200 represents HTTP OK\n                if (statusCode == 200) {\n                    String response = streamToString(httpResponse.getEntity().getContent());\n                    parseResult(response);\n                    result = 1; // Successful\n                } else {\n                    result = 0; //\"Failed\n                }\n            } catch (Exception e) {\n                Log.d(TAG, e.getLocalizedMessage());\n            }\n            return result;\n        }\n\n        @Override\n        protected void onPostExecute(Integer result) {\n            // Download complete. Let us update UI\n            if (result == 1) {\n                mGridAdapter.setGridData(mGridData);\n            } else {\n                Toast.makeText(GridViewActivity.this, \"Failed to fetch data!\", Toast.LENGTH_SHORT).show();\n            }\n            mProgressBar.setVisibility(View.GONE);\n        }\n    }\n\n    String streamToString(InputStream stream) throws IOException {\n        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));\n        String line;\n        String result = \"\";\n        while ((line = bufferedReader.readLine()) != null) {\n            result += line;\n        }\n\n        // Close stream\n        if (null != stream) {\n            stream.close();\n        }\n        return result;\n    }\n\n    /**\n     * Parsing the feed results and get the list\n     * @param result\n     */\n    private void parseResult(String result) {\n        try {\n            JSONObject response = new JSONObject(result);\n            JSONArray posts = response.optJSONArray(\"posts\");\n            GridItem item;\n            for (int i = 0; i \u003c posts.length(); i++) {\n                JSONObject post = posts.optJSONObject(i);\n                String title = post.optString(\"title\");\n                item = new GridItem();\n                item.setTitle(title);\n                JSONArray attachments = post.getJSONArray(\"attachments\");\n                if (null != attachments \u0026\u0026 attachments.length() \u003e 0) {\n                    JSONObject attachment = attachments.getJSONObject(0);\n                    if (attachment != null)\n                        item.setImage(attachment.getString(\"url\"));\n                }\n                mGridData.add(item);\n            }\n        } catch (JSONException e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n\nAt this point you will be able to run the app and notice that the app will download the data from the server and display on GridView.\n\n## 7. Handle GridView Click Event\n\nRight now GridView is not responding to user clicks. Let us make it more functional by adding the following code.\n\n```java\nmGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {\npublic void onItemClick(AdapterView\u003c?\u003e parent, View v, int position, long id) {\n\n        //Get item at position\n        GridItem item = (GridItem) parent.getItemAtPosition(position);\n\n        //Pass the image title and url to DetailsActivity\n                Intent intent = new Intent(GridViewActivity.this, DetailsActivity.class);\n                intent.putExtra(\"title\", item.getTitle());\n                intent.putExtra(\"image\", item.getImage());\n\n        //Start details activity\n        startActivity(intent);\n    }\n});\n```\n\nWhen user clicks on a grid item, we will start another activity that displays the full screen image. You can start one activity form another by calling `startActivity()` method.\n\nWe need to pass the details of the item such as title, and image url for displaying it on `DetailsActivity`.\n\n## 8. Create Details Activity Layout\n\nAdd a new layout file to res/layout directory, name it as `activity_details_view.xml` and add the following code snippets.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cFrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:background=\"#000\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cImageView\n        android:id=\"@+id/grid_item_image\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:layout_gravity=\"center\"\n        android:scaleType=\"fitCenter\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/title\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"bottom\"\n        android:background=\"#00000c\"\n        android:padding=\"10dp\"\n        android:textColor=\"#fff\"\n        android:textSize=\"20dp\" /\u003e\n\u003c/FrameLayout\u003e\n```\n\n## 9. Completing the Details Activity\n\nThe `DetailsActivity` retrieves the details passed from `GridViewActivity` and renders the details on screen. Create a new class 
1named DetailsActivity and add the following code snippets.\n\n```java\npackage com.javatechig.gridviewexample;\n\nimport android.os.Bundle;\nimport android.support.v7.app.ActionBar;\nimport android.support.v7.app.ActionBarActivity;\nimport android.text.Html;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.squareup.picasso.Picasso;\n\npublic class DetailsActivity extends ActionBarActivity {\n    private TextView titleTextView;\n    private ImageView imageView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_details_view);\n\n        ActionBar actionBar = getSupportActionBar();\n        actionBar.hide();\n\n        String title = getIntent().getStringExtra(\"title\");\n        String image = getIntent().getStringExtra(\"image\");\n        titleTextView = (TextView) findViewById(R.id.title);\n        imageView = (ImageView) findViewById(R.id.grid_item_image);\n        titleTextView.setText(Html.fromHtml(title));\n\n        Picasso.with(this).load(image).into(imageView);\n    }\n}\n```\n\n## 10. Download Complete Example\n\n[Download source](https://github.com/javatechig/Android-GridView-Advance-Tutorial)\n\n## 11. Custom Activity Transition in GridView\n\nContinue reading in our [next tutorial.](http://stacktips.com/android/using-custom-activity-transition-in-gridview-image-gallery)\n"])</script>
1<script>self.__next_f.push([1,"c7:T1e11,"])</script>
1<script>self.__next_f.push([1,"\nA quick Android example with code snippet to demonstrate `[ListView](/articles/android-listview-tutorial)` parallax effect with sticky header. In our previous tutorial, we saw [Creating ListView Header Parallax Animation](/articles/how-to-create-listview-header-with-parallax-effect-in-android), now in this example we will go little further and make the list header parallax animation with an view stick to top when list is scrolled.  \nYou need to follow the following steps as described below to create the list view parallax effect.\n\nThe output of this example in the following attached video.\n\n{{\u003c youtube eyWDkwVnYxo \u003e}}\n\n## 1. Declare Activity Layout\n\nTo begin with let us start declaring your activity layout. It is a bit tricky. Let us take an frame layout that hosts the hero image, sticky view and a ListView.\n\n```xml\n\u003cFrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\u003e\n\n    \u003cImageView\n        android:id=\"@+id/heroImageView\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"250dp\"\n        android:background=\"@drawable/wallpaper\"\n        android:scaleType=\"fitCenter\" /\u003e\n\n    \u003cListView\n        android:id=\"@+id/listView\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:divider=\"#9E9E9E\"\n        android:dividerHeight=\"1dp\"\n        android:scrollbars=\"none\"\u003e\u003c/ListView\u003e\n\n    \u003cTextView\n        android:id=\"@+id/stickyView\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"50dp\"\n        android:background=\"#222\"\n        android:gravity=\"center_vertical\"\n        android:paddingLeft=\"10dp\"\n        android:text=\"Heading1\"\n        android:textColor=\"#fff\"\n        android:textSize=\"20sp\"\n        android:textStyle=\"bold\" /\u003e\n\u003c/FrameLayout\u003e\n```\n\nThe following screenshot depicts how out activity layout is defined.  \n[![How to Create ListView Parallax Effect with Sticky Header in Android](/media/articles/187/How-to-Create-ListView-Parallax-Effect-with-Sticky-Header-in-Android.png)](http://stacktips.com)\n\n## 2. Declare List Header Layout\n\nNow declare the layout for list header. In this example, I have declared an [ImageView](/articles/android-imageview-example) inside [FrameLayout](/articles/android-framelayout-example). The header view is declared as follows.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cSpace\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"250dp\" /\u003e\n\n    \u003cSpace\n        android:id=\"@+id/stickyViewPlaceholder\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"50dp\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\nNotice that in the above header layout,\n\n-   We have declared `Space` objects. Android Space widget is subclass of View, used to occupy invisible, transparent space on the screen. You cannot apply any style, such as color, background etc.\n-   The height of both Space objects are same as the height of hero image and sticky widget as declared in your activity layout.\n-   These two invisible views will be useful to calculate the view position and will help to create the parallel effect.\n\n## 3. Declare List Row Layout\n\nDeclare another layout for your list view row. In this example, for sake of simplicity I have declared a simple `TextView`. You may design fancy list of your choice by declaring your own custom adapter.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cTextView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:background=\"#FAFAFA\"\n    android:gravity=\"center_vertical\"\n    android:text=\"List Item\"\n    android:padding=\"8dp\"\n    android:minHeight=\"40dp\"\n    android:textColor=\"#222\"/\u003e\n```\n\n## 4. Handle ListView Scroll Events\n\nFollowing step will guide you with the necessary things required in your activity to create list view, add list header and implement parallax effect.\n\n-   Implement `setOnScrollListener` for your list view to handle the user scroll event.\n-   Calculate the position of the sticky header view according to the position of the first item in the ListView.\n-   When the first item is already reached to top, you don’t need to re-position the sticky header view.\n-   Set the hero image to scroll half of the amount that of ListView\n\n```java\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.support.v7.app.ActionBarActivity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.AbsListView;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * \u003cp/\u003e\n * Calculate the position of the sticky header view according to the\n * position of the first item in the ListView. When the first item is already\n * reached to top, you don't need to position the sticky header view.\n *\n * @author Nilanchala\n */\npublic class MainActivity extends ActionBarActivity {\n\n    private TextView stickyView;\n    private ListView listView;\n    private View heroImageView;\n\n    private View stickyViewSpacer;\n\n    private int MAX_ROWS = 20;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        /* Initialise list view, hero image, and sticky view */\n        listView = (ListView) findViewById(R.id.listView);\n        heroImageView = findViewById(R.id.heroImageView);\n        stickyView = (TextView) findViewById(R.id.stickyView);\n\n        /* Inflate list header layout */\n        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n        View listHeader = inflater.inflate(R.layout.list_header, null);\n        stickyViewSpacer = listHeader.findViewById(R.id.stickyViewPlaceholder);\n\n        /* Add list view header */\n        listView.addHeaderView(listHeader);\n\n        /* Handle list View scroll events */\n        listView.setOnScrollListener(new AbsListView.OnScrollListener() {\n\n            @Override\n            public void onScrollStateChanged(AbsListView view, int scrollState) {\n            }\n\n            @Override\n            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {\n\n                /* Check if the first item is already reached to top.*/\n                if (listView.getFirstVisiblePosition() == 0) {\n                    View firstChild = listView.getChildAt(0);\n                    int topY = 0;\n                    if (firstChild != null) {\n                        topY = f
1irstChild.getTop();\n                    }\n\n                    int heroTopY = stickyViewSpacer.getTop();\n                    stickyView.setY(Math.max(0, heroTopY + topY));\n\n                    /* Set the image to scroll half of the amount that of ListView */\n                    heroImageView.setY(topY * 0.5f);\n                }\n            }\n        });\n\n        /* Populate the ListView with sample data */\n        List\u003cString\u003e modelList = new ArrayList\u003c\u003e();\n        for (int i = 0; i \u003c MAX_ROWS; i++) {\n            modelList.add(\"List item \" + i);\n        }\n\n        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_row, modelList);\n        listView.setAdapter(adapter);\n    }\n}\n```\n\n## 5. Download Complete Source Code\n\n[Download source](https://github.com/javatechig/Android-Parallax-ListView-Sticky)\n"])</script>
1<script>self.__next_f.push([1,"c8:T1439,"])</script>
1<script>self.__next_f.push([1,"\nA quick Android example with code snippet to demonstrate `[ListView](http://stacktips.com/android/android-listview-tutorial)` header with parallax effect. You need to follow few steps as described below to create the list view parallax effect.  \n\nThe output of this example in the following attached video.\n\n{{\u003c youtube rcDWjRdYaSM \u003e}}\n\n## Declare Activity Layout\n\nTo begin with let us start declaring a simple layout for our example activity. We are adding just a simple ListView that covers the total width of screen.\n\n```xml\n\u003cListView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:id=\"@+id/list\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:dividerHeight=\"1dp\"\n    android:divider=\"#9E9E9E\"/\u003e\n```\n\n## Declare List Header Layout\n\nNow declare the layout for list header. In this example, I have declared an [ImageView](/articles/android-imageview-example) inside [FrameLayout](/articles/android-framelayout-example).\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cFrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"250dp\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cImageView\n        android:id=\"@+id/listHeaderImage\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:scaleType=\"centerCrop\"\n        android:src=\"@drawable/wallpaper\" /\u003e\n\u003c/FrameLayout\u003e\n```\n\n## 3. Declare List Row Layout\n\nDeclare another layout for your list view row. In this example, for sake of simplicity I have declared a simple `TextView`. You may design fancy list of your choice by declaring your own custom adapter.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cTextView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:background=\"#FAFAFA\"\n    android:gravity=\"center_vertical\"\n    android:text=\"List Item\"\n    android:padding=\"8dp\"\n    android:minHeight=\"40dp\"\n    android:textColor=\"#222\"/\u003e\n```\n\n## 4. Handle ListView Scroll Events\n\nFollowing step will guide you with the necessary things required in your activity to create list view, add list header and implement parallax effect.\n\n-   Let us now create an activity and set the layout by calling `setContentView()` method inside `onCreate()` lifecycle callback.\n-   Initialize list view and create an array adapter, which will be used for the list view.\n-   Inflate list header layout and set to list view by calling `listView.addHeaderView()` method.\n-   Handle user scroll events for list view and change the position Y of list header.\n-   For handling the user scroll event, you need to implement `AbsListView.OnScrollListener` interface to your activity or fragment class and override the `onScrollStateChanged` and `onScroll` method. The onScroll method will be called when user scrolls the list view up or downwards.\n\n```java\npackage com.javatechig.parallaxlistview;\n\nimport android.graphics.Rect;\nimport android.os.Bundle;\nimport android.support.v7.app.ActionBarActivity;\nimport android.view.LayoutInflater;\nimport android.view.ViewGroup;\nimport android.widget.AbsListView;\nimport android.widget.ArrayAdapter;\nimport android.widget.ImageView;\nimport android.widget.ListView;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MainActivity extends ActionBarActivity implements AbsListView.OnScrollListener {\n\n    private static final int MAX_ROWS = 50;\n    private int lastTopValue = 0;\n\n    private List\u003cString\u003e modelList = new ArrayList\u003c\u003e();\n    private ListView listView;\n    private ImageView backgroundImage;\n    private ArrayAdapter adapter;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        listView = (ListView) findViewById(R.id.list);\n\n        for (int i = 0; i \u003c MAX_ROWS;
1 i++) {\n            modelList.add(\"List item \" + i);\n        }\n\n        adapter = new ArrayAdapter(this, R.layout.list_row, modelList);\n        listView.setAdapter(adapter);\n\n        // inflate custom header and attach it to the list\n        LayoutInflater inflater = getLayoutInflater();\n        ViewGroup header = (ViewGroup) inflater.inflate(R.layout.custom_header, listView, false);\n        listView.addHeaderView(header, null, false);\n\n        // we take the background image and button reference from the header\n        backgroundImage = (ImageView) header.findViewById(R.id.listHeaderImage);\n        listView.setOnScrollListener(this);\n    }\n\n    @Override\n    public void onScrollStateChanged(AbsListView view, int scrollState) {\n\n    }\n\n    @Override\n    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {\n        Rect rect = new Rect();\n        backgroundImage.getLocalVisibleRect(rect);\n        if (lastTopValue != rect.top) {\n            lastTopValue = rect.top;\n            backgroundImage.setY((float) (rect.top / 2.0));\n        }\n    }\n}\n```\n\n## Download Complete Source Code\n\nhttps://github.com/javatechig/Parallax-List-View-Header\n"])</script>
1<script>self.__next_f.push([1,"c9:T4ef,\nQuick Java code snippet to show Linear / Sequential Search.\n\n```java\nimport java.util.Scanner;\n\npublic class LinearSearchExample {\n\n    public static void main(String args[]) {\n        int i, totalCount, search, inputArray[];\n\n        Scanner scanner = new Scanner(System.in);\n\n        System.out.println(\"Enter number of elements\");\n        totalCount = scanner.nextInt();\n        inputArray = new int[totalCount];\n\n        System.out.println(\"Enter \" + totalCount + \" integers\");\n\n        for (i = 0; i \u003c totalCount; i++) {\n            inputArray[i] = scanner.nextInt();\n        }\n\n        System.out.println(\"Enter value to find\");\n        search = scanner.nextInt();\n\n        for (i = 0; i \u003c totalCount; i++) {\n            // Element found\n            if (inputArray[i] == search) {\n                System.out.println(search + \" is present at location \"\n                        + (i + 1) + \".\");\n                break;\n            }\n        }\n\n        // Element not in the input array\n        if (i == totalCount) {\n            System.out.println(search + \" is not present in array.\");\n        }\n    }\n}\n```\n\n## Output\n\n[![Linear : Sequential Search Example in Java](/media/articles/189/Linear-Sequential-Search-Example-in-Java1.png)](http://stacktips.com)\nca:Tbee,"])</script>
1<script>self.__next_f.push([1,"\nQuick Java code snippet to sort Array ascending or descending using comparator in Java.\n\n```java\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class SortFruitObject {\n\n    public static void main(String args[]) {\n        Fruit pineappale = new Fruit(\"Pineapple\", \"Pineapple description\", 70);\n        Fruit apple = new Fruit(\"Apple\", \"Apple description\", 100);\n        Fruit orange = new Fruit(\"Orange\", \"Orange description\", 80);\n        Fruit banana = new Fruit(\"Banana\", \"Banana description\", 90);\n\n        Fruit[] fruits = new Fruit[4];\n        fruits[0] = pineappale;\n        fruits[1] = apple;\n        fruits[2] = orange;\n        fruits[3] = banana;\n\n        Arrays.sort(fruits, FruitNameComparator);\n        System.out.println(\"Sort by Fruit Name\");\n        for (Fruit temp : fruits) {\n            System.out.println(temp.toString());\n        }\n\n        System.out.println(\"=======================\");\n        Arrays.sort(fruits, fruitQuantityComparator);\n        System.out.println(\"Sort by Fruit Quantity\");\n        for (Fruit temp : fruits) {\n            System.out.println(temp.toString());\n        }\n    }\n\n    public static Comparator\u003cFruit\u003e FruitNameComparator = new Comparator\u003cFruit\u003e() {\n        public int compare(Fruit fruit1, Fruit fruit2) {\n            String fruitName1 = fruit1.getFruitName().toUpperCase();\n            String fruitName2 = fruit2.getFruitName().toUpperCase();\n\n            // ascending order\n            return fruitName1.compareTo(fruitName2);\n\n            // descending order\n            // return fruitName2.compareTo(fruitName1);\n        }\n\n    };\n\n    public static Comparator\u003cFruit\u003e fruitQuantityComparator = new Comparator\u003cFruit\u003e() {\n        public int compare(Fruit fruit1, Fruit fruit2) {\n\n            // ascending order\n            return fruit2.getQuantity() - fruit1.getQuantity();\n\n            // descending order\n            // return fruit1.getQuantity() - fruit2.getQuantity()\n        }\n\n    };\n}\n\nclass Fruit {\n    private String fruitName;\n    private String fruitDesc;\n    private int quantity;\n\n    public Fruit(String fruitName, String fruitDesc, int quantity) {\n        super();\n        this.fruitName = fruitName;\n        this.fruitDesc = fruitDesc;\n        this.quantity = quantity;\n    }\n\n    public String getFruitName() {\n        return fruitName;\n    }\n\n    public void setFruitName(String fruitName) {\n        this.fruitName = fruitName;\n    }\n\n    public String getFruitDesc() {\n        return fruitDesc;\n    }\n\n    public void setFruitDesc(String fruitDesc) {\n        this.fruitDesc = fruitDesc;\n    }\n\n    public int getQuantity() {\n        return quantity;\n    }\n\n    public void setQuantity(int quantity) {\n        this.quantity = quantity;\n    }\n\n    @Override\n    public String toString() {\n        return \"Name=\" + getFruitName() + \", Quantity=\" + getQuantity();\n    }\n}\n```\n\n**Output**  \n[![sort Array ascending or descending using comparator in Java.](/media/articles/190/sort-Array-ascending-or-descending-using-comparator-in-Java..png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"cb:T16ce,"])</script>
1<script>self.__next_f.push([1,"\nA `LinearLayout` manager is a most basic type of layout manager, that organizes its child views either `horizontally` or `vertically` based on the value provided in android:orientation property.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:orientation=\"horizontal\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\u003e\n    \u003c!-- add children here--\u003e\n\u003c/LinearLayout\u003e\n```\n\nNotice in the above code snippet, the orientation property access two possible values such as `vertical` or `horizontal`. This defines the whether the views to be organized vertically or horizontally. We had enough talk about linear layouts; let us move a bit towards the practical implementation of it. To began with let us design a login page layout as shown in the screenshot below. [![Linear Layout Manager Android](/media/articles/195/Linear-Layout-Manager-Android.png)](http://stacktips.com) We would add two edit text for the user to enter the username and password and two buttons for Login and Register action. **ActivityMain.axml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:orientation=\"vertical\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\u003e\n\n    \u003cEditText\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:id=\"@+id/password\"\n        android:padding=\"10dp\"\n        android:hint=\"@string/username_hint\" /\u003e\n\n    \u003cEditText\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:id=\"@+id/password\"\n        android:padding=\"10dp\"\n        android:hint=\"@string/password_hint\" /\u003e\n    \u003cButton\n        android:id=\"@+id/submit\"\n        android:layout_width=\"200dp\"\n        android:layout_height=\"wrap_content\"\n        android:padding=\"10dp\"\n        android:text=\"@string/login\" /\u003e\n    \u003cButton\n        android:id=\"@+id/register\"\n        android:layout_width=\"200dp \"\n        android:layout_height=\"wrap_content\"\n        android:padding=\"10dp\"\n        android:text=\"@string/register\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\nAs you see in the above layout XML;\n\n1.  Linear Layout has two properties as `layout_height` and `layout_width`. In android each layout manager/view must supply these two properties to define the height and width of the view in view hierarchy.\n2.  `wrap_ontent` – Wraps with the maximum allowed (Parent’s) width or height\n3.  `fill_parent` or match\\_parent –fits the view size to the available size of its parent\n4.  If you want to specify a static height or width for any view you can supply values in dp. For example in the above snippet, both the submit and register button has a static width of 200dp.\n5.  `DP` – Density independent Pixels, based on physical density of the screen.\n\n# Understanding the weight and gravity\n\nApart from the orientation attribute, the `weight` and gravity attribute can affect size and position of child views in a LinearLayout manager.\n\n## android:weight\n\nYou use weight to assign size importance to a control relative to the other controls in the container. Suppose a container has three controls: one has a weight of 1, whereas the others have a weight of 0. In this case, the control whose weight equals 1 will consume the empty space in the container.\n\n## android:gravity\n\nGravity is used to specify the alignment of view. For example, if you want to align a TextView’s text to the right, you would set its gravity to right. There are quite a few possible values for gravity, including left, center, right, top, bottom, center\\_vertical, clip\\_horizontal, and others.\n\nThe above screenshot shows that the Login and Register button is aligned one below other. It would be nicer, if we can align both the buttons horizontally and distribute equal space to each (as shown in the following screenshot).\n\n[![LinearLayout Manager Gravity Weight Xamarin](/media/articles/195/LinearLayout-Manager-Gravity-Weight-Xamarin.png)](http://stacktips.com)\n\nTo do so, we have to add another LinearLayout with horizontal orientation and add both the buttons to it. The following code blocks can be used to achieve the result as shown in the above screenshot.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:orientation=\"vertical\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\u003e\n    \u003cEditText\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:id=\"@+id/password\"\n        android:hint=\"@string/username_hint\" /\u003e\n    \u003cEditText\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:id=\"@+id/password\"\n        android:hint=\"@string/password_hint\" /\u003e\n    \u003cLinearLayout\n        android:orientation=\"horizontal\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\u003e\n        \u003cButton\n            android:id=\"@+id/submit\"\n            android:layout_width=\"200dp\"\n            android:layout_height=\"wrap_content\"\n            android:padding=\"10dp\"\n            android:text=\"@string/login\" /\u003e\n        \u003cButton\n            android:id=\"@+id/register\"\n            android:layout_width=\"200dp\"\n            android:layout_height=\"wrap_content\"\n            android:padding=\"10dp\"\n            android:text=\"@string/register\"\n            android:layout_weight=\"1\" /\u003e\n    \u003c/LinearLayout\u003e\n\u003c/LinearLayout\u003e\n```\n\n## android:gravity vs. android:layout\\_gravity\n\nNote that Android defines two similar gravity attributes: `android:gravity` and `android:layout_gravity`. Here’s the difference: android:gravity is a setting used by the view, whereas android:layout\\_gravity is used by the container.\n"])</script>
1<script>self.__next_f.push([1,"cc:Te3d,"])</script>
1<script>self.__next_f.push([1,"\n# Views and ViewGroups\n\nEverything that you see in an Android app is a View; buttons, labels, text boxes, and radio buttons are all examples of Views. Views are organized in a hierarchy using various types of ViewGroups. A ViewGroup is a special kind of View which is used to arrange (layout) other Views on the screen.\n\n## User Interface Widgets\n\nAndroid provides a comprehensive set of user interface widgets that can be used to build a rich user experience. All of these widgets are subtypes of View and can be organized into sophisticated layouts using various types of ViewGroups. All of the user interface widgets can be found in the android.widget package within the Application Framework.\n\nSome of the common UI widgets includes;\n\n-   TextView\n-   EditText\n-   Radio Buttons and Radio button group\n-   CheckBox\n-   Adapter views such as [List View](/articles/listview-example-in-xamarin-android), GridView\n-   [WebView](/articles/xamarin-android-webview-tutorial)\n-   Spinners, etc.\n\n# Declarative Versus Programmatic View Creation\n\nViews and ViewGroups can be created using two different methods, programmatically or declaratively. When using a programmatic approach, a developer makes API calls to create and position each individual View on screen. When using a declarative approach, a developer creates XML layout files that specify how Views should be arranged. Visual layout designer embedded to Xamarin Studio and Visual Studio IDE provides extensive support for creating the layout using drag and drop approach. In case of XML declaration, you need to remember each element and property to control the view/layout behavior.\n\nThe declarative method enjoys several advantages stated as follows:\n\n-   Provides better separation of the visual design of an application from the processing logic\n-   Allows multiple layouts to be created to support multiple devices or device configurations with a single code base\n-   Development tools, such as Android Studio, Android plugin for Eclipse and Xamarin Studio Android designer, allow you to view the user interface as you build it, without needing to compile and execute your application after each change\n\nWhile most developers prefer the declarative method of view creation, in practice, some combination of programmatic and declarative methods are often required.\n\n# Xamarin Android Layout Managers\n\nXamarin.Android offers a collection of view group classes that acts as container for views. These containers are refereed as layout managers. Each of the layout managers can contain one more child views and provides a specific strategy to manage the size and position of its children. For example, the Linear Layout class places its children either horizontally or vertically, one view adjacent to the other.\n\nFollowing table lists the different types of layout managers available in Xamarin android.\n\n| Layout Manager | Description |\n| --- | --- |\n| Linear Layout | Position its child views either horizontally or vertically |\n| Relative Layout | Position its child view relative to others child or parent. |\n| Table Layout | Position its child on tabular form |\n| Frame Layout | Allows to change content dynamically |\n| Grid Layout | Position child views in a grid format |\n| Absolute Layout (Deprecated) | Allows absolute positioning of child. This layout manager is deprecated and strictly not recommended to use for your app. |\n\nAll the above layout managers are derived from the View class; therefore all the layout managers can be nested one inside of one another. You can also create a custom layout by extending ViewGroup classes for specific requirements for your project.\n"])</script>
1<script>self.__next_f.push([1,"cd:Tc7a,"])</script>
1<script>self.__next_f.push([1,"\nBook titled **“Xamarin Mobile Application Development for Android”** – Second Edition is announced and is available to pre-order. This book is expected to be published in September 2015.\n\nIf you are a C# developer who wants to develop Android apps and enhance your existing skill set, then this book is ideal for you. Good working knowledge of C#, .NET, and object-oriented software development is assumed.\n\nFor preorder visit [packtpub.com](https://www.packtpub.com/application-development/xamarin-mobile-application-development-android-second-edition)\n\nTechnology trends come and go, but few have generated the excitement, momentum, or long-term impact that mobile computing has. Mobile computing impacts people’s lives at work and at home on a daily basis. Many companies and individual developers are looking to become a part of the movement but are unsure how to best utilize their existing skills and assets. The Xamarin suite of products provides new opportunities to those who already have a significant investment in C# development skills and .NET code bases, and would like to enter into this new, exciting world.\n\nThis example-oriented guide provides a practical approach to quickly learn the fundamentals of Android app development using C# and Xamarin.Android. It will lead you through building an Android app step-by-step with steadily increasing complexity.\n\nBeginning with an overview of the Android and Xamarin platforms to provide you with a solid understanding of the underlying platform, we gradually walk through building and testing a Points of Interest Android app using C# and the Xamarin.Android product. You will learn to create ListView and add detail view to your Android application. You will handle application behaviors on orientation changes, before learning the different techniques to manage resources and layouts to support multiple screen sizes. You will then access a SQLite database in a cross-platform way and add location features to your application. Finally, you will add camera integration to your application and deploy your app to the various Android app stores.  \n[![Xamarin Mobile Application Development for Android - Second Edition](/media/articles/197/Xamarin-Mobile-Application-Development-for-Android-Second-Edition.jpg)](https://www.amazon.co.uk/Xamarin-Mobile-Application-Development-Android/dp/1785280376)\n\n## About This Book\n\n-   Build and test multi-view Android applications using Xamarin.Android\n-   Work with device capabilities such as location sensors and the camera\n-   A progressive, hands-on guide to develop stunning Android applications using Xamarin\n\n## What You Will Learn\n\n-   Build a multi-view, orientation-aware Android application with navigation\n-   Lay out content using the LinearLayout, RelativeLayout, and TableLayout layout managers\n-   Use a ListView (AdapterView) and Adapter to build a view that is populated from server data\n-   Consume REST web service to perform GET, UPDATE, DELETE operation\n-   Use Android SQLite for data persistence and caching\n-   Capture the current location of a device, determine the street address, and integrate with the map app\n-   Test, debug, and deploy an Android app\n"])</script>
1<script>self.__next_f.push([1,"ce:T668,"])</script>
1<script>self.__next_f.push([1,"\nShared preferences are persistence key/value data pairs, used to store primitive data pairs such as bool, float, int, string and long. The data saved into android preference are persisted across different user sessions and is private to the application it is created. Any other application cannot access it.\n\nFor using shared preference to saving data pairs, you need first get an instance of `ISharedPreferences` interface. A shared preference can be specific to an activity or made global to all activities in the application. If you want to create a single preference file specific to an activity you can use `Activity.GetPreferences` to initialize ISharedPreferences interface. For getting the application level preference, you can call `GetSharedPreferences` method passing the preference name and mode of operation.\n\n```csharp\nISharedPreferences prefs = Application.Context.GetSharedPreferences (\"PREF_NAME\", FileCreationMode.Private);\n```\n\nNow let us call `Edit()` to get an instance of `ISharedPreferencesEditor`. This batches all of the changes made to value in shred preferences and saves only when there is a call to `Commit()` or `Apply()` is made.\n\n```csharp\nISharedPreferencesEditor editor = prefs.Edit();\neditor.PutInt(\"your_key1\" ,10);\neditor.PutString(\"your_key2\", \"Xamarin Example\");\neditor.Apply();\n```\n\nTo read values from shared preferences, we can use methods such as `GetString()`, `GetInt()`, `GetFloat()` etc. by providing proper key. The following snippets retrieves the values stored in the above step.\n\n```csharp\nvar value1 = prefs.GetInt (\"your_key1\", 0);\nvar value2 = prefs.GetString (\"your_key2\", null);\n```\n"])</script>
1<script>self.__next_f.push([1,"cf:T1610,"])</script>
1<script>self.__next_f.push([1,"\n## Dialogs in Android\n\nThe dialog is like any other window that pops up in front of the current window, used to show some short message, taking user input or to accept users decision. Unlike Toast, a dialog is generally used where user attention is mandated.\n\nAndroid supports several different ways to create a dialog such as `AlertDialog` and `FragmentDialog`. This example will widely cover all the aspect of DialogFragment.\n\nSince the release of Android 3.0 (API level 11), the fragment can show as a dialog and call as `DialogFragment`. If you’re supporting older android versions, you can make use of fragment-compatibility support library.\n\nTo create a dialog fragment, we will be using `android.app.DialogFragment` class. This class is derived from the Fragment and behaves much like a fragment with all available fragment lifecycle methods.\n\nIn the following sections, you learn how to use dialog fragment to show a simple alert dialog from activity.\n\n## Creating Dialog Fragment\n\nFirst step towards creating dialog fragment is to create a new class and extend it from DialogFragment. In the following code snippet, I am creating a new class named `MyDialogFragment`.\n\n```java\npublic class MyDialogFragment extends DialogFragment {\n\n}\n```\n\nAs a DialogFragment is much like any other fragment, the same lifecycle rules are applied. Now we have to override `onCreateView` or `onCreateDialog` method to provide the view hierarchy and construct the dialog fragment.\n\n```java\npublic class MyDialogFragment extends DialogFragment {\n\n    @Override\n    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n        View rootView = inflater.inflate(R.layout.fragment_sample_dialog, container, false);\n        getDialog().setTitle(\"Simple Dialog\");\n        return rootView;\n    }\n}\n```\n\nIn the above code, the `onCreateView()` method is expected to return the instance of view that represent the view hierarchy for your dialog. The instance of layout inflater can be used to inflate the layout for the fragment. ViewGroup represents the parent view where the fragment to be attached, and the Bundle param is the saved bundle data if available to restore the fragment to previous state.\n\n## Defining Dialog Fragment Layout\n\nNotice that, we are using `fragment_sample_dialog` layout form `onCreateView()` method, which is not declared anywhere. Let us create a simple layout that displays an ImageView and TextView as shown in the following screenshot.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:gravity=\"center\"\n    android:padding=\"10dp\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cImageView\n        android:id=\"@+id/image\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:src=\"@drawable/image\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/title\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Lorem ipsum dolor sit amet...\"\n        android:textSize=\"20dp\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/dismiss\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Dismiss\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\n## Displaying Dialog Fragment\n\nWe are pretty much done with creating dialog fragment. Put the following code snippet in Activity to show the dialog when user clicks on the button.\n\n```java\nFragmentManager fm = getFragmentManager();\nMyDialogFragment dialogFragment = new MyDialogFragment ();\ndialogFragment.show(fm, \"Sample Fragment\");\n```\n\nAt this point we can run the application and it will produce the output as shown in the following screenshot.  \n[![Android DialogFragment Example](/media/articles/203/Android-DialogFragment-Example.png)](http://stacktips.com)\n\n## Dism
1iss Dialog Fragment\n\nDialog fragment can be dismissed by calling `dismiss()` method from `MyDialogFragment` class. Place the following code snippet in MyDialogFragment `onCreateView()` method before return statement to dismiss the dialog when user clicks on Dismiss button.\n\n```java\nButton dismiss = (Button) rootView.findViewById(R.id.dismiss);\ndismiss.setOnClickListener(new View.OnClickListener() {\n\n    @Override\n    public void onClick(View v) {\n          dismiss();\n    }\n});\n```\n\nThe fragment dialog dismiss() method dismiss the dialog by removes the fragment from fragment manager, and then commit the fragment transaction.\n\n## Dialog Fragment using onCreateDialog()\n\nThere are two approaches to attach view group hierarchy to a dialog. Either we can override `onCreateView()` method and inflate layout as we have done in the step, or alternatively we can override `onCreateDialog()` method and supply a dialog instance. The following code hows how to create dialog fragment using onCreateDialog method.\n\n```java\n@Override\npublic Dialog onCreateDialog(Bundle savedInstanceState) {\n    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n    builder.setTitle(\"Simple Dialog\");\n    builder.setMessage(\"Some message here\");\n\n    builder.setPositiveButton(\"Ok\", new DialogInterface.OnClickListener() {\n        @Override\n        public void onClick(DialogInterface dialog, int which) {\n            dismiss();\n        }\n    });\n\n    builder.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n        @Override\n        public void onClick(DialogInterface dialog, int which) {\n            dismiss();\n        }\n    });\n\n    return builder.create();\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"d0:T10fd,"])</script>
1<script>self.__next_f.push([1,"\nConsuming data from web services is the most common task and very integral part to most of the full-fledged mobile application. In this tutorial we will take a look into various key concepts and steps for consuming web service methods from Xamarin Android application. This tutorial explains the following key concepts.\n\n# 1. Understanding web service basics\n\nWeb services are the server side applications that are meant to serve data or logic to various client applications. REST and SOAP are the industry standard web service architecture widely used. The data shared to client can be of various media formats, it can be plain text data, XML, JSON, audio, video or other supporting formats.\n\nAndroid application doesn’t care of which language the web service is developed in. All you need to know is the specification of the API Application Programming Interface). The specification includes, request method such as (GET, POST, PUT, DELETE), header metadata such as accept-type, content-type, etc.\n\nIn this example, we will be consuming the following API to fetch list of latest posts from JavaTechig.\n\n**URL Endpoint:** [http://stacktips.com/api/get\\_category\\_posts/?dev=1\u0026slug=android](http://stacktips.com/api/get_category_posts/?dev=1\u0026slug=android)  \n**Request Method:** GET  \n**Accept-Type:** “application/json”  \n**Response:**  \n[![JSON Feed Response](/media/articles/208/JSON-Feed-Response-940x838.png)](http://stacktips.com)\n\n# 2. Declare entity class\n\nNow that we have fair understanding of the structure of response, lets us go ahead with declaring an entity class that holds the repose received. Notice that the response is quite big and structure looks complex.\n\nFrom the above response, we will use only the list of recent posts from the above response and ignore the other data. Let us create an entity class “Post” with the following attributes.\n\n```cs\npublic class Post\n{\n     public int Id { get; set;}\n     public string Url { get; set; }\n     public string Title { get; set; }\n}\n```\n\n# 3. Asynchronous programming with async await\n\nDownloading data from server is a long running task, and hence we must create a new thread to perform such operations. We can make use of `System.Threading` namespace classes to create a new thread or simply use `async`, `await` keywords. The async and await are two keywords introduced since .NET 4.5 helps programmers to execute code asynchronously without writing your own thread. All you have to do is to define async keyword in your method declaration and use await keyword for any long running tasks.\n\n```cs\npublic async void DownloadDataAsync() {\n    string url = \"http://stacktips.com/api/get_category_posts/?dev=1\u0026slug=android\"\n\n    var httpClient = new HttpClient();\n    Task\u003cstring\u003e downloadTask = httpClient.GetStringAsync(url);\n    string content = await downloadTask;\n    Console.Out.WriteLine(\"Response: \\r\\n {0}\", content);\n}\n```\n\n# 4. Deserializing response using Json.NET\n\nSo far we have downloaded data from server and printing the JSON response on console. Now let us de-serialize the JSON response into Post list collection. In this example, I am using **Json.NET** component for parsing JSON data. You can add it to your project it from Xamarin component store.\n\nOnce you have added Json.NET component to your solution, add the following code snippet to `DownloadDataAsync()` method.\n\n```cs\n// de-serializing json response into list\nvar posts = new List \u003cPost\u003e ();\nJObject jsonResponse = JObject.Parse (content);\nIList\u003cJToken\u003e results = jsonResponse [\"posts\"].ToList ();\nforeach (JToken token in results) {\n    PointOfInterest poi = JsonConvert.DeserializeObject\u003cPost\u003e (token.ToString ());\n    posts.Add (poi);\n}\n\n// Write your logic here to display posts list on ui\n```\n\nIn this example, we are not writing any code to explain the user interface and hence, I have just a comment. You can follow [Xamarin Android ListView Example](http://stacktips.com/xamarin/listview-example-in-xamarin-android \"ListView Example in Xamarin.Android\") to learn more about creating list UI.\n\n# 5. Adding INTERNET permission\n\nDownloading data from server requires special permission to be granted in `AndroidManifest.xml`. Open AndroidManifest.xml and add the following code before `\u003capplication\u003e` element.\n\n```xml\n\u003cuses-permission android:name=\"android.permission.INTERNET\"/\u003e\n```\n"])</script>
1<script>self.__next_f.push([1,"d1:T12d3,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we will show you how to use TextWatcher in Android for an example.\n\n`TextWatcher` is used to keep watch on the [EditText](http://stacktips.com/android/edittext-validation-in-android-example \"Edittext Validation in Android Example\") content while user inputs the data. It allows you to keep track on each character when entered on EditText.\n\nA Text Watcher is really helpful for scenarios like login/register screen validation. As an when user is entering the data, you can keep an eye on user input and notify early instead of waiting until user press submit button manually. Another great real-time example is Google search; it shows the user the real-time search suggestion while user entering data.\n\nImplementing Text watcher is quite easy, you have to call `addTextChangedListener()` method and pass the reference to TextWatcher instance. You can override the following TextWatcher class method to take various actions when the content of EditText changes.\n\n1.  `afterTextChanged (Editable s) -` This method is called when the text has been changed. Because any changes you make will cause this method to be called again recursively, you have to be watchful about performing operations here, otherwise, it might lead to infinite loop.\n2.  `beforeTextChanged (CharSequence s, int start, int count, int after) -` This method is called to notify you that, within s, the count characters beginning at the start are about to be replaced by new text with long after. It is an error to attempt to make changes to s from this callback.\n3.  `onTextChanged (CharSequence s, int start, int before, int count) -` This method is called to notify you that, within s, the count characters beginning at the start have just replaced old text that had long before. It is an error to attempt to make changes to s from this callback.\n\n# Android TextWatcher Example\n\nLets us jump straight into the TextWatcher example in android. In this tutorial, we will create a simple EditField for entering a password, and the text watcher will show the same password in another TextView.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:orientation=\"vertical\"\n    android:padding=\"10dp\"\u003e\n\n    \u003cTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:paddingBottom=\"10dp\"\n        android:text=\"Enter your password and see the magic!!\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:textStyle=\"bold\" /\u003e\n\n    \u003cEditText\n        android:id=\"@+id/password\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:hint=\"Password\"\n        android:inputType=\"textPassword\"\n        android:padding=\"12dp\"\u003e\n\n        \u003crequestFocus /\u003e\n    \u003c/EditText\u003e\n\n    \u003cTextView\n        android:id=\"@+id/passwordHint\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_below=\"@+id/password\"\n        android:background=\"#ffd33a26\"\n        android:padding=\"5dp\"\n        android:text=\"* Not Entered\"\n        android:textColor=\"#fff\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\n# Using TextWatcher in Activity\n\n```java\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.text.Editable;\nimport android.text.TextWatcher;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends Activity {\n    private EditText passwordEditText;\n    private TextView textView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        /* Initializing views */\n        passwordEditText = (EditText) findViewById(R.id.password);\n        textView = (TextView) findViewById(R.id.passwordHint);\n        textView.setVisibility(View.GONE);\n\n        /* Set Text Watcher listener */\n        passwordEditText.addTextChangedListener(passwordWatcher);\n    }\n\n    private final TextWatcher passwordWatcher = new TextWatcher() {\n        public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n        }\n\n        public void onTextChanged(CharSequence s, int start, int before, int count) {\n            textView.setVisibility(View.VISIBLE);\n        }\n\n        public void afterTextChanged(Editable s) {\n            if (s.length() == 0) {\n                textView.setVisibility(View.GONE);\n            } else{\n                textView.setText(\"You have entered : \" + passwordEditText.getText());\n            }\n        }\n    };\n}
1\n```\n\n# Output\n\n[![Android TextWatcher Example](/media/articles/209/Android-TextWatcher-Example-620x579.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"d2:T1255,"])</script>
1<script>self.__next_f.push([1,"\nJSON (_JavaScript Object Notation_) is text-based, lightweight, language-independent data interchange format. It is one of the most popular and widely accepted data exchange formats on the Web.  \nAlthough the abbreviation starts with JavaScript, JSON is not a language with any language literals it just a specification for notation of data.\n\nIt is often misunderstood as a replacement of XML.  \nJSON defines a set of formatting rules for the portable representation of structured data.\n\n## How it is compared with XML?\n\nBefore JSON was popular, XML was considered to be the chosen data interchange format for most of the cases. XML is heavyweight, it consumes more of network bandwidth in comparison to JSON.\n\nXML data is considerably complex for parsing. It requires an XML DOM implementation on the client-side that would accept the XML response and convert into client program understandable format. It is often time-consuming to implement parsers on the client-side and it requires the XML DOM to be loaded into memory while parsing it.\n\nThe following example shows Employees data in XML format;\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cemployees\u003e\n   \u003cemploye\u003e\n      \u003cname\u003eAlex\u003c/first\u003e\n      \u003cid\u003e19\u003c/id\u003e\n      \u003cdetails\u003e\n          \u003clocation\u003eLondon\u003c/location\u003e\n         \u003cdob\u003e15 May 1962\u003c/dob\u003e\n         \u003csex\u003eMale\u003c/sex\u003e\n      \u003c/details\u003e\n   \u003c/employe\u003e\n   \u003cemploye\u003e\n      \u003cname\u003eMark\u003c/first\u003e\n      \u003cid\u003e19\u003c/id\u003e\n      \u003cdetails\u003e\n          \u003clocation\u003eBerlin\u003c/location\u003e\n         \u003cdob\u003e15 May 1968\u003c/dob\u003e\n         \u003csex\u003eMale\u003c/sex\u003e\n      \u003c/details\u003e\n   \u003c/employe\u003e\n\u003c/employees\u003e\n```\n\nThe above XML data can be represented in JSON format as follows:\n\n```json\n{\n  \"employees\": [\n    {\n      \"name\": \"Alex\",\n      \"id\": \"19\",\n      \"details\": {\n        \"location\": \"London\",\n        \"dob\": \"15 May 1962\",\n        \"sex\": \"Male\"\n      }\n    },\n    {\n      \"name\": \"Mark\",\n      \"id\": \"19\",\n      \"details\": {\n        \"location\": \"Berlin\",\n        \"dob\": \"15 May 1968\",\n        \"sex\": \"Male\"\n      }\n    }\n  ]\n}\n```\n\nNotice that the size of the XML document is comparatively larger to its representation in JSON. This result significant impact for larger size documents when used with real-time applications.\n\nThus, JSON becomes one of the most preferred media formats for data exchange between client and server.\n\n## JSON Syntax\n\nJSON defines only two data structures: Objects and Arrays. An object is a collection of name-value pairs, and an array is a list of values.\
1n\nJSON defines six value types: String, Number, Object, Array, Boolean and null. JSON has the following syntax:\n\n-   Objects are enclosed in braces ({})\n-   Name-value pairs are separated by a comma (,)\n-   The name and value in a pair are separated by a colon (:).\n-   Names in an object are strings, whereas values may be of any of the six value types, including another array or an object.\n-   Arrays are enclosed in brackets (\\[\\]), and their values are separated by a comma (,). Each value in an array may be of a different type, including another array or an object.\n\nIn the above JSON example, you will notice that the value for the name “employees” is an array whose elements are two objects.\n\n## Uses of JSON\n\nJSON is often used as a data interchange format to serialize and deserialize data in applications that communicate with each other over the Internet. Because of its open standard, it is well suited for many different programming languages.\n\nRESTful web services use JSON extensively as the format for the data in requests and responses. The HTTP header used to indicate that the content of a request or a response is JSON data is\n\n```text\nContent-Type: application/json\n```\n\n## JSON Processing in JavaScript\n\n### JSON.parse()\n\nWhen receiving data from a web server, the data is always a string. We can parse the data to an JavaScript object using `JSON.parse()` method.\n\n```javascript\nvar jsonString = '{\"employees\":[{\"name\":\"Alex\",\"id\":\"19\",\"details\":{\"location\":\"London\",\"dob\":\"15 May 1962\",\"sex\":\"Male\"}},{\"name\":\"Mark\",\"id\":\"19\",\"details\":{\"location\":\"Berlin\",\"dob\":\"15 May 1968\",\"sex\":\"Male\"}}]}';\n\nvar jsonObject = JSON.parse(jsonString);\nconsole.log(jsonObject.employees[0].name);\nconsole.log(jsonObject.employees[0].id);\nconsole.log(jsonObject.employees[0].details.location);\n```\n\nThe `JSON.parse()` method accepts the second argument `reviver`, to perform a transformation on the resulting object before it is returned.\n\n### JSON.stringify()\n\nThe JSON.stringify() method converts a JavaScript object to a JSON string representation. It can optionally use a replacer function to replace values using custom logic.\n\n```javascript\nvar resultString = JSON.stringify(jsonObject);\nconsole.log(resultString);\n```\n"])</script>
1<script>self.__next_f.push([1,"d3:T11d2,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we will show you, how to use Android ScrollView component and create a simple example using various ScrollView properties.\n\nMost Android application will likely to have the contents that’s doesn’t fit the screen. Think a bit about displaying the news details, the contents are dynamic and can grow beyond your screen size. If we design our screen layout using standard layout managers like [LinearLayout](http://stacktips.com/android/android-linearlayout-example \"Android LinearLayout Example\"), [RelativeLayout](http://stacktips.com/android/android-relativelayout-example \"Android RelativeLayout Example\"), [FrameLayout](http://stacktips.com/android/android-framelayout-example \"Android FrameLayout Example\") or [TableLayout](http://stacktips.com/android/android-table-layout-example \"Android Table Layout Example\"); when the content grows, and data goes beyond screen size, and user won’t be able scroll and view the content.\n\n**ScrollView** is a special kind of layout, designed to hold view larger than its actual size. When the Views size goes beyond the ScrollView size, it automatically adds scroll bars and can be scrolled vertically.\n\n1.  ScrollView can hold only one direct child. This means that, if you have complex layout with more view controls, you must enclose them inside another standard layout like [LinearLayout](http://stacktips.com/android/android-linearlayout-example \"Android LinearLayout Example\"), [TableLayout](http://stacktips.com/android/android-table-layout-example \"Android Table Layout Example\") or [RelativeLayout](http://stacktips.com/android/android-relativelayout-example \"Android RelativeLayout Example\").\n2.  You can specify `layout_height` and `layout_width` to adjust height and width of screen.\n3.  Scrollview is ideal for screens 
1where scrolling is required, but it is an overhead when scroll view is used to render a larger list of data. Android provides specialized adapter views like [ListView](http://stacktips.com/android/android-listview-tutorial \"Android ListView Example\"), [GridView](http://stacktips.com/android/android-gridview-example-building-image-gallery-in-android \"Android Gridview Example- Building Image Gallery in android\") and [Recycler View](http://stacktips.com/android/android-recyclerview-example \"Android RecyclerView Example\") (Introduced in Android Lollipop) are recommended for long lists.\n4.  You should never use a ScrollView with a ListView or GridView, because they both takes care of their own vertical scrolling.\n5.  ScrollView only supports vertical scrolling. Use `HorizontalScrollView` for horizontal scrolling.\n6.  The `android:fillViewport` property defines whether the scrollview should stretch its content to fill the viewport. You can set the same property by calling `setFillViewport(boolean)` method.\n\n# Android ScrollView Example\n\nLet us create an example that displays the layout as shown in the below screenshot. Notice that the blue like indicates the outline of textView2 is gone beyond the scren.\n\n**[![Android ScrollView Example](/media/articles/211/Android-ScrollView-Example.png)](http://stacktips.com)**\n\n# Scrollbar Layout\n\n```xml\n\u003cScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:orientation=\"vertical\"\n    android:padding=\"10dp\"\n    android:fillViewport=\"false\"\u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:orientation=\"vertical\"\u003e\n        \u003cImageView\n            android:id=\"@+id/imageView\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"200dp\"\n            android:scaleType=\"centerCrop\"\n            android:src=\"@drawable/image\" /\u003e\n\n        \u003cButton\n            android:id=\"@+id/button\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"KNOW MORE\" /\u003e\n\n        \u003cTextView\n            android:id=\"@+id/textView\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"@string/title\"\n            android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n        \u003cTextView\n            android:id=\"@+id/textView2\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"@string/description\"\n            android:textAppearance=\"?android:attr/textAppearanceSmall\" /\u003e\n    \u003c/LinearLayout\u003e\n\u003c/ScrollView\u003e\n```\n"])</script>
1<script>self.__next_f.push([1,"d4:T16ba,"])</script>
1<script>self.__next_f.push([1,"\nIn the course of this tutorial, we will take a look into using WebView in Xamarin.Android. This tutorial loads simple webpage on `WebView` and using `WebViewClient`.\n\n## Introduction to WebView\n\n1.  WebView is an android UI component that displays webpages. It can either display a remote webpage or can also load static HTML data.\n2.  This encompasses the functionality of a browser that can be integrated to application. Most of the android applications like WordPress, Flipboard, fiddly; Google Reader, etc. are integrated with WebView in order to display certain piece of online contents.\n3.  It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, and perform text searches and more.\n4.  The implementation of WebView is quite simple like any other views, all you have to do is declare the WebView layout on your Activity or Fragment, instantiate and load the data on WebView.\n\nFollowing section of the tutorial, will drive you with step by step approach to create a simple WebView with different configuration params and load stacktips.com home page.\n\n## Declare WebView Layout\n\nAs discussed, let us create a simple WebView layout that covers the full screen space.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:orientation=\"vertical\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\u003e\n\n    \u003cWebView\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:id=\"@+id/webView\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n## Load Static HTML Data on WebView\n\nFollowing activity class snippet will show you how to initialize WebView instance and load static Html string onto it.\n\n```csharp\n[Activity (Label = \"WebViewExample\", MainLauncher = true, Icon = \"@drawable/icon\")]\npublic class MainActivity : Activity\n{\n    protected override void OnCreate (Bundle bundle)\n    {\n        base.OnCreate (bundle);\n\n        // Set our view from the \"main\" layout resource\n        SetContentView (Resource.Layout.Main);\n\n        // Get WebView from the layout resource,\n        // and load html text data on it\n        WebView mWebView = FindViewById\u003cWebView\u003e(Resource.Id.webView);\n\n        string customHtml = \"\u003chtml\u003e\u003cbody\u003e\u003ch1\u003eHello, WebView\u003c/h1\u003e\" +\n            \"\u003ch1\u003eHeading 1\u003c/h1\u003e\u003ch2\u003eHeading 2\u003c/h2\u003e\u003ch3\u003eHeading 3\u003c/h3\u003e\" +\n            \"\u003cp\u003eThis is a sample paragraph.\u003c/p\u003e\" +\n            \"\u003c/body\u003e\u003c/html\u003e\";\n        mWebView.LoadData(customHtml, \"text/html\", \"UTF-8\");\n    }\n}\n```\n\n### How it works?\n\n1.  Like any other view controller, let us first instantiate WebView in your Activity by calling FindViewById() method. This requires you to import `Android.Webkit` package.\n2.  Call `LoadData()` method that accepts your static Html string, mime type and the encoding format.\n\nThe output of the above code is below\n\n[![Load Static HTML Data on WebView](/media/articles/213/Load-Static-HTML-Data-on-WebView-300x294.png)](#)\n\n## Load Remote URL on WebView\n\n1.  The default behavior of Android is to open device browser, when links are clicked. But as our WebView should work like a embedded browser, we must override to always open the links in the WebView instead redirecting it to the default browser.\n2.  We can do this using android `WebViewClient`. WebViewClient helps to monitor events in a WebView. We have to override the `shouldOverrideUrlLoading()` method. This method allows performing your own action when a particular URL is selected. Once we are ready with the WebViewClient, we can set the WebViewClient of your WebView using the `setWebViewClient()` method.\n3.  The WebViewClient class has some other useful methods such as `OnPageStarted()`, `OnPageFinished()` and `OnReceivedError()` that helps you to show loading progress of WebView content, or handle error.\n\nCheckout my Android tutorial that explains [How to show loading progress in Android WebView](http://stacktips.com/android/progressbar-while-loading-webview \"ProgressBar while Loading WebView in Android\"). Bear with me, this tutorial is written in Java. You need to take the pain to make it compatible for C#.\n\nNow let us go back to our example, and take a look into how our activity class looks like.\n\n```csharp\n[Activity (Label = \"WebViewExample\", MainLauncher = true, Icon = \"@drawable/icon\")]\npublic class MainActivity : Activity\n{\n    protected override void OnCreate (Bundle bundle)\n    {\n        base.OnCreate (bundle);\n\n        // Set our view from the \"main\" layout resource\n        SetContentView (Resource.Layout.Main);\n\n        WebView mWebView = FindViewById\u003cWebView\u003e(Resource.Id.webView);\n        mWebView.Settings.JavaScriptEnabled = true;\n\n        mWebView.SetWebViewClient (new MyWebViewClient());\n\n        //Load url to be randered on WebView\n        mWebView.LoadUrl(\"http://www.stacktips.com\");\n    }\n\n    public class MyWebViewClient : WebViewClient\n    {\n      public override bool ShouldOverrideUrlLoading (WebView view, string url)\n        {\n            view.LoadUrl (url);\n            return true;\n        }\n\n        public override void OnPageStarted (WebView view, string url, Android.Graphics.Bitmap favicon)\n        {\n            base.OnPageStarted (view, url, favicon);\n        }\n\n        public override void OnPageFinished (WebView view, string url)\n        {\n            base.OnPageFinished (view, url);\n        }\n\n        public override void OnReceivedError (WebView view, ClientError errorCode, string description, string failingUrl)\n        {\n            base.OnReceivedError (view, errorCode, description, failingUrl);\n        }\n    }\n}\n```\n\nOutput of the above code is shown below  \n![Load Remote URL on WebView](/media/articles/213/Load-Remote-URL-on-WebView-300x416.png)\n"])</script>
1<script>self.__next_f.push([1,"d5:T11dc,"])</script>
1<script>self.__next_f.push([1,"\nThe LinearLayout is the most basic layout manager provided by Android. The LinearLayout organizes the child views either horizontally or vertically based on the specified orientation property. The value for orientation property can be either `horizontal` or `vertical`.\n\nHere is how the LinearLayout declaration looks like in Android layout\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n       android:orientation=\"horizontal\"\n       android:layout_width=\"fill_parent\"\n       android:layout_height=\"wrap_content\"\u003e\n\n\u003c!-- add children here--\u003e\n\n\u003c/LinearLayout\u003e\n```\n\nNotice that in the above code snippets, we have specified orientation as horizontal, this aligns all its child layout/views horizontally.\n\nAll of the layout managers can be nested. This means that you can put a RelativeLayout or FrameLayout as a child to LinearLayout.\n\nFor example, if you want to create a layout as shown in the picture below, you need to construct a vertical layout manager that contained horizontal layout managers, where each row owns its own horizontal layout.\n\n[![LinearLayout Example](/media/articles/214/LinearLayout-Example.png)](http://stacktips.com)\n\n**Example**\n\n```java\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:orientation=\"horizontal\"\n        android:padding=\"5dp\"\u003e\n\n        \u003cTextView\n            android:id=\"@+id/textView\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"Label1\"\n            android:textAppearance=\"?android:attr/textAppearanceMedium\" /\u003e\n\n        \u003cEditText\n            android:id=\"@+id/editText\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"Edit text1\" /\u003e\n\n    \u003c/LinearLayout\u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:orientation=\"horizontal\"\n        android:padding=\"5dp\"\u003e\n\n        \u003cTextView\n            android:id=\"@+id/textView1\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"Label2\"\n            android:textAppearance=\"?android:attr/textAppearanceMedium\" /\u003e\n\n        \u003cEditText\n            android:id=\"@+id/editText1\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"Edit text2\" /\u003e\n\n    \u003c/LinearLayout\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n### Understanding Weight\n\nThe weight property is used to assign a size importance of child views in a container. For example, if you want to place two buttons distributed horizontally by occupying each half of the screen width, you can define `layout_weight` as 0.5 for each of the buttons inside LinearLayout. Following screenshot depicts the views distributed  \nequally using weight property.\n\n[![LinearLayout Weight Property](/media/articles/214/LinearLayout-Weight-Property.png)](http://stacktips.com/android/android-linearlayout-example/attachment/linearlayout-weight-property)  \n**Example**\n\nFollowing code snippets implements the same as shown in the above image.\n\n```java\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:layout_marginTop=\"10dp\"\n    android:orientation=\"horizontal\"\u003e\n\n    \u003cButton\n        android:id=\"@+id/button\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_weight=\"0.5\"\n        android:text=\"Button1\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/button2\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_weight=\"0.5\"\n        android:text=\"Button2\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n### Key Points\n\n-   If a LinearLayout is set to vertical orientation and contains a number of views than the screen space, it will not be scrollable by default. You have to explicitly put the LinearLayout inside a `ScrollView`.\n-   you must be careful about over-using the LinearLayout. If your application design demands the nesting of multiple LinearLayouts, you may want to consider using a RelativeLayout instead.\n"])</script>
1<script>self.__next_f.push([1,"d6:T1278,"])</script>
1<script>self.__next_f.push([1,"\nIn the course of this tutorial, we will take a look into Android TextView widget and various TextView properties.\n\nTextView is one of the most fundamental Android user interface widget, which is used to display text on an Android screen. TextView is like a dummy label, doesn’t allow to edit text input.\n\nFollowing are some of the most used TextView properties.\n\n| Attribute Name | Related Method | Description |\n| --- | --- | --- |\n| android:autoLink | setAutoLinkMask(int) | Automatically convert the links such as web url or email. |\n| android:autoText | setKeyListener(KeyListener) | Auto spelling correction for text. |\n| android:ellipsize | setEllipsize(TextUtils.TruncateAt) | If the width required by text is longer than the View itself, it ellipsized text. |\n| android:ems | setEms(int) | Makes the TextView be exactly this many ems wide. |\n| android:gravity | setGravity(int) | Specifies how to align the text by the view’s x- and/or y-axis when the text is smaller than the view. |\n| android:lineSpacingMultiplier | setLineSpacing(float,float) |  |\n| android:lines | setLines(int) | Makes the TextView be exactly this many lines tall. |\n| android:maxLines | setMaxLines(int) | Makes the TextView be at most this many lines tall. |\n| android:minLines | setMinLines(int) | Makes the TextView be at least this many lines tall. |\n| android:minWidth | setMinWidth(int) | Makes the TextView be at least this many pixels wide. |\n| android:shadowColor | setShadowLayer(float, float, float,int) | Place a blurred shadow of text underneath the text, drawn with the specified color. |\n| android:shadowDx | setShadowLayer(float, float, float, int) | Horizontal offset of the text shadow. |\n| android:shadowDy | setShadowLayer(float, float, float, int) | Vertical offset of the text shadow. |\n| android:shadowRadius | setShadowLayer(float, float, float, int) | Blur radius of the text shadow. |\n| android:text | setText(CharSequence, TextView.BufferType) | Text to display. |\n| android:textAllCaps | setAllCaps(boolean) | Present the text in ALL CAPS. |\n| android:textAppearance |  | Base text color, typeface, size, and style. |\n| android:textColor | setTextColor(int) | Text color. |\n| android:textSize | setTextSize(int, float) | Size of the text. |\n| android:typeface | setTypeface(Typeface) | Typeface (normal, sans, serif, monospace) for the text. |\n\nFor all TextView properties and attributes follow official [TextView documentation](http://developer.android.com/reference/android/widget/TextView.html).\n\nAlso refer the following tutorials to learn more on Android TextView  \n\n[How to apply shadow effect on Android TextView](http://stacktips.com/android/how-to-apply-shadow-effect-on-android-textview)  \n[How to use external fonts in Android TextView](http://stacktips.com/android/using-external-fonts-in-android-view \"Using External Fonts in Android View\")  \n[How to Display HTML in Android TextView](http://stacktips.com/android/display-html-in-android-textview \"How to Display HTML in Android TextView\")\n\n## TextView Example\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:layout_marginTop=\"10dp\"\n    android:orientation=\"vertical\"\n    android:padding=\"10dp\"\u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView1\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginBottom=\"10dp\"\n        android:gravity=\"center_horizontal\"\n        android:text=\"stacktips.com\"\n        android:textAllCaps=\"true\"\n        android:textColor=\"#86AD33\"\n        android:textSize=\"25dp\"\n        android:textStyle=\"bold\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView2\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center_horizontal\"\n        android:layout_marginBottom=\"20dp\"\n        android:ellipsize=\"end\"\n        android:letterSpacing=\"1.5\"\n        android:maxLines=\"2\"\n        android:text=\"Free programming tutorials on Java, Android development, Xamarin, Java Design Pattern, Data Structure Algorithm and examples on related technologies.\"\n        android:textAppearance=\"?android:attr/textAppearanceMedium\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView3\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center_horizontal\"\n        android:autoLink=\"email|web\"\n        android:lineSpacingMultiplier=\"1.5\"\n        android:text=\"Have questions about stacktips.com or just want to chat? Contact us at [email protected]\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n"])</script>
1<script>self.__next_f.push([1,"d7:T1bc3,"])</script>
1<script>self.__next_f.push([1,"\nIn the course of this tutorial, we will take a look into the new Swipe to refresh layout introduced in material design.\n\nAndroid Lollipop is baked with some of the finest looking user interface widgets and UI design guidelines, and what they call it as Material Design. Some of the widgets are fine-tuned while some new of them are added to the SDK.\n\nThe Swipe to refresh layout is used to indicate user while the content of a screen is being updated. The Swipe to refresh layout was earlier introduced in Android 4.4 Kitkat and was named as `SwipeRefreshLayout`. Visually it was represented just below ActionBar.\n\nSince Android Lollipop, the visual representation of the swipe to refresh layout has been changed drastically. It appears as a circular refresh animation, horizontally centered and appears right below the [Toolbar](http://stacktips.com/android/android-lollipop-toolbar-example \"Android Lollipop Toolbar Example\"). Check out official documentation for [Swipe to refresh](http://www.google.co.uk/design/spec/patterns/swipe-to-refresh.html) layout in Android Lollipop.\n\n# Swipe to Refresh Layout Example\n\nIn this example, we will create the sample application that downloads the data from a server feed, and displays on a ListView. It also allows the user the ability to swipe down and request for updated data from the server.\n\nThe output of this example is as the following video.\n\n{{\u003c youtube y9RdvzelGbQ \u003e}}\n\n  \nNow without wasting much of time, lets us move straight into its implementation. To implement Swipe to refresh layout, you will need the v4 support library. You can include the v4 support library to your project by adding below dependency in `build.gradle` file.\n\n```groovy\ndependencies {\n    compile fileTree(dir: 'libs', include: ['*.jar'])\n    compile \"com.android.support:appcompat-v7:21.0.+\"\n}\n```\n\nSecondly, let us define the swipe to refresh layout and list view to show the feed response. Create a new layout file inside res/layout folder, name it as activity\\_main.xml and paste the below code snippets.\n\n### activity\\_main.xml\n\n```xml\n\u003candroid.support.v4.widget.SwipeRefreshLayout\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:id=\"@+id/swipeRefreshLayout\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\u003e\n\n    \u003cListView\n        android:id=\"@+id/listView\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\u003e\u003c/ListView\u003e\n\u003c/android.support.v4.widget.SwipeRefreshLayout\u003e\n```\n\n## How it works\n\n-   The ListView is placed as a child view to SwipeRefreshLayout.\n-   This allows user the ability to show the loading spinner when user swipes the ListView edge. All the functionality of displaying loading bar is encapsulated inside `SwipeRefreshLayout` class.\n-   When user swipes down, the `OnRefreshListener` events gets fired. You can handle this event to write the logic for downloading or refreshing data.\n-   Note that, once data is downloaded, user has to manually call `setRefreshing(false)` to hide the refresh spinner.\n\nLet us now initialize the SwipeRefreshLayout and ListView from activity and write the logic to download data from server.\n\nIn this example we are downloading data form server and parsing JSON response before we rendering it on the ListView. Please refer [Android Networking Tutorial](http://stacktips.com/android/android-networking-tutorial \"Android Networking Tutorial\") for understanding more on this code.\n\n### MainActivity.java\n\n```java\npublic class MainActivity extends ActionBarActivity {\n\n    private ListView mListView = null;\n    private ArrayAdapter mAdapter = null;\n    private SwipeRefreshLayout mSwipeRefreshLayout = null;\n\n    private String[] feedList = null;\n    private String feedUrl = \"http://stacktips.com/api/get_category_posts/?dev=1\u0026slug=android\";\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n\n        setContentView(R.layout.activity_main);\n\n        mListView = (ListView) findViewById(R.id.listView);\n\n        //Start Downloading data\n        new DownloadFilesTask().execute(feedUrl);\n\n        //Initialize swipe to refresh view\n        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);\n        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {\n            @Override\n            public void onRefresh() {\n                //Refreshing data on server\n                new DownloadFilesTask().execute(feedUrl);\n            }\n        });\n    }\n\n    private void updateList() {\n        ArrayAdapter mAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, feedList);\n        mListView.setAdapter(mAdapter);\n\n        if (mSwipeRefreshLayout.isRefreshing()) {\n            mSwipeRefreshLayout.setRefreshing(false);\n        }\n    }\n\n    private class DownloadFilesTask extends AsyncTask\u003cString, Void, Void\u003e {\n\n        @Override\n        protected void onProgressUpdate(Void... values) {\n        }\n\n        @Override\n        protected void onPostExecute(Void result) {\n            if (null != feedList) {\n                updateList();\n            }\n        }
1\n\n        @Override\n        protected Void doInBackground(String... params) {\n            // getting JSON string from URL\n            JSONObject json = getJSONFromUrl(params[0]);\n\n            //parsing json data\n            parseJson(json);\n            return null;\n        }\n    }\n\n    public JSONObject getJSONFromUrl(String url) {\n        InputStream is = null;\n        JSONObject jObj = null;\n        String json = null;\n\n        try {\n            DefaultHttpClient httpClient = new DefaultHttpClient();\n            HttpPost httpPost = new HttpPost(url);\n\n            HttpResponse httpResponse = httpClient.execute(httpPost);\n            HttpEntity httpEntity = httpResponse.getEntity();\n            is = httpEntity.getContent();\n\n            BufferedReader reader = new BufferedReader(new InputStreamReader(is, \"iso-8859-1\"), 8);\n            StringBuilder sb = new StringBuilder();\n            String line = null;\n            while ((line = reader.readLine()) != null) {\n                sb.append(line + \"\\n\");\n            }\n            is.close();\n            json = sb.toString();\n\n            jObj = new JSONObject(json);\n\n        } catch (Exception e) {\n            Log.e(\"Error\", \"Error parsing data \" + e.toString());\n        }\n        return jObj;\n    }\n\n    public void parseJson(JSONObject json) {\n        try {\n            if (json.getString(\"status\").equalsIgnoreCase(\"ok\")) {\n                JSONArray posts = json.getJSONArray(\"posts\");\n\n                feedList = new String[posts.length()];\n                for (int i = 0; i \u003c posts.length(); i++) {\n                    JSONObject post = (JSONObject) posts.getJSONObject(i);\n                    feedList[i] = post.getString(\"title\");\n                }\n            }\n        } catch (JSONException e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n\n[Download source](https://github.com/npanigrahy/Android-Lollipop-Swipe-to-Refresh)\n"])</script>
1<script>self.__next_f.push([1,"d8:Tfed,"])</script>
1<script>self.__next_f.push([1,"\nThe TableLayout layout is an extension of LinearLayout. As the name indicates, TableLayout is used to display child View elements in rows and columns.\n\nThe concept of TableLayout works something similar to an HTML table. If you can recall the HTML table, TableLayout can be explained as \u003ctable\u003e tag and TableRow is like a \u003ctr\u003e element. You can use any view as table cell element.\n\nLet us create a TableView layout to display a list of Android version releases. Each row contains three cells that represent version code, version name, and API level. We are trying to achieve the same as the screenshot shown below.\n\n[![TableLayout Android Example](/media/articles/217/TableLayout-Android-Example.png)](http://stacktips.com)\n\n# Example\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cTableLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:layout_marginTop=\"10dp\"\u003e\n\n    \u003cTableRow\n        android:background=\"#607D8B\"\n        android:padding=\"5dp\"\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Version\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Version Name\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"API Level\" /\u003e\n    \u003c/TableRow\u003e\n\n    \u003cTableRow\n        android:background=\"#ECEFF1\"\n        android:padding=\"5dp\"\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"5.0\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Android Lollipop\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"21\" /\u003e\n    \u003c/TableRow\u003e\n\n    \u003cTableRow\n        android:background=\"#ECEFF1\"\n        android:padding=\"5dp\"\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"4.4\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Android Kitkat\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"19\" /\u003e\n    \u003c/TableRow\u003e\n    \u003cTableRow\n        android:background=\"#ECEFF1\"\n        android:padding=\"5dp\"\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"4.3\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Android Jelly Bean\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"18\" /\u003e\n    \u003c/TableRow\u003e\n\u003c/TableLayout\u003e\n```\n\nNow that we have declared the TableLayout layout, let is load this layout in the Activity `onCreate()` method\n\n```java\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n}\n```\n\nThe `SetContentView(int)` method loads the layout file for the Activity, specified by the layout resource Id.\n"])</script>
1<script>self.__next_f.push([1,"d9:Tfeb,"])</script>
1<script>self.__next_f.push([1,"\nThe TableLayout layout is an extension of LinearLayout. As the name indicates, TableLayout is used to display child View elements in rows and columns.\n\nThe concept of TableLayout works something similar to an HTML table. If you can recall the HTML table, TableLayout can be explained as \u003ctable\u003e tag and TableRow is like a \u003ctr\u003e element. You can use any view as table cell element.\n\nLet us create a TableView layout to display list of Android version releases. Each row contains three cells that represents version code, version name and API level. We are trying to achieve the same as the screenshot shown below.\n\n[![TableLayout Android Example](/media/articles/218/TableLayout-Android-Example.png)](http://stacktips.com)\n\n# Example\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cTableLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:layout_marginTop=\"10dp\"\u003e\n\n    \u003cTableRow\n        android:background=\"#607D8B\"\n        android:padding=\"5dp\"\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Version\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Version Name\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"API Level\" /\u003e\n    \u003c/TableRow\u003e\n\n    \u003cTableRow\n        android:background=\"#ECEFF1\"\n        android:padding=\"5dp\"\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"5.0\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Android Lollipop\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"21\" /\u003e\n    \u003c/TableRow\u003e\n\n    \u003cTableRow\n        android:background=\"#ECEFF1\"\n        android:padding=\"5dp\"\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"4.4\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Android Kitkat\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"19\" /\u003e\n    \u003c/TableRow\u003e\n    \u003cTableRow\n        android:background=\"#ECEFF1\"\n        android:padding=\"5dp\"\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"4.3\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Android Jelly Bean\" /\u003e\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"18\" /\u003e\n    \u003c/TableRow\u003e\n\u003c/TableLayout\u003e\n```\n\nNow that we have declared the TableLayout layout, let is load this layout in the Activity `onCreate()` method\n\n```java\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n}\n```\n\nThe `SetContentView(int)` method loads the layout file for the Activity, specified by the layout resource Id.\n"])</script>
1<script>self.__next_f.push([1,"da:T166a,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we will take a look into Android FrameLayout and creating layout through XML and from code programmatically.\n\nFrameLayout is one of the useful layout provided by the Android system, which allows User Interface widgets to be overlapped with each other.\n\nThe Linear Layout and RelativeLayout places the views adjacent to each other but, if you have to develop something as shown in the screenshot below, where the TextViews are placed on top of an ImageView. It is quite impossible to achieve using LinearLayout or RelativeLayout.\n\nIn FrameLayout, all the child views added are placed like a stack. The most recently added are shown on top. This means that developers must pay attention to the order of widgets while adding them to the layout.\n\n## Creating FrameLayout in XML\n\nOpen Android Studio and Create a new project. In this example, I have used `MyApplication` as the name of my application.\n\nAdd a new file called `activity_main.xml` and add the following code. To compile this code, you need to add a image with named image.jpg.\n\n```xml\n\u003cFrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cImageView\n        android:id=\"@+id/imageView1\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:scaleType=\"centerCrop\"\n        android:src=\"@drawable/photo\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView1\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center_horizontal\"\n        android:layout_marginTop=\"20dp\"\n        android:background=\"#00000c\"\n        android:padding=\"10dp\"\n        android:text=\"Fanny Hands Lane, London\"\n        android:textColor=\"#fafafa\"\n        android:textSize=\"22sp\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView2\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"right|bottom\"\n        android:layout_marginLeft=\"5dp\"\n        android:background=\"#AA000000\"\n        android:padding=\"10dp\"\n        android:text=\"26/Jan/2014\"\n        android:textColor=\"#FFFFFF\"\n        android:textSize=\"18sp\" /\u003e\n\n\u003c/FrameLayout\u003e\n```\n\nWe are almost done! All you have to do is now set the layout to your activity. you can do that by calling `setContentView(layoutID)` method inside onCreate(). Your activity code should look something similar to the following code snippets.\n\n```java\n//Your activity class\npublic class MainActivity extends Activity {\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n    }\n}\n```\n\nCompile and run The output of the code will look same as the screenshot below.\n\n[](http://stacktips.com/android/android-framelayout-example/attachment/frame-layout-android-example)\n\n## Creating FrameLayout Programmatically\n\nAndroid operating system provides list of API’s to create FrameLayout programmatically. Although most developers prefers to have layout as xml, but certain situations you might require view to be created programmatically. The following code snippet will show you how to achieve the same result as shown in the image above, from code.\n\nJust add the following code to your activity `onCreate()` method.\n\n```java\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n    super.onCreate(savedInstanceState);\n\n    //Initializing imageView\n    ImageView imageView = new ImageView(this);\n    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);\n    imageView.setImageResource(R.drawable.photo);\n    imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,\n                LayoutParams.MATCH_PARENT));\n\n    TextView textView1 = new TextView(this);\n    textView1.setText(\"Fanny Hands Lane, London\");\n    textView1.setTextSize(22);\n    textView1.setGravity(Gravity.CENTER_HORIZONTAL);\n    textView1.setTextColor(Color.parseColor(\"#fcfcfc\"));
1\n    textView1.setBackgroundColor((Color.parseColor(\"#00000c\")));\n    textView1.setPadding(10,10,10,10);\n    LayoutParams lp1 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,\n                Gravity.CENTER_HORIZONTAL);\n    lp1.setMargins(0,20,0,0);\n    textView1.setLayoutParams(lp1);\n\n    TextView textView2 = new TextView(this);\n    textView2.setTextSize(18);\n    textView2.setGravity(Gravity.RIGHT|Gravity.BOTTOM);\n    textView2.setText(\"26/Jan/2014\");\n    textView2.setTextColor(Color.WHITE);\n    textView2.setPadding(10,10,10,10);\n    textView2.setBackgroundColor(Color.BLACK);\n    LayoutParams lp2 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,\n                Gravity.BOTTOM|Gravity.RIGHT);\n    textView2.setLayoutParams(lp2);\n\n    //Initializing frame layout\n    FrameLayout framelayout = new FrameLayout(this);\n    framelayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,\n                LayoutParams.MATCH_PARENT));\n\n    //Adding views to FrameLayout\n    framelayout.addView(imageView);\n    framelayout.addView(textView1);\n    framelayout.addView(textView2);\n\n     setContentView(framelayout);\n}\n```\n\n### Key Points\n\n1.  The visibility of all child views added to FrameLayout, can be controlled programmatically by using `setVisiblity()` method.\n2.  `LayoutParams` are used by views to tell their parents how they want to be laid out. The base LayoutParams class just describes how big the view wants to be for both width and height.\n3.  The order in which the views are added to FrameLayout is important. Views may be hidden beneath, if we some other view added on top of it.\n"])</script>
1<script>self.__next_f.push([1,"db:Te81,"])</script>
1<script>self.__next_f.push([1,"\n## Introduction\n\nAndroid’s new operating system named Android Lollipop is highly focused on rich user experience and what they called it as material design. In this example, we will take a look at the new Actionbar replacement called Toolbar.\n\n## What is Toolbar?\n\nThe toolbar is a complete replacement to Android ActionBar. It provides greater control to customize its appearance, unlike old ActionBar. Using the Toolbar, the application developer can now, show multiple toolbars on the screen, spanning only part of the width, etc.\n\n[![Android Toolbar Example](/media/articles/220/Android-Toolbar-Example-620x331.png)](http://stacktips.com)\n\nScreenshot showing simple toolbar in android tablet and phone.\n\nIt is introduced in Android Lollipop, API level 21 release, and hence it is available to use, out of the box for the application that is targeted to 21 and above. However, as always Google provides fully supported Toolbar features to lower android os devices via AppCompact support library. In AppCompat, Toolbar is implemented in the `android.support.v7.widget.Toolbar` class.\n\nA Toolbar can be used in two ways.\n\n1.  Use a Toolbar as an replacement to ActionBar. In this you can still continued to use the ActionBar features such as menus, selections, etc.\n2.  Use a standalone Toolbar, where ever you want to place in your application.\n\n## Using Toolbar as ActionBar\n\nFollowing are simple steps you need to follow for implementing Toolbar as ActionBar replacement.\n\nFirst of all, you need to disable ActionBar. To do this, you need to extend your application theme from `Theme.AppCompat.NoActionBar` or if you are already using `Theme.AppCompact` theme, then just add below lines of code snippet\n\n```xml\n\u003c!-- Base application theme. --\u003e\n    \u003cstyle name=\"AppTheme\" parent=\"Theme.AppCompat\"\u003e\n        \u003citem name=\"android:windowNoTitle\"\u003etrue\u003c/item\u003e\n        \u003citem name=\"windowActionBar\"\u003efalse\u003c/item\u003e\n    \u003c/style\u003e\n```\n\nSecondly, add the App Compact V7 support support library. In this example, I am using Android Studio as the development IDE. You can add the V7 support library dependency to your application build.gradle file.\n\n```groovy\ndependencies {\n    compile fileTree(dir: 'libs', include: ['*.jar'])\n    compile \"com.android.support:appcompat-v7:21.0.+\"\n}\n```\n\nNow you need to add Toolbar to your Activity layout. Find the code snippet below for simple Toolbar Layout.\n\n```xml\n\u003candroid.support.v7.widget.Toolbar\n        android:id=\"@+id/toolbar\"\n        android:minHeight=\"?attr/actionBarSize\"\n        android:background=\"#2196F3\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\u003e\n    \u003c/android.support.v7.widget.Toolbar\u003e\n```\n\nApply the theme to Activity. Here in this step you need to apply the theme which we have created in step-1 to your activity. This can be done, by using `android:theme` attribute in your application AndroidManifest.xml.\n\n```xml\n\u003cactivity\n            android:name=\"com.javatechig.sample.MyActivity\"\n            android:label=\"@string/app_name\"\n            android:theme=\"@style/AppTheme\" \u003e\n\u003c/activity\u003e\n```\n\nNow you are almost ready. You just need to instantiate the Toolbar and add it to your activity by using `setSupportActionBar(Toolbar)` method.\n\n```java\nimport android.support.v7.app.ActionBarActivity;\nimport android.support.v7.widget.Toolbar;\n\npublic class MyActivity extends ActionBarActivity{\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_my);\n\n        // Set a toolbar to replace the action bar.\n        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\n        setSupportActionBar(toolbar);\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"dc:Tfa4,"])</script>
1<script>self.__next_f.push([1,"\nThe Strategy design pattern belongs to the behavioral family of pattern that deals with the change of the behavior of a class by changing the internal algorithm at runtime without modifying the class itself. This allows extensibility and loose coupling of objects. The definition of State Design Pattern as per the original Gang of Four book is;\n\n“Defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior.”\n\n### Use cases\n\nA data compression software like WinZip, provides different algorithms to perform gip, gzip, tar, jar, 7zip format. At runtime, the client chooses which type of algorithm to be performed.\n\nEmail client like outlook supports various email types such as plain text and HTML type. It allows the client to choose the email format.\n\n### How does Strategy Pattern Works?\n\nThe Strategy pattern is simple yet popular design pattern mostly works together with State pattern. Following are the steps involved to create strategy design pattern:\n\n1.  Implement a Strategy interface for your strategy objects. This interface defines the strategy object behavior.\n2.  Implement Concrete Strategy classes that implement the Strategy interface defined in the above step.\n3.  Create a Context class and maintain the reference to strategy object. Create a setter and getter method to allow access to a strategy object.\n\n### Strategy Design Pattern Example\n\nLet us take the example of a program that performs various number sorting algorithm such as Insertion sort, Selection Sort, Merge Sort etc. It allows the client to choose which type of sorting he would like to perform.\n\nThe above use case can be represented in the following class diagram\n\n[![Strategy Design Pattern Java](/media/articles/223/Strategy-Design-Pattern-Java.png)](http://stacktips.com)\n\n**SortingStrategy.java**\n\n```java\npublic interface SortingStrategy {\n\n    public void sort(int[] numbers);\n\n}\n```\n\n**SelectionSort.java**\n\n```java\npublic class SelectionSort implements SortingStrategy {\n\n    @Override\n    public void sort(int[] numbers) {\n        System.out.println(\"Selection Sort!\");\n\n        int i, j, first, temp;\n        for (i = numbers.length - 1; i \u003e 0; i--) {\n            first = 0;\n            for (j = 1; j \u003c= i; j++) {\n                if (numbers[j] \u003e numbers[first])\n                    first = j;\n            }\n            temp = numbers[first];\n            numbers[first] = numbers[i];\n            numbers[i] = temp;\n        }\n\n        System.out.println(Arrays.toString(numbers));\n    }\n}\n```\n\n**InsertionSort.java**\n\n```java\npublic class InsertionSort implements SortingStrategy {\n\n    @Override\n    public void sort(int[] numbers) {\n        System.out.println(\"Insertion Sort!\");\n\n        for (int i = 1; i \u003c numbers.length; i++) {\n            int temp = numbers[i];\n            int j;\n            for (j = i - 1; (j \u003e= 0) \u0026\u0026 (numbers[j] \u003e temp); j--) {\n                numbers[j + 1] = numbers[j];\n            }\n            numbers[j + 1] = temp;\n        }\n\n        System.out.println(Arrays.toString(numbers));\n    }\n}\n```\n\n```java\npublic class SortingContext {\n\n    private SortingStrategy strategy;\n\n    public void setSortingMethod(SortingStrategy strategy) {\n        this.strategy = strategy;\n    }\n\n    public SortingStrategy getStrategy() {\n        return strategy;\n    }\n\n    public void sortNumbers(int[] numbers){\n        strategy.sort(numbers);\n    }\n}\n```\n\n**TestMain.java**\n\nHere is how client using strategy pattern\n\n```java\npublic class TestMain {\n\n    public static void main(String[] args) {\n\n        int numbers[] = {20, 50, 15, 6, 80};\n\n        SortingContext context = new SortingContext();\n        context.setSortingMethod(new InsertionSort());\n        context.sortNumbers(numbers);\n\n        System.out.println(\"***********\");\n        context.setSortingMethod(new SelectionSort());\n        context.sortNumbers(numbers);\n\n    }\n}\n```\n\n**Output**\n\n```text\nInsertion Sort!\n[6, 15, 20, 50, 80]\n***********\nSelection Sort!\n[6, 15, 20, 50, 80]\n```\n"])</script>
1<script>self.__next_f.push([1,"dd:T141f,"])</script>
1<script>self.__next_f.push([1,"\nOver the course of this article, we will examine State design pattern in java with help of real-time examples.\n\nThe State design pattern belongs to the behavioral family of pattern that deals with the runtime object behavior based on the current state. The definition of State Design Pattern as per the original Gang of Four book is; “Allows an object to alter its behavior when its internal state changes. The object will appear to change its class”.\n\nHow does state pattern works:\n\n-   Define an object that represents various states that an object can be. Remember state machine.\n-   Define a context object, whose behavior varies as its state object changes.\n\n### Use cases\n\nState pattern is one of the heavily used patterns in game development. The game character can be in different states such as healthy, surviving and dead. When the character is healthy, it allows the user to fires at enemies with different weapons. When surviving state its health gets critical, and when its health reaches to 0, the character is said to be in the dead state where the game is over.\n\nLet us implement this use case without using the State design pattern. It can be achieved by using set of if else conditional checks, as shown in the following code snippets.\n\n### Player.java\n\nThe Player class defines the different actions a player can perform.\n\n```java\npublic class Player {\n\n    public void attack() {\n        System.out.println(\"Attack\");\n    }\n\n    public void fireBumb() {\n        System.out.println(\"Fire Bomb\");\n    }\n\n    public void fireGunblade() {\n        System.out.println(\"Fire Gunblade\");\n    }\n\n    public void fireLaserPistol() {\n        System.out.println(\"Laser Pistols\");\n    }\n\n    public void firePistol() {\n        System.out.println(\"Fire Pistol\");\n    }\n\n    public void survive() {\n        System.out.println(\"Surviving!\");\n    }\n\n    public void dead() {\n        System.out.println(\"Dead! Game Over\");\n    }\n\n}\n```\n\nNow let us define our game context class which defines the different actions conditionally depends on the state of the player.\n\n### GameContext.java\n\n```java\npublic class GameContext {\n\n    private Player player = new Player();\n\n    public void gameAction(String state) {\n        if (state == \"healthy\") {\n            player.attack();\n            player.fireBumb();\n            player.fireGunblade();\n            player.fireLaserPistol();\n        } else if (state == \"survival\") {\n            player.survive();\n            player.firePistol();\n        } else if (state == \"dead\") {\n            player.dead();\n        }\n    }\n}\n```\n\nIn the above code snippet, the gameAction method contains too many conditional blocks for performing the different game action based on the state of the player. This is a real problem of code maintainability. this can be avoided using the State design pattern.\n\n# State Design Pattern Example\n\nBefore we begin with the state design pattern, let us have a look into the class design.  \n[![State Design Pattern Java](/media/articles/224/State-Design-Pattern-Java.png)](http://stacktips.com)1. Define an interface named PlayerState that defines an action method. The access() method takes the instance of Player class. This is required to perform the player action.\n\n```java\npublic interface PlayerState {\n    void action(Player p);\n}\n```\n\n2. Define three different classes that represent the different states. In this example, I have named them as, `HealthyState``, SurvivalState``DeadState`. All three classes implement the `PlayerState`interface and provides the specific `action()` method implementation.\n\n```java\npublic class HealthyState implements PlayerState {\n\n    @Override\n    public void action(Player p) {\n        p.attack();\n        p.fireBumb();\n        p.fireGunblade();\n        p.fireLaserPistol();\n    }\n}\n\npublic class SurvivalState implements PlayerState {\n\n    @Override\n    public void action(Player p) {\n        p.survive();\n        p.firePistol();\n    }\n}\n\npublic class DeadState implements PlayerState {\n\n    @Override\n    public void action(Player p) {\n        p.dead();\n    }\n}\n```\n\n3. The `GameContxt` class contains two `setState()` method composition. Now we will remove all of the code to conditional logic.\n\n```java\npublic class GameC
1ontext {\n\n    private PlayerState state = null;\n    private Player player = new Player();\n\n    public void setState(PlayerState state) {\n        this.state = state;\n    }\n\n    public void gameAction() {\n        state.action(player);\n    }\n}\n```\n\n4. That’s All! Let us test our code using below class.\n\n```java\npublic class GameTest {\n\n    public static void main(String[] args) {\n\n        GameContext context = new GameContext();\n\n        context.setState(new HealthyState());\n        context.gameAction();\n        System.out.println(\"*****\");\n\n        context.setState(new SurvivalState());\n        context.gameAction();\n        System.out.println(\"*****\");\n\n        context.setState(new DeadState());\n        context.gameAction();\n        System.out.println(\"*****\");\n\n    }\n}\n```\n\n### Output\n\n```text\nAttack\nFire Bomb\nFire Gunblade\nLaser Pistols\n*****\nSurviving!\nFire Pistol\n*****\nDead! Game Over\n*****\n```\n"])</script>
1<script>self.__next_f.push([1,"de:T1835,"])</script>
1<script>self.__next_f.push([1,"\nOver the course of this article, we will examine the Template Method design pattern in java with help of real-time examples.\n\nThe template method design pattern belongs to the behavioral family of patterns that defines the steps for an algorithm and allows the subclass to provide the implementation for one or more steps. This design pattern helps in maximizing the code reusability.\n\n### How does the Template Method Works?\n\n1.  Define an abstract base class with some fully qualified method containing common implementation logic\n2.  Declare the abstract methods for subclasses to override specific behaviors\n3.  Declare a **Template method** in a superclass that holds the core algorithm implementation steps\n4.  Derived classes can override placeholder methods\n5.  Derived classes can override implemented methods\n\n### Use Case\n\nLet us take the example of a Pizza Store. The making of a Pizza includes the steps such as selection of bread, add ingredient, heating, add toppings and add cheese. All these steps are in sequential order. Let us implement this use case in Template Method design representation.\n\n[![Template Method Design Pattern Example](/media/articles/226/Template-Method-Design-Pattern-Example-620x406.png)](http://stacktips.com)\n\nThe above use case is represented in the following class diagram.\n\n1.  We have declared an abstract base class for all `Pizza` implementation. The Pizza store currently serves two variants of pizzas; `SweetCornPizza` and `MexicanPizza`. Both classes extends Pizza class.\n2.  Pizza class contains the `chooseBread()`, `addIngredients()` abstract methods. Each of the Pizza implementation will override them to provide specific implementation logic.\n3.  The `heating()`, `addTopinngs()` and `addCheese()` methods are common for all Pizza types and hence their implementation is commonly provided in Pizza super class.\n4.  Pizza superclass defines `preparePizza()` template method that controls the order that all other methods are called.\n5.  Note that preparePizza() method is declared as final, because we don’t want client to override/change the pizza preperation steps.\n\nThat’s all! We are ready with the Template Method design. Lets us have a glance at the code snippet below.\n\n#### Pizza.java\n\n```java\npublic abstract class Pizza {\n    public abstract void chooseBread();\n    public abstract void addIngredients();\n\n    public void heating() {\n        System.out.println(\"Heating for 10 minutes!\");\n    }\n\n    public void addTopinngs() {\n        System.out.println(\"Adding Topinngs!\");\n    }\n\n    public void addCheese() {\n        System.out.println(\"Adding Cheese!\");\n    }\n\n    // Template method\n    public final void preparePizza() {\n        chooseBread();\n        addIngredients();\n        heating();\n        addCheese();\n        addTopinngs();\n    }\n}\n```\n\n#### SweetCornPizza.java\n\n```java\npublic class SweetCornPizza extends Pizza {\n    @Override\n    public void chooseBread() {\n        System.out.println(\"Choosing SweetCorn Pizza Bread!\");\n    }\n\n    @Override\n    public void addIngredients() {\n        System.out.println(\"Adding SweetCorn Pizza Ingredients!\");\n    }\n}\n```\n\n#### MexicanPizza.java\n\n```java\npublic class MexicanPizza extends Pizza {\n    @Override\n    public void chooseBread() {\n        System.out.println(\"Choosing Mexican Pizza Bread!\");\n    }\n\n    @Override\n    public void addIngredients() {\n        System.out.println(\"Adding Mexican Pizza Ingredients!\");\n    }\n}\n```\n\n#### TestMain.java\n\n```java\npublic class TestMain {\n    public static void main(String[] args) {\n        SweetCornPizza pizza1 = new SweetCornPizza();\n        pizza1.preparePizza();\n\n        System.out.println(\"**********\");\n\n        MexicanPizza pizza2 = new MexicanPizza();\n        pizza2.preparePizza();\n    }\n}\n```\n\n#### Output\n\n```text\nAdding SweetCorn Pizza Ingredients!\nHeating for 10 minutes!\nAdding Cheese!\nAdding Toppings!\n************\nChoosing Mexican Pizza Bread!\nAdding Mexican Pizza Ingredients!\nHeating for 10 minutes!\nAdding Cheese!\nAdding Toppings!\n```\n\n### Did you know?\n\n1.  The Template method should be declares as final to avoid its subclass overriding its implementation logic.\n2.  The template method in a super class follows the [Hollywood principle](http://en.wikipedia.org/wiki/Hollywood_principle), _Don’t call us, we’ll call you._ This refers to the fact that instead of calling the base class methods in the subclasses, the methods from the subclass are called form super class template method.\n\n### Problem – 1\n\nSo far our pizza store works great. But now based on the customer demand the Pizza store is willing to introduce two new pizza types DoubleCheesePizza and NoCheesePizza.\n\nIn Order to supp
1ort Double Cheese Pizza, we can override the addCheese() method in DoubleCheesePizza class and provide double cheese specific implementation here.\n\n#### DoubleCheesePizza.java\n\n```java\npublic class DoubleCheesePizza extends Pizza {\n    @Override\n    public void chooseBread() {\n        System.out.println(\"Choosing DoubleCheese Pizza Bread!\");\n    }\n\n    @Override\n    public void addIngredients() {\n        System.out.println(\"Adding DoubleCheese Pizza Ingredients!\");\n    }\n\n    @Override\n    public void addCheese() {\n        System.out.println(\"Adding Double Cheese!\");\n    }\n}\n```\n\nHowever, for No cheese pizza the current design will fail to support. We have to introduce hook methods to achieve the same.\n\n1.  Add `isCheese()` method in Pizza class that execute `addCheese()` method conditionally.\n2.  Change the following code in `preparePizza()` method.\n\n```java\npublic boolean isCheese(){\n    return true;\n}\n\n// Template method\npublic final void preparePizza() {\n    chooseBread();\n    addIngredients();\n    heating();\n\n    if(isCheese()){\n        addCheese();\n    }\n    addTopinngs();\n}\n```\n\n#### NoCheesePizza.java\n\n```java\npublic class NoCheesePizza extends Pizza {\n    @Override\n    public void chooseBread() {\n        System.out.println(\"Choosing SweetCorn Pizza Bread!\");\n    }\n\n    @Override\n    public void addIngredients() {\n        System.out.println(\"Adding SweetCorn Pizza Ingredients!\");\n    }\n\n    @Override\n    public boolean isCheese() {\n        return false;\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"df:T2170,"])</script>
1<script>self.__next_f.push([1,"\n### What are Design Patterns?\n\nPatterns exist everywhere in the world. In culinary, art, medicine, law, mathematics, music, dancing and the list goes on. Generally, a pattern is identified as a recurring arrangement created to solve some generalized problem. It is simply a solution outline, but not the solution itself. In more formal words, a pattern is a generalized outline of a reusable solution to a recurring problem.\n\n\u003e A software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.  \n\u003e — Wikipedia\n\nIn software development, design patterns are the well-described solution to some of the common recurring problems you may face while designing your software. Design patterns are the concepts that outline the solution approach but not the solution itself and hence they are platform and language independent.\n\nThere are many design patterns identified and available today. It is almost impossible for an individual to know about each and every design pattern present. However, a developer with knowledge of the Foundational design patterns known as GOF (Gang-Of-Four) will make him efficient on his day to day job.\n\n### Why Design Patterns?\n\nSome of the benefits of using design patterns are:\n\n-   Design patterns are already defined and provide an industry standard approach to solve the recurring problem, so it saves time.\n-   Using design pattern promotes re-usability that leads to more robust and highly maintainable code.\n-   Since design patterns are already defined, it makes out code easy to understand and debug. It leads to faster development and new members of the team understand it easily.\n\n### Characteristics of a Good Design\n\nWhile designing your application, you should be conscious of various software design characteristics. A great design would have all the characteristic.\n\nHowever, it is practically not possible, as sometimes one pattern contradicts to other, so you have to make a hit a middle ground and choose one over other.\n\nFollowing are some of the characteristics for a good software design:\n\n#### Ease of maintenance\n\nThe software is always highly unstable. It is expected to undergo maintenance and changes in the feature. The design should be self-explanatory and easy to understand for other programmers.\n\n#### Minimal complexity\n\nSimplicity is the soul of efficiency (– Austin Freeman).\n\nDesign for simplicity. A complex design is often difficult to extend, maintain and understand. There are factors like many interconnections and relations, non-trivial algorithm, behaviors or rules, etc. causes the complexity in design.\n\n#### Loose coupling\n\nAll components in your design should be loosely coupled to the maximum extent possible. This will make the system modularized and each component can be tested separately before it is integrated into a larger system.\n\nYou should be able to change a piece of the system without affecting another. If there is a defect in one component in your software, then it won’t bug much to the other components. This can be done with the basic Object-Oriented Programming Principles (OOP) like encapsulation, information hiding, and abstractions.\n\n#### Portability\n\n_Portability_ is a characteristic attributed to a computer program when it can work on another environment other than the one in which it was created without requiring major rework.\n\n#### Stratification and reusability\n\nDesign patterns encourage design reuse. Design software component, that can be easily used in other system or software.\n\nFor example, if you look at the android design (Image below), it provides multiple layers of abstractions. Each component is independent of other and provides a great level of reusability.\n\n#### Standard techniques\n\nDon’t hate things, because you don’t know or you don’t like them. Before designing your software evaluate and use the industry suggested patterns that are appropriate for your requirements.\n\n## Foundational (Gang-of-Four) Design Patterns\n\nGang-Of-Four also called as foundation patterns are the 23 basic design patterns that provide a solution to commonly recurring problems in software design. They are categorized 
1into three major categories; Creational, Structural and Behavioral pattern based on behavior and characteristics.\n\n### 1. Creational design patterns\n\nThis category provides patterns to resolve the problems of object creation in flexible ways. These will eliminate the difficulties in object instantiation and enables enable greater levels of reuse in evolving systems.\n\n| Abstract Factory | Provides an interface for creating families of related or dependent objects without specifying their concrete classes. |\n| --- | --- |\n| Builder | Separates the construction of a complex object from its representation so that the same construction process can create different representations. |\n| Factory Method | Provides a way to use an instance as an object factory. The factory can return an instance of one of several possible classes in a class hierarchy, depending on the data provided to it. |\n| Prototype | Prototype is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. In a simpler term, using prototype pattern, we will create new instances through cloning existing instances. |\n| Singleton | Singleton pattern ensures at most one instance of a particular class is ever created in your application. |\n\n### 2. Structural design patterns\n\nThis category provides patterns to resolve the problems of object structure and composition. These will help to identify a simple way to realize relationships between entities.\n\n| Adapter | Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. |\n| --- | --- |\n| Bridge | Decouple an abstraction from its implementation so that the two can vary independently. |\n| Composite | Compose objects into a tree structure to represent part-whole hierarchies. Composite lets client treat individual objects and compositions of objects uniformly. |\n| Decorator | Allows for the dynamic wrapping of objects in order to modify their existing responsibilities and behaviors. |\n| Facade | Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use. |\n| Flyweight | Facilitates the reuse of many fine-grained objects, making the utilization of large numbers of objects more efficient. |\n| Proxy | Allows for object-level access control by acting as a pass-through entity or a placeholder object. |\n\n### 3. Behavioral design patterns\n\nThis category provides patterns to resolve the problems of common communication patterns between objects. These will use to manage algorithms, relationships, and responsibilities between objects.\n\n| Chain of Responsibility | Gives more than one object an opportunity to handle a request by linking receiving objects together. |\n| --- | --- |\n| Command | Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. |\n| Interpreter | Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. |\n| Iterator | Provides a way to access the elements of an aggregate object without exposing its underlying representation. |\n| Mediator | Allows loose coupling by encapsulating the way disparate sets of objects interact and communicate with each other. Allows for the actions of each object set to vary independently of one another. |\n| Memento | Captures and externalizes an object’s internal state so that it can be restored later, all without violating encapsulation. |\n| Observer | Observer design pattern defines One-to-Many dependency between objects in which one object changes state, all its dependents are notified. |\n| State | Allows an object to alter its behavior when its internal state changes. The object will appear to change its class. |\n| Strategy | Defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior. |\n| Template Method | Defines the steps for an algorithm and allows a 
1subclass to provide an implementation for one or more steps. |\n| Visitor | Allows for one or more operation to be applied to a set of objects at runtime, decoupling the operations from the object structure. |\n"])</script>
1<script>self.__next_f.push([1,"e0:Ta27,"])</script>
1<script>self.__next_f.push([1,"\nBefore begin writing your first Java program, you need to have your development environment ready. For writing and executing Java program, you need the latest version of Java SDK installed installed and configured on your machine;\n\nNow, let us create an example class that simply prints “Hello World!” on standard output terminal.\n\n```java\n/* My first java program prints “Hello World!” */\nclass HelloWorldApp {\n    public static void main(String[] args) {\n       //Prints string hello world\n        System.out.println(\"Hello World!\");\n    }\n}\n```\n\nThe “Hello World!” application consists of three primary components:\n\n1.  Source code comments\n2.  The HelloWorldApp class definition\n3.  The main method\n\n### Source Code Comments\n\nComments are ignored by the compiler but are useful for readability purpose. The Java programming language supports three kinds of comments such as, single line, multiline and documentation type comments.\n\n-   **// text** – The compiler ignores everything from // to the end of the line.\n-   **/\\* text \\*/** – This indicates multiline comments. The compiler ignores everything from /\\* to \\*/.\n-   **/\\*\\* documentation \\*/** – This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /\\* and \\*/.\n\nThe following bold text defines the comments of the “Hello World!” application:\n\n```java\n/* My first java program prints “Hello World!” */\nclass HelloWorldApp {\n    public static void main(String[] args) {\n        //Prints string hello world\n        System.out.println(\"Hello World!\");\n    }\n}\n```\n\n### The HelloWorldApp Class Definition\n\nThe following bold text begins the class definition block for the “Hello World!” application:\n\n```java\n/* My first java program prints “Hello World!” */\nclass HelloWorldApp {\n    public static void main(String[] args) {\n        //Prints string hello world\n        System.out.println(\"Hello World!\");\n    }\n}\n```\n\nAs shown above, the most basic form of a class definition is `class \u003cClass Name\u003e` followed by curly braces. The keyword `class` begins the class definition for a class named name, and the code for each class appears between the opening and closing curly braces marked in bold above.\n\n### The main Method\n\nThe following bold text begins the definition of the main method:\n\n```java\n/* My first java program prints “Hello World!” */\nclass HelloWorldApp {\n    public static void main(String[] args) {\n       //Prints string hello world\n        System.out.println(\"Hello World!\");\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"e1:T19cd,"])</script>
1<script>self.__next_f.push([1,"\nThis post will walk you through crating a custom ListView in Xamarin.Android using list adapter.\n\nListView is one of the most common UI pattern, used extensively to display collection of data elements in rows. Android ListView is a view group that displays a list of scrollable items.\n\nThe list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array. Find out more about android `ListView` and `ListAdapters` from Android ListView Tutorial.\n\nFollowing are the steps involved in using ListView in your application\n\n1.  Declare ListView layout\n2.  Declare list row layout\n3.  Define ListView Adapter\n4.  Setting ListView Adapter\n5.  Handle list click event\n\n# 1. Declare ListView layout\n\nBefore using list in your application, you first need to declare its layout inside your activity or fragment. For the sake of simplicity, in the below code snippet, we have declared ListView inside activity layout file.\n\n#### ListActivity.axml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:orientation=\"vertical\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\u003e\n    \u003cListView\n        android:minWidth=\"25px\"\n        android:minHeight=\"25px\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:id=\"@+id/ListView\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\nThe property `android:id=\"@+id/IntentoryList\"` in the above code snippet is the id assigned to ListView. This id will be used to initialize this from activity cs file.\n\n# 2. Declare list row layout\n\nIn the above step we have declared ListView layout. Now it is the time to define the layout for list row item. This layout will be used by list adapter.\n\n#### ListItemRow.axml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:minHeight=\"50dp\"\n    android:orientation=\"horizontal\"\u003e\n    \u003cImageView\n        android:id=\"@+id/Thumbnail\"\n        android:layout_width=\"70dp\"\n        android:layout_height=\"70dp\"\n        android:paddingLeft=\"10dp\"\n        android:layout_alignParentLeft=\"true\"\n        android:layout_centerVertical=\"true\"\n        android:src=\"@drawable/Placeholder\" /\u003e\n    \u003cTextView\n        android:id=\"@+id/Title\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_toRightOf=\"@id/Thumbnail\"\n        android:lineSpacingExtra=\"3dp\"\n        android:paddingLeft=\"10dp\"\n        android:paddingTop=\"5dp\"\n        android:textColor=\"#ffffff\"\n        android:textStyle=\"bold\"\n        android:typeface=\"sans\" /\u003e\n    \u003cTextView\n        android:id=\"@+id/Description\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_below=\"@+id/Title\"\n        android:layout_toRightOf=\"@id/Thumbnail\"\n        android:paddingLeft=\"10dp\"\n        android:paddingTop=\"5dp\"\n        android:textColor=\"#fff\"\n        android:textSize=\"11sp\" /\u003e\n\u003c/RelativeLayout\u003e\n```\n\n# 3. Define ListView Adapter\n\nAdapter is a tricky part while creating ListView. BaseAdapter is a common Adapter that can be used in both ListView, GridView or Spinners. An adapter takes list of data objects as input, and each object in the list is mapped to a list row. Adapter also inflates the layout to be rendered for each row items.\n\nIn our example, `CusotmListAdapter` takes list of Post objects. The structure of Post class as described below.\n\n```csharp\npublic class Post\n{\n    public string url { get; set; }\n    public string title { get; set; }\n    public string description { get; set; }\n}\n```\n\nThe post class contains three fields; a url, title and a description. In this example we will not cover much on how to get the data source, you may hardcode or write some logic to download data form server. Now lets move to our list adapter implementation.\n\n```csharp\npublic class CusotmListAdapter : BaseAdapter\u003cPost\u003e\n{\n    Activity context;\n    List\u003cPost\u003e list;\n\n    public CusotmListAdapter (Activity _context, List\u003cPost\u003e _list)\n        :base()\n    {\n        this.context = _context;\n        this.list = _list;\n    }\n\n    public override int Count {\n        get { return list.Count; }\n    }\n\n    public override long GetItemId (int position)\n    {\n        return position;\n    }\n\n    public override Post this[int index] {\n        get { return list [index]; }\n    }\n\n    public override View GetView (int position, View convertView, ViewGroup parent)\n    {\n        View view = convertView;\n\n        // re-use an existing view, if one is available\n        // otherwise create a new one\n        if (view == null)\n            view = context.LayoutInflater.Inflate (Resource.Layout.ListRowLayout, parent, false);\n\n        Post item = this [position];\n        view.FindViewById\u003cTextView\u003e (Resource.Id.Title).Text = item.title;\n        view.FindViewById\u003cTextView\u003e(Resource.Id.Description).Text = item.description;\n\n        using (var imageView = view.FindViewById\u003cImageView\u003e (Resource.Id.Thumbnail)) {\n            str
1ing url = Android.Text.Html.FromHtml (item.thumbnail).ToString ();\n\n            //Download and display image\n            Koush.UrlImageViewHelper.SetUrlDrawable (imageView,\n                url, Resource.Drawable.Placeholder);\n        }\n        return view;\n    }\n}\n```\n\n1.  You must override the Count, GetItemId and GetView method in your BaseAdapter class implementation. The `Count` method indicates the total number of rows in the list, `GetItemId` represent a unique id for reach item in the list. `GetView` inflates layout for each list row and render on the screen.\n2.  In this example, we have used [UrlImageViewHelper](http://components.xamarin.com/gettingstarted/urlimageviewhelper) component. You may download the same form component store and add to your project.\n\n# 4. Setting ListView Adapter\n\nOnce your list adapter is ready, then you are almost done with your ListView implementation. Now all you need to do is to instantiate the adapter and setting to ListView.\n\n```csharp\n//Initializing listview\nlistView = FindViewById (Resource.Id.feedList);\nlistView.ItemClick += OnListItemClick;\nlistView.Adapter = new CusotmListAdapter(this, listData);\n```\n\nYou can handle ListView click event by adding `ItemClick` callback.\n\n```csharp\nvoid OnListItemClick(object sender, AdapterView.ItemClickEventArgs e) {\n    Post item = result.posts.ElementAt (e.Position);\n    // Do whatever you like here\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"e2:T11ed,"])</script>
1<script>self.__next_f.push([1,"\nORM stands for Object Relational Mapping. SQLite.NET ORM is an light weight and open source library that allows .NET and Mono application to store data in SQLite database. This is available as a free component in Xamarin component store. SQLite.NET supports for Android, iOS and Windows platform, and hence the database operation logic can shared across platforms. Some of the key features of SQLite.NET ORM includes\n\n1.  Easy to ingrate component available to use in existing Xamarin project\n2.  It is an light weight thin wrapper, and is efficient without performance trade-off\n3.  Support simple CURD operations and support for simple, complex SQL quires\n\n# How to use SQLite.NET?\n\nThere are two approaches to integrate SQLite.NET ORM in Xamarin application\n\n### Downloading from Github\n\nSQLite.NET is a very thin library with single file. You can download `SQLite.cs` file from [Github](https://github.com/praeclarum/sqlite-net/blob/master/src/SQLite.cs) and add into your application. SQLite.NET library binds directly to the native device SQLite database engine on each platform.\n\n### Adding from component store\n\nSQLite.NET is listed free Xamarin Component Store and available for both iOS and Android platform. To include this into your Xamarin Studio project, you can , either double-click on the Components folder in the solution pad, or and right click to select Component Manager.\n\nYou will notice that the component manager will be loaded with already downloaded components and you can open Component store from the window. Accessing component manager requires log in to your Xamarin account. Once logged, you can browse through available components and add them to project.\n\n[![SQLite.NET-ORM-in-Xamarin-Component-Store](/media/articles/235/SQLite.NET-ORM-in-Xamarin-Component-Store.png)](http://stacktips.com)\n\n# SQLite.NET Example\n\nOnce the component is added to your Xamarin project, you are good to use this library to write SQL operations.\n\n## Creating a database\n\nBefore you can store data into SQLite, you first need to create a database, if not created already. Create a blank database or open existing by passing the file path the SQLiteConnection class constructor.\n\n```csharp\nprivate string DbName = \"Intentory_DB.db\";\nstring path = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);\nSQLiteConnection dbConn = new SQLiteConnection (System.IO.Path.Combine (path, DbName));\n```\n\n1.  Depending on what platform you are targeting the file location will be different. For iOS and Android you can use Environment class as shown in the above code snippet, to construct a valid path\n2.  The `new SQLiteConnection` opens the database file, if the file under mentioned path is already available, else it will create a new database.\n3.  Once your database connection is opened, you can execute the following methods to command different database operations.\n\n## Creating a table\n\nIn this example, we will be storing items to Inventory table. Below is the structure of Inventory class. As you can see in the code snippet below, we have declared different SQL attributes to Inventory class model.\n\n```csharp\nclass Inventory\n{\n    [PrimaryKey, AutoIncrement]\n    public int Id { get; set; }\n\n    [NotNull]\n    public int ItemCode { get; set;}\n\n    public String Name{ get; set;}\n    public String Category { get; set;}\n    public double Price{ get; set;}\n    public bool StockAvailable { get; set;}\n}\n```\n\nOnce you have your model ready, you can invoke the below methods to create table, if not exist already.\n\n```csharp\ndbConn.CreateTable ();\n```\n\n## Insert into database\n\n```csharp\n//Creating inventory object for storing into db\nInventory newInventory = new Inventory ();\nnewInventory.ItemCode = Convert.ToInt32(ItemCode.Text);\nnewInventory.Name = ItemName.Text;\nnewInventory.Category = ItemCategory.Text;\nnewInventory.Price = Convert.ToDouble(ItemPrice.Text);\nnewInventory.StockAvailable = IsStockAvailable.Checked;\n\n//Inserting record into database\ndbConn.Insert (newInventory);\n```\n\n## Retrieve data from database\n\nUse the following syntax to retrieve all the records from database\n\n```csharp\nIEnumerable\u003cInventory\u003e table = dbConn.Table\u003cInventory\u003e ();\nforeach (Inventory s in table) {\n    Console.WriteLine (s.ItemCode + \" \" + s.Name);\n}\n```\n\nTo retrieve object by primary key, you can use following code syntax.\n\n```csharp\n//3 is primary key\nvar item = db.Get\u003cInventory\u003e(3);
1\n```\n\n## Update record into database\n\n```csharp\n//Inserting record into database\ndbConn.Update (item);\n```\n\n## Delete from database\n\n```csharp\ndbConn.Delete (item);\n```\n"])</script>
1<script>self.__next_f.push([1,"e3:Td24,"])</script>
1<script>self.__next_f.push([1,"\nMost of the commercial mobile application uses local storage for large data processing and to improve efficiency. While mobile applications are limited with memory and processing, the way you store, manage and process on data it is always been very tricky. Think a bit, before jumping straight into designing a database for your application.\n\nBoth Android and iOS platform provides different mechanism to deal with data storage. You must understand each of the option to choose one over other. Following are some of the available data storage mechanisms for mobile mobile platforms like Android and iOS.\n\n## 1. Key Value Preferences\n\nPreferences are most used way to store simple data of key value pair. They are local to your application, you will loose the data once the application is deleted from device. This option of data storage is preferred for storing application rationalization information. In Android it is named as shared preferences and in iOS it is called NSUserDefaults. Additionally iOS users can take advantage of iCloud technology for data backup and synchronization in multiple devices.\n\nHere is the link to [Shared preference in Xamarin.Android example](http://stacktips.com/xamarin/sharedpreferences-example-in-xamarin-android) , that might intrest you.\n\n## 2. Text Files / Serialized Data Files\n\nText file is most easiest and convenient way to sore data such content downloaded from server. You may use different data encryption mechanism for ensuring the data security.\n\nObjects can be serialized and persisted as XML or JSON on the file-system. The .NET framework includes libraries that make serializing and de-serializing objects easy. Use appropriate names to organize data files.\n\n## 3. Database\n\nSQLite is an Open-Source embedded SQL database engine built available on both iOS and Android platforms. SQLite provides relational database management structure for storing user defined records in the form of tables. SQLite is light weight when it comes to resource usage and it doesn’t need to have any server setup like other RDBMS systems. It is an cross platform and self-contained database. Database storage is suited to lists of data with many properties.\n\nFollowing are some of the advantages of using SQL database engine\n\n1.  SQL databases structured and efficient for storing data\n2.  Allows simple and complex queries, that helps to extract specific data\n3.  Query results can be sorted\n4.  Query results can be aggregated\n5.  Similar to other RDBMS, which helps developers to utilize existing knowledge in database design\n6.  Allow application to pre-package with database\n\nYou may take advantage of the ready to use ORM (Object Relational Mapping) such as SQLite.NET components from Xamarin Component store for quick integration for SQLite storage. Here is the link to S[QLite.NET components integration example](http://stacktips.com/xamarin/using-sqlite-net-orm-in-xamarin-application \"Using SQLite.NET ORM in Xamarin Application\"), that might intrest you.\n\n## 4. Image files\n\nAs mobile devices are limited with memory, it is highly recommended not to use database for storing large size images. Images must be stored into device file-system and only the mapping file name can be stored into database. If you’re dealing with many images in your application, it is a good practice to have image caching logic in place.\n"])</script>
1<script>self.__next_f.push([1,"e4:T1289,"])</script>
1<script>self.__next_f.push([1,"\nXamarin is a San Francisco, California based software company which provides commercial software development tools that leverage the Mono open source project in order to allow you to develop applications for Android, iOS, and OS X using C# and the .NET framework.\n\nFind links to Xamarin learning resources and some of the popular Xamarin development books. If you want to list down your blog or book on this page then please comment below.\n\n### Xamarin Learning Resources\n\nBelow are some of the Xamarin learning web portals, provides examples, source code and step by step guide for developers to learn Xamarin from scratch.\n\n#### API Documentation\n\n[1. iOS API Documentation](http://iosapi.xamarin.com/ \"iOS Xamarin API documentation\")  \n[2. Android API Documentation](http://androidapi.xamarin.com/)  \n[3. Mac API Documentation](http://macapi.xamarin.com/)  \n[4. TestCloud Documentation](http://developer.xamarin.com/guides/testcloud/apis)\n\n#### Xamarin Tutorials\n\n[1. Xamarin Developer Website](http://developer.xamarin.com/guides/ios/getting_started/)  \n[2. Microsoft MSDN Site](http://blogs.msdn.com/)  \n[3. XamarinAppDev.com](http://xamarinappdev.com/ \"XamarinAppDev.com\")  \n[2. MvvmCross Github](https://github.com/MvvmCross/MvvmCross/wiki \"MvvmCross Github\")\n\n### Xamarin Development Books\n\n* * *\n\n[\u001b](http://stacktips.com)[![Xamarin+Mobile+Application+Development+for+Android+second](/media/articles/237/Xamarin-Mobile-Application-Development-for-Android-second-300x356.jpg)](http://stacktips.com)[  \n](http://stacktips.com)  \n\n### Xamarin Mobile Application Development for Android – Second Edition\n\n## About This Book\n\n-   Build and test multi-view Android applications using Xamarin.Android\n-   Work with device capabilities such as location sensors and the camera\n-   A progressive, hands-on guide to develop stunning Android applications using Xamarin\n\n## Who This Book Is For\n\nIf you are a C# developer who wants to develop Android apps and enhance your existing skill set, then this book is ideal for you. Good working knowledge of C#, .NET, and object-oriented software development is assumed.\n\n## What You Will Learn\n\n-   Build a multi-view, orientation-aware Android application with navigation\n-   Lay out content using the LinearLayout, RelativeLayout, and TableLayout layout managers\n-   Use a ListView (AdapterView) and Adapter to build a view that is populated from server data\n-   Consume REST web service to perform GET, UPDATE, DELETE operation\n-   Use Android SQLite for data persistence and caching\n-   Capture the current location of a device, determine the street address, and integrate with the map app\n-   Test, debug, and deploy an Android app\n\n[Download this book from Amazon](http://www.amazon.com/Xamarin-Mobile-Application-Development-Android-ebook/dp/B00YSIM3UU/ref=sr_1_1?s=books\u0026ie=UTF8\u0026qid=1449238693\u0026sr=1-1\u0026keywords=Xamarin+Mobile+Application+Development+for+Android+second)\n\n* * *\n\n[![Xamarin form](/media/articles/237/Xamarin-Forms.png)](http://stacktips.com)  \n\n### Creating Mobile Apps with Xamarin.Forms\n\nThe preview edition contains six chapters:\n\n-   How does Xamarin.Forms fit in?\n-   Pages, layouts, and views\n-   Building an app: Infrastructure\n-   Building an app: Architecture\n-   Principles of presentation\n-   The interactive interface\n\nThis is only the beginning – the completed book will cover all aspects of Xamarin.Forms from the various layout and styling options to extending functionality using native APIs. Preview edition is now available for [download](http://developer.xamarin.com/guides/cross-platform/xamarin-forms/creating-mobile-apps-xamarin-forms/#Download_Now).\n\n* * *\n\n[![Xamarin Mobile Application Development for iOS](/media/articles/237/Xamarin-Mobile-Application-Development-for-iOS.jpg)](http://stacktips.com)  \n\n### Xamarin Mobile Application Development for iOS\n\nThe book begins by discussing the installation of the IDE (for both PC and Mac) as well as how to set up your PC so it can be used to develop for iOS. From there, successive chapters cover the user interface, views, view controllers, customisation of controls, animation, events and event handling, getting the most from your app using threading, creating your own settings system, the internal database system and LINQ, sending texts, making calls, taking photos, videos, and audio recordings as well as using the mapping system. The book culminates by showing you how to test your app using testflight and finally how to release your app on the Apple Store. It is an all-encompassing book that leaves nothing out.\n\n[Download this book from Amazon
1](http://www.amazon.in/Xamarin-Mobile-Application-Development-iOS/dp/935110477X/ref=sr_1_1?s=books\u0026ie=UTF8\u0026qid=1418369348\u0026sr=1-1\u0026keywords=xamarin)\n"])</script>
1<script>self.__next_f.push([1,"e5:T1b4c,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains how to download image asynchronously in Xamarin.Android. In this example, we will downloading image using `System.Net.WebClient` and while downloading, the application will show a loading progress indicator.\n\n**System.Net.WebClient** class provides ability to send and download data from remote location. Check out class reference from [Official MSDN](http://msdn.microsoft.com/en-us/library/system.net.webclient\\(v=vs.110\\).aspx) API documentation.\n\n[![Asynchronous Image Loading in Xamarin Android](/media/articles/238/Asynchronous-Image-Loading-in-Xamarin-Android.png)](http://stacktips.com)\n\nLet us create a layout as shown in the image above\n\n### Main.axml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:minWidth=\"25px\"\n    android:minHeight=\"25px\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:gravity=\"center_horizontal\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cButton\n        android:text=\"Download Image\"\n        android:id=\"@+id/downloadButton\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\" /\u003e\n\n    \u003cLinearLayout\n        android:minWidth=\"25px\"\n        android:minHeight=\"25px\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:orientation=\"horizontal\"\n        android:id=\"@+id/progressLayout\"\n        android:gravity=\"center\"\u003e\n\n        \u003cProgressBar\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"match_parent\"\n            android:id=\"@+id/progressBar1\" /\u003e\n        \u003cTextView\n            android:text=\"Loading..\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"match_parent\"\n            android:id=\"@+id/textView1\"\n            android:gravity=\"center\" /\u003e\n    \u003c/LinearLayout\u003e\n\n    \u003cImageView\n        android:src=\"@android:drawable/ic_menu_gallery\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:id=\"@+id/imageView1\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\n### ImageViewExample.cs\n\n```cs\nusing System;\n\nusing Android.App;\nusing Android.Content;\nusing Android.Runtime;\nusing Android.Views;\nusing Android.Widget;\nusing Android.OS;\nusing Android.Graphics;\nusing System.Threading.Tasks;\nusing System.IO;\nusing System.Net;\n\nnamespace ImageViewExample\n{\n    [Activity (Label = \"ImageViewExample\", MainLauncher = true, Icon = \"@drawable/icon\")]\n    public class MainActivity : Activity\n    {\n\n        Button downloadButton;\n        ImageView imageView;\n        LinearLayout progressLayout;\n\n        //Instance of webclient for async processing\n        WebClient webClient;\n\n        protected override void OnCreate (Bundle bundle){\n            base.OnCreate (bundle);\n\n            // Set our view from the \"main\" layout resource\n            SetContentView (Resource.Layout.Main);\n\n            this.imageView = FindViewById\u003cImageView\u003e (Resource.Id.imageView1);\n            //Hide progressbar initially\n            this.progressLayout = FindViewById\u003cLinearLayout\u003e (Resource.Id.progressLayout);\n            this.progressLayout.Visibility = ViewStates.Gone;\n\n            // Get views from the layout resource axml file\n            this.downloadButton = FindViewById\u003cButton\u003e (Resource.Id.downloadButton);\n            downloadButton.Click += downloadAsync;\n        }\n\n        async void downloadAsync(object sender, System.EventArgs ea){\n                  //Logic to download image and display on ImageView\n        }\n\n        void cancelDownload(object sender, System.EventArgs ea){\n                 // Logic to cancel downlaod\n        }\n    }\n}\n```\n\n## Downloading Image\n\nIn our activity, we have a button labelled “Download Image” is added with `downloadAsync` delegate. The downloadAsync method will contain the logic of download using WebClient, display progress bar, resize and store image locally. When user hits download button, the download starts and the button turns into “Cancel Download”. Below is the code snippet for downloadAsync method.\n\n```cs\nasync void downloadAsync(object sender, System.EventArgs ea){\n    webClient = new WebClient ();\n    var url = new Uri (\"http://doubletreebyhiltonsanjose.com/wp-content/uploads/2014/08/Dog-Pictures-1024x698.jpg\");\n    byte[] imageBytes = null;\n\n    //Show loading progress\n    this.progressLayout.Visibility = ViewStates.Visible;\n\n    //Toggle button click listener to cancel the task\n    this.downloadButton.Text = \"Cancel Download\";\n    this.downloadButton.Click -= downloadAsync;\n    this.downloadButton.Click += cancelDownload;\n\n    try{\n        imageBytes = await webClient.DownloadDataTaskAsync(url);\n    } catch(TaskCanceledException){\n        this.progressLayout.Visibility = ViewStates.Gone;\n        return;\n    } catch(Exception e){\n        this.progressLayout.Visibility = ViewStates.Gone;\n\n        this.downloadButton.Click -= cancelDownload;\n        this.downloadButton.Click += downloadAsync;\n        this.downloadButton.Text = \"Download Image\";\n        return;\n    }\n\n    //Saving bitmap locally\n    string documentsPath = System.Environment.GetFolderPath (System.
1Environment.SpecialFolder.Personal);\n    string localFilename = \"image.png\";\n    string localPath = System.IO.Path.Combine (documentsPath, localFilename);\n\n    //Save the Image using writeAsync\n    FileStream fs = new FileStream (localPath, FileMode.OpenOrCreate);\n    await fs.WriteAsync (imageBytes, 0, imageBytes.Length);\n    Console.WriteLine(\"Saving image in local path: \"+localPath);\n\n    //Close file connection\n    fs.Close ();\n\n    BitmapFactory.Options options = new BitmapFactory.Options ();\n    options.InJustDecodeBounds = true;\n    await BitmapFactory.DecodeFileAsync (localPath, options);\n\n    //Resizing bitmap image\n    options.InSampleSize = options.OutWidth \u003e options.OutHeight ? options.OutHeight / imageView.Height : options.OutWidth / imageView.Width;\n    options.InJustDecodeBounds = false;\n\n    Bitmap bitmap = await BitmapFactory.DecodeFileAsync (localPath, options);\n    imageView.SetImageBitmap (bitmap);\n\n    //Hide progress bar layout\n    this.progressLayout.Visibility = ViewStates.Gone;\n\n    //Toggle button click listener\n    this.downloadButton.Click -= cancelDownload;\n    this.downloadButton.Click += downloadAsync;\n    this.downloadButton.Text = \"Download Image\";\n}\n```\n\n## Cancel Image Download\n\nThe `cancelDownload` delegate is added to button, when the user clicks on download button. This method contains the logic to cancel the download process.\n\n```cs\nvoid cancelDownload(object sender, System.EventArgs ea){\n    if(webClient!=null)\n        webClient.CancelAsync ();\n\n    //Hide progressbar layout\n    this.progressLayout.Visibility = ViewStates.Gone;\n\n    //Toggle button click listener\n    this.downloadButton.Click -= cancelDownload;\n    this.downloadButton.Click += downloadAsync;\n    this.downloadButton.Text = \"Download Image\";\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"e6:T180c,"])</script>
1<script>self.__next_f.push([1,"\nBuilding a fine quality mobile app is something that involves a great deal of dedication and hard work. In other words, prior to submitting your iOS app to the App Store, it is pivotal to beta test it for detection of any kind of bugs.\n\nTestFlight is one of the best tools that are used for distributing iOS applications for beta testing. Having being acquired by Apple, TestFlight’s parent company Burstly has been quite confident about the success and acceptance of this Apple beta distribution platform. Getting started with TestFlight is as simple as taking a walk in the park. Through this blog, I’ll be offering you a definite guideline on iOS8 beta testing performed with the help of TestFlight.\n\n# **iOS app beta testing- What is it exactly?**\n\nBeta testing is basically a prominent step in the software development life cycle. Even after testing the app using the built-in simulator and real device, there are chance of missing the opportunity of uncovering some of the basic bugs. This is the point why, the significance of beta testing is realized. Generally open for a small group of real people, beta testing is an effective method of receiving feedback for a particular app that’s to be released soon. You can allow the beta testers to discover a wide range of bugs that might have entered into the app during the design and development stages.\n\n## **TestFlight- An innovative tool for beta testing of iOS apps**\n\nTestFlight helps you in streamlining the process of beta testing of your application. TestFlight is a tool that makes it quite easy for a developer/app owner to invite users for testing the pre-release version of iOS8 applications. With TestFlight, you can invite up to 1,000 beta testers via their email addresses.\n\nAdjacent to the official release of iOS8 and Xcode 6, TestFlight can be easily integrated into iTunes Connect.\n\n[![testflight-24-19](/media/articles/242/testflight-24-19-620x403.png)](http://stacktips.com)\n\n## **Testing with external testers- Possible with TestFlight**\n\nTestFlight allows you to arrange app testing with external testers and internal app users. Here, internal app users can be engineers from development team and other stakeholders. With new TestFlight, you can invite up to, 25 internal users and 1,000 external testers, who can download and test the app and can report bugs.\n\nThe only point that needs to be noted with the process of inviting external testers is that your app must be approved by Apple beforehand. This restriction isn’t there for the internal users as they can begin beta testing your app once its been uploaded to iTunes Connect.\n\n## **And now, the steps involved in beta testing iOS apps using TestFlight**\n\nIn this post, we will drive through the process that involve the steps to distribute an app for beta testers using TestFlight.\n\nIf you are an Android developer looking for similar beta testing platform read through [TestFairy – Android app beta testing and deployment platform](http://stacktips.com/android/testfairy-android-app-beta-testing-platform \"TestFairy – Android app beta testing and deployment platform\").\n\n### **Step 1- Create an app record on iTunes Connect**\n\nIn order to get started with beta testing, you need to create an app record on iTunes Connect. Simply go to the [iTunes Connect](https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa) official website and create an account.\n\nOnce your account is setup, sign in and select ‘My Apps’ and the + icon for creating a new Ios app. Here, you’ll also be asked to fill in values for fields including: App name, primary language, Bundle ID, version and SKU (Stock Keeping Unit).\n\n### **Step 2- Update the Build String**\n\nNow let us go back to Xcode IDE and make sure the version number matches with the one you entered in iTunes Connect.\n\nGo to project navigator and select the project and target for displaying the project editor. After this, under the General Tab, ensure to review the version fields available under the identity section and set the Build field to 1.\n\n### **Step 3- Archive and upload the application**\n\nPrior to archiving the app, make it a point to include the app icon and launch the image in the Xcode project. Here, all the app icons will be managed by the asset catalog. In order to add an icon to the set, select the app icon in the Finder and drag the same to the appropriate image in the set viewer.\n\nFor archiving the app, simply review the Archive scheme settings and make sure the build configuration has been set to Release. Once you’re done with the app archiving process, the archive will appear within the Organizer and the app will be ready for upload to iTunes Connect.\n\n### **Step 4- Manage the app’s beta testing in iTunes Connect**\n\nOnce the build is uploaded to iTunes Connect, select My Apps and then your app. You can easily spot your uploaded app archive under the PreRelease tab. Next, opt for enabling beta testing by flipping the TestFlight Beta Testing to ‘On’.\n\n[![12TestingOff_2x](/media/articles/242/12TestingOff_2x.png)](http://stacktips.com)\n\nThe status of beta testing of app will be changed from Inactive to Invite Testers. After this, click on ‘Invite Testers’ and ‘Users and Roles’ for inviting the internal testers to check out the application. You can assign specific designations to users including: admin, legal etc. The specific users will receive an email regarding the invitation for performing the app’s TestFlight beta testing.\n\n[
1![6AddExternalTesters_2x](/media/articles/242/6AddExternalTesters_2x.png)](http://stacktips.com)\n\n# **Conclusion**\n\nTestFlight has been one of the most powerful tools for beta testing of iOS applications. Once you’ve built an app after hiring a [Custom iPhone App Development Company](http://www.xicom.biz/offerings/iphone-development/), its quite crucial for you to beta test it before releasing it for the general public. With testing being a vital part of app development process, you can’t afford to skip it in any way.\n\nHope the steps mentioned will helped you gather a clear insight into beta testing your apps using TestFlight before public release.\n"])</script>
1<script>self.__next_f.push([1,"e7:Td1f,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial we will see “How to create a login screen using Xamarin.Android”. This example assumes, you have Xamarin for Android development environment setup already.\n\nTo design login screen as shown in the image below, we will be using two EditText for username, password and login button.\n\n[![Login Screen using Xamarin](/media/articles/244/Login-Screen-using-Xamarin.png)](http://stacktips.com)\n\n### Login.axml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:background=\"#2579BF\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerInParent=\"true\"\n        android:layout_margin=\"10dp\"\n        android:orientation=\"vertical\"\u003e\n\n        \u003cImageView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_gravity=\"center\"\n            android:layout_marginBottom=\"20dp\"\n            android:src=\"@drawable/ic_launcher\" /\u003e\n\n        \u003cEditText\n            android:id=\"@+id/userName\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"45dp\"\n            android:padding=\"5dp\"\n            android:background=\"@android:color/white\" /\u003e\n\n        \u003cView\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"2dp\"\n            android:background=\"#f7f7f7\" /\u003e\n\n        \u003cEditText\n            android:id=\"@+id/password\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"45dp\"\n            android:padding=\"5dp\"\n            android:background=\"@android:color/white\"\n            android:inputType=\"textPassword\" /\u003e\n\n        \u003cButton\n            android:id=\"@+id/login\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"wrap_content\"\n            android:layout_below=\"@id/password\"\n            android:layout_marginTop=\"10dp\"\n            android:background=\"#307FC1\"\n            android:text=\"Login\"\n            android:textColor=\"@android:color/white\" /\u003e\n\n    \u003c/LinearLayout\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\nNow, let us create an Activity class and use the below code. To make this example simplified, we are just displaying a toast message when login button is clicked.\n\n### LoginActivity.cs\n\n```cs\nusing System;\n\nusing Android.App;\nusing Android.Content;\nusing Android.Runtime;\nusing Android.Views;\nusing Android.Widget;\nusing Android.OS;\n\nnamespace MyApplication\n{\n    [Activity (Label = \"POIApplication\", Theme=\"@style/android:Theme.Holo.Light.NoActionBar\")]\n    public class LoginActivity : Activity\n    {\n        protected override void OnCreate (Bundle bundle)\n        {\n            base.OnCreate (bundle);\n\n            // Set our view from the \"main\" layout resource\n            SetContentView (Resource.Layout.Login);\n\n            //Initializing button from layout\n            Button login = FindViewById\u003cButton\u003e (Resource.Id.login);\n\n            //Login button click action\n            login.Click += (object sender, EventArgs e) =\u003e {\n                Android.Widget.Toast.MakeText(this, \"Login Button Clicked!\", Android.Widget.ToastLength.Short).Show();\n            };\n        }\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"e8:Ta09,"])</script>
1<script>self.__next_f.push([1,"\nIn this article, we take a look into creating a splash screen in Android using Xamarin. A splash screen is non different than other screens, that indicates the loading of resources/data for application. Usually most of the real time application have a splash screen as the first screen to show when application starts, and it is automatically goes off once app is fully loaded.\n\nAll you have to do is to define your activity theme style inside `Resources/values/Styles.xml` file. If you take a look into below style attributes, they are self explanatory. The `android:windowBackground` attributes takes the link to splash image.\n\n### Styles.xml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\" ?\u003e\n\u003cresources\u003e\n  \u003cstyle name=\"Theme.SplashActivity\" parent=\"android:Theme.Holo.Light.NoActionBar\"\u003e\n    \u003citem name=\"android:windowBackground\"\u003e@drawable/ic_splash_logo\u003c/item\u003e\n  \u003c/style\u003e\n\u003c/resources\u003e\n```\n\n### SplashActivity.cs\n\nNow let us create a new Activity for splash screen. In this example, we have named it as SplashActivity, and paste the below code.\n\n```csharp\nnamespace MyApplication\n{\n    using System.Threading;\n    using Android.App;\n    using Android.OS;\n\n    [Activity (Label = \"SplashScreen\", MainLauncher=true, NoHistory=true, Theme=\"@style/Theme.SplashActivity\")]\n    public class SplashActivity : Activity\n    {\n        protected override void OnCreate(Bundle bundle)\n        {\n            base.OnCreate(bundle);\n\n            // Wait for 2 seconds\n            Thread.Sleep(2000);\n\n            //Moving to next activity\n            StartActivity(typeof(MainActivity));\n        }\n    }\n}\n```\n\nIn the above code we have specified `[Activity]` attribute with following properties\n\n1.  **MainLauncher** – This specifies that the activity is a launcher activity and will start automatically when application is launched\n2.  **Theme** – This specifies the custom theme to android activity\n3.  **NoHistory** – By default Android application maintain back stack of all activities. When user moves from ActivityA to ActivityB, and presses device back button from ActivityB, android system automatically shows to ActivityA. In case of splash screen, once application is loaded, we are not welling to display splash screen again at any point of time. Hence, we must ask android system to explicitely, not to add SplashActivity into backstack. This can be done by using `NoHistory = true` argument. .\n\nA typical android application Splash screen will perform the loading activity. As this is an example we are just using `Thread.Sleep(milliseconds)` to create a delay.\n"])</script>
1<script>self.__next_f.push([1,"e9:Ta19,"])</script>
1<script>self.__next_f.push([1,"\nThis article explains the interface segregation principle and its uses. Interface segregation is a design principle that deals with the disadvantages of “fat” interfaces. Interfaces containing methods that are not specific to it are called polluted or fat interfaces.\n\n\u003e Clients should not be forced to depend upon interfaces that they don’t use.\n\nLet us take the example of a multi-purpose machine developed by Xerox. This super xerox system could do a wide variety of jobs like printing, scanning, stapling, photocopying, etc. They can be implemented as a IMachine interface and XeroxMachine implementation as shown below.\n\n```java\npublic interface IMachine {\n    public void print();\n    public void staple();\n    public void scan();\n    public void photoCopy();\n}\n```\n\nXeroxMachine implementation\n\n```java\npublic class XeroxMachine implements IMachine {\n\n    @Override\n    public void print() {\n        System.out.println(\"Printing Job\");\n    }\n\n    @Override\n    public void staple() {\n        System.out.println(\"Stapling Job\");\n    }\n\n    @Override\n    public void scan() {\n        System.out.println(\"Scan Job\");\n    }\n\n    @Override\n    public void photoCopy() {\n        System.out.println(\"Photo Copy\");\n    }\n}\n```\n\nThe super machine is developed and working great. Now the company is getting requests for making a machine that do only print function. Management has decided to develop a specialized print machine. Now developers want to write Printer class that implements IMachine interface. Did you notice any problem? Although you need only print function, you have to implement all other methods of IMachine interface. **Now IMachine interface is not following interface segregation principle and called fat interface.**\n\nWe can breakdown the IMachine into multiple special purpose interfaces as shown below.\n\n```java\npublic interface IPrinter {\n    public void print();\n}\n\npublic interface IScanner {\n    public void fax();\n}\n\npublic interface IStapler {\n    public void staple();\n}\n\npublic interface IPhotoCopier {\n    public void photoCopy();\n}\n```\n\n### Notes:\n\nWhat if you are dealing with an existing legacy application where the interface is a fat interface? How do deal with such a situation? Well, you can always use an adapter design pattern for segregation.\n\nInterface segregation brings implementation simplicity and makes easy to debug and maintain.\n\nInterface segregation principle is easy to understand and sounds great in theory, but often difficult to identify the distinct interfaces and it can also end up with the proliferation of interfaces.\n"])</script>
1<script>self.__next_f.push([1,"ea:T104a,"])</script>
1<script>self.__next_f.push([1,"\n[![Picasso Image Downloader](/media/articles/247/Picasso-Image-Downloader.png)](http://stacktips.com)This this guide, we will see how to use Picasso library in android. Picasso is open source and one of the widely used image downloader library in Android. It is created and maintained by [Square](http://square.github.io/). It is among the powerful image download and caching [library for Android.](/articles/android-third-party-libraries-sdks \"Android third party libraries and SDK’s\")\n\n## Why Use Picasso?\n\n1.  It simplifies the process of loading images from external URLs and displays on your application. For example, downloading an image from the server is one of the most common tasks in any application. And it needs quite a larger amount of code to achieve this via android networking API’s. By using Picasso, you can achieve this with few lines of code.\n2.  It is always not about downloading the image from a remote location. You also have to think of implementing image caching logic in order to provide a seamless user experience. Picasso provides automatic image caching.\n3.  Image transformation is a costly affair. If your application need deal with such runtime image transformation, you must be watchful about OutOfMemoryException. Picasso deals with it, so you don’t have to do it yourself.\n\n### How to Use Picasso Android Library?\n\n[Download the Picasso JAR file](http://square.github.io/picasso/), If you haven’t done it already. If you are using eclipse as your development IDE, then just copy the downloaded `picasso-2.4.0.jar` file into your application lib folder. If you are using Android Studio IDE, then you have to add below dependency in `build.gradle` file.\n\n```java\ndependencies {\n   ...\n   compile \"com.squareup.picasso:picasso:2.4.0\"\n   ...\n}\n```\n\n### **Loading Image from URL ImageView**\n\nWe are done with configuration, let us see how to use this library to download images from remote server and display in ImageView. I assume you have your activity layout file already with ImageView declared on it.\n\n```xml\n\u003cImageView\n    android:layout_width=\"wrap_content\"\n    android:layout_height=\"wrap_content\"\n    android:id=\"@+id/imageView\"\n    android:layout_alignParentTop=\"true\"\n    android:layout_centerHorizontal=\"true\"\u003e\n\u003c/ImageView\u003e\n```\n\nFor Picasso download image from server, you need to add below internet permissions to your project’s manifest.\n\n```xml\n\u003cuses-permission android:name=\"android.permission.INTERNET\" /\u003e\n```\n\nNow let us download the image and display on imageView\n\n```java\n//Initialize ImageView\nImageView imageView = (ImageView) findViewById(R.id.imageView);\n//Loading image from below URL into imageView\nPicasso.with(this)\n   .load(\"YOUR IMAGE URL HERE\")\n   .into(imageView);\n```\n\nIn the first line we are getting ImageView instance from the layout. And then load the image from the above remote URL using the Picasso library.\n\n### Placeholder and Error Fallback\n\nIn the above code snippet, we have just downloaded the image and displayed on ImageView. But that is not enough always. For any real-time application, you must think of all possible cases. Now we need a placeholder and error fallback for our ImageView. Placeholder image will be shown before the image is loaded. Error fallback will be shown if, there is an error while downloading image. However both fallback and placeholder are optional.\n\n```java\nPicasso.with(this)\n    .load(\"YOUR IMAGE URL HERE\")\n    .placeholder(R.drawable.ic_placeholder)\n    .error(R.drawable.ic_error_fallback)\n    .into(imageView);\n```\n\n### Image Resize and Transformation\n\nPicasso offers much more than just downloading image. It can resize the image, transform before it is displayed in ImageView.\n\n```java\nPicasso.with(this)\n     .load(\"YOUR IMAGE URL HERE\")\n     .placeholder(R.drawable.ic_placeholder)\n     .error(R.drawable.ic_error_fallback)\n     .resize(250, 200)\n     .rotate(90)\n     .into(imageView);\n```\n\n### Alternative options:\n\nSome of the other alternative contenders of Picasso are:\n\n-   [Universal Image Loader](/articles/universal-image-loader-library-in-android)\n-   [Volley from Google](http://developer.android.com/training/volley/index.html)\n"])</script>
1<script>self.__next_f.push([1,"eb:T1c8a,"])</script>
1<script>self.__next_f.push([1,"\nOver the course of this article, we will examine one of the most commonly used patterns, the Factory method pattern in java.\n\nSoftware systems undergo constant changes and they are unstable. We must consider designing where the objects and relationships are loosely coupled. Loose coupling is one of the most important characteristics in software design; this helps in extending new functions in the software without disturbing or doing no changes to the existing system.\n\n\u003e “The Factory design pattern provides a way to use an instance as an object factory. The factory can return an instance of one of several possible classes in a class hierarchy, depending on the data provided to it.”\n\nJava Factory pattern belongs to the creational family of design patterns that govern the object instantiation process. The Factory pattern is grouped into the Simple Factory, Factory Method, and Abstract Factory patterns. We will taper the context of this tutorial to Simple Factory and Factory method design pattern.\n\n1.  **Simple Factory:** the Simple factory isn’t actually a design pattern; its more of a programming technique often used to encapsulate the object instantiation process.\n2.  **Factory Method:** Defines an interface for creating an object, but lets the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.\n3.  **Abstract Factory:** Provides an interface for creating families of related or dependent objects without specifying their concrete classes.\n\nBenefits of Factory design pattern\n\n1.  The client does not need to know every subclass of objects it must create. It only needs one reference to the abstract class/interface and the factory object.\n2.  The factory encapsulates the creation of objects. This can be useful if the creation process is very complex.\n\n# Simple Factory Pattern\n\nSpice Digital Inc. is one of the top smartphone manufacturers in India. They are the pioneer in manufacturing and distributing smartphones in Indian market. For now, they have two successful products SpiceFire and SpiceBolt. The `produceMobile()` method is working well which produce two different mobiles based on their model number. Let us have a look into the current implementation of produceMobile() method.\n\n```java\npublic SpiceMobile produceMobile(String model) {\n        SpiceMobile mobile = null;\n\n        if (model.equalsIgnoreCase(\"SpiceBolt\")) {\n            mobile = new SpicePlus();\n        } else if (model.equalsIgnoreCase(\"SpiceFire\")) {\n            mobile = new SpiceBolt();\n        }\n        mobile.prepare();\n        mobile.bundle();\n        mobile.label();\n\n        return mobile;\n}\n```\n\nSpiceMobile implementation,\n\n```java\npublic abstract class SpiceMobile {\n    public abstract void prepare();\n    public abstract void bundle();\n    public abstract void label();\n}\n\npublic class SpiceFire extends SpiceMobile {\n    @Override\n    public void prepare() {\n    }\n\n    @Override\n    public void bundle() {\n    }\n\n    @Override\n    public void label() {\n    }\n}\n\npublic class SpiceBolt extends SpiceMobile {\n\n    @Override\n    public void prepare() {\n    }\n\n    @Override\n    public void bundle() {\n    }\n\n    @Override\n    public void label() {\n    }\n}\n```\n\nProblems with the above implementation\n\n1.  The above implementation is working well and everyone is happy. However, at some point in time, a company want to release another new model to market, they need to change the produceMobile() method code.\n2.  The design is not extensive and it is closed for modification.\n3.  Adds more complexity to refactor code each time new products added.\n\n# Factory Method Design Pattern Example\n\nThe above example is working great to deal with producing mobiles. However, we have outlined some of the problems above on the above approach. Now let us add some more complexity to the above requirements.\n\nSpice Digital Inc. company now decided to make their global presence. They want to extend their business to London and NewYork location. Looking at the market interest, London factory will produce only SpiceBolt and SpiceFire model and New York will produce SpiceFire and SpicePlus. Now the use-case is becoming fairly complex. Let us have a glance at the below class diagram that using the Factory method design pattern.\n\n[![Factory Method Design Pattern](/media/articles/248/Factory-Method-Design-Pattern-620x365.png)](http://stacktips.com)\n\n### SpiceMobile.java\n\n```java\npublic abstract class SpiceMobile {\n    public double price;\n    public double getPrice() {\n        return price;\n    }\n\n    public void setPrice(double price) {\n        this.price = price;\n    }\n\n    public abstract void prepare();\n\n    public abstract void bundle();\n\n    public abstract void label();\n}\n```\n\nNow, let us create three different Spice mobile implementation. For demonstration purpose, we have three simple implementations i.e. SpiceBolt, SpiceFire, and SpicePlus. All three classes are similar so we don’t have listed them all.\n\n### SpiceBolt.java\n\n```java\npublic class SpiceBolt extends SpiceMobile {\n\n    @Override\n    public void prepare() {\n    }\n\n    @Override\n    public void bundle() {\n    }\n\n    @Override\n    public void label() {\n    }\n}\n```\n\n### MobileFactory.java\n\n```java\npublic abstract class MobileFactory {\n\n    public abstract SpiceMobile constructMobile(String model);\n\n    /**\n     * Defines the process to product mobile. This implementation should'nt be\n     * be changed by clients\n     *\n     * @param model\n     * @return SpiceMobile\n     */\n    public SpiceMobile produceMobile(String model) {\n\n        SpiceMobile mobile = constructMobile(model);\n        mobile.prepare();\n        mobile.bundle();\n        mobile.label();\n\n        return mobile;\n    }\n}\n```\n\n### LondonMobileFactory.java\n\n```java\n/**\n * London mobile factory is specialized and only sale Spice3D and SpiceHD.\n */\npublic class LondonMobileFactory extends MobileFactory {\n\n    @Override\n    public SpiceMobile constructMobile(String model) {\n\n        SpiceMobile mobile = null;\n\n        if (model.equalsIgnoreCase(\"SpiceFire\")) {\n            mobile = new SpicePlus();\n            mobile.setPrice(300);\n        } else if (model.equalsIgnoreCase(\"SpiceBolt\")) {\n            mobile = new SpiceBolt();\n            mobile.setPrice(400);\n        }\n\n        return mobile;\n    }\n}\n```\n\n### NYMobileFactory.java\n\n```java\n/**\n * New York mobile factory is specialized and only sale Spice3D and SpiceMono.\n */\n\npublic class NYMobileFactory extends MobileFactory {\n\n    @Override\n    public SpiceMobile constructMobile(String model) {\n\n        SpiceMobile mobile = null;\n\n        if (model.equalsIgnoreCase(\"SpiceFire\")) {\n            mobile = new SpicePlus();\n            mobile.setPrice(200);\n        } else if (model.equalsIgnoreCase(\"SpiceMono\")) {\n            mobile = new SpiceFire();\n            mobile.setPrice(280);\n        }\n\n        return mobile;\n    }\n}\n```\n\n### Client.java\n\n```java\npublic class Client {\n\n    public static void main(String[] args) {\n\n        MobileFactory factory = new LondonMobileFactory();\n        SpiceMobile mobile = factory.produceMobile(\"SpiceHD\");\n\n        MobileFactory nyFactory = new NYMobileFactory();\n        SpiceMobile mobile2 = factory.produceMobile(\"SpiceMono\");\n\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"ec:T110a,"])</script>
1<script>self.__next_f.push([1,"\nOver the course of this article, we will examine Builder design pattern in Java. Builder design pattern belongs to the creational family of pattern, that control the object instantiation process. Builder design pattern simplifies the object instantiation process for complex objects. The definition of Builder design pattern as provided in the original Gang of Four book is,\n\nSeparates the construction of a complex object from its representation so that the same construction process can create different representations.\n\nLet us understand this pattern in a simpler term. In Java for instantiating objects we need to pass parameters to its class constructor. What if we have different combinations of parameters required to create objects and some of them are mandatory and some are optional? We can overload the class constructor with different combinations to achieve this.\n\nInstead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.\n\n# Builder Design Pattern Example\n\nLet us take an example of a cafe preparing a meal. For preparing a meal there are various steps being performed, for example, choosing sandwich, adding sides, drink, offer, etc. There can be different combination of meal created during the process. In such cases preparing a meal is difficult than it is expected. Let us solve this issue by using builder design pattern.\n\n[![Builder Design Pattern Java](/media/articles/249/Builder-Design-Pattern-Java-620x382.png)](http://stacktips.com)\n\nIn the above class diagram,\n\n1.  The `MealBuilder` specifies an abstract interface for creating parts of a Meal.\n2.  The `SandwichMealBuilder` is an concrete builder constructs and assembles parts of the product by implementing the MealBuilder interface.\n3.  The `MealDirector` constructs an object using the MealBuilder interface.\n4.  The `Meal` is the object which we are intended to create during this process\n\n### Meal.java\n\n```java\npackage com.javatechig.designpattern.builder;\n\npublic class Meal {\n    public String sandwich;\n    public String sideOrder;\n    public String drink;\n    public String offer;\n    public double price;\n\n    @Override\n    public String toString() {\n        return \"Sandwich=\" + sandwich + \" Side Order=\" + sideOrder + \" Drink=\"\n                + drink + \" Offer=\" + offer + \" Price=\" + price;\n    }\n}\n```\n\n### MealBuilder.java\n\n```java\npackage com.javatechig.designpattern.builder;\n\npublic interface MealBuilder {\n    public abstract void addSandwich(String sandwich);\n    public abstract void addSides(String sides);\n    public abstract void addDrink(String drink);\n    public abstract void addOffer(String coupon);\n    public abstract void setPrice(double price);\n    public abstract Meal getMeal();\n}\n```\n\n### SandwichMealBuilder.java\n\n```java\npackage com.javatechig.designpattern.builder;\n\npublic class SandwichMealBuilder implements MealBuilder {\n    private Meal _meal = new Meal();\n\n    @Override\n    public void addSandwich(String sandwich) {\n        _meal.sandwich = sandwich;\n    }\n\n    @Override\n    public void addSides(String sides) {\n        _meal.sideOrder = sides;\n    }\n\n    @Override\n    public void addDrink(String drink) {\n        _meal.drink = drink;\n    }\n\n    @Override\n    public void addOffer(String coupon) {\n        _meal.offer = coupon;\n    }\n\n    @Override\n    public void setPrice(double price) {\n        _meal.price = price;\n    }\n\n    @Override\n    public Meal getMeal() {\n        return _meal;\n    }\n}\n```\n\n### MealDirector.java\n\n```java\npackage com.javatechig.designpattern.builder;\n\npublic class MealDirector {\n\n    public void makeMeal(MealBuilder mealBuilder) {\n\n        mealBuilder.addSandwich(\"Hamburger\");\n        mealBuilder.addSides(\"Fries\");\n        mealBuilder.addDrink(\"Coke\");\n        mealBuilder.addOffer(\"Weekend Bonanza\");\n        mealBuilder.setPrice(5.99);\n    }\n}\n```\n\n### Client.java\n\n```java\npackage com.javatechig.designpattern.builder;\n\npublic class Client {\n    public static void main(String[] args) {\n        MealBuilder pizzaBuilder = new SandwichMealBu
1ilder();\n        MealDirector director = new MealDirector();\n        director.makeMeal(pizzaBuilder);\n\n        Meal meal = pizzaBuilder.getMeal();\n        System.out.println(meal.toString());\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"ed:Tecf,"])</script>
1<script>self.__next_f.push([1,"\nOver the course of this article, we will examine Prototype design pattern in Java. Prototype design pattern belongs to the creational family of pattern. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. In a simpler term, using prototype pattern, we will create new instances through cloning existing instances.\n\nCreating instance in java is one of the costly operation. It costs time and resources. If there is a scope to avoid object creation process, by just copying the existing object, then won’t it be great? Prototype design patterns answers that problem.\n\nUse the prototype design pattern when,\n\n1.  When specifying new objects by changing an existing objects structure\n2.  Speeds up instantiation of large, dynamically loaded classes\n\n## Prototype Design Pattern Example\n\nThe Hampstead Cake company are well known for providing quality birthday cheese cakes in London. For each order the cheese cake has to be customized with recipients name, however the ingredients and taste remains the same. The cake company is getting inundated orders and now struggling to deliver them. The trouble is, it is taking too long to specify ingredients and build cheese cake for each order. That way they cannot produce enough cakes. How about you just produce a single cheesecake, and clone it multiple times, and then customize each one?\n\nIn this example, CakeStore class is the client. The client creates multiple prototypical instances by calling `prepareCake()` method.\n\n  \n[![Prototype Design Pattern](/media/articles/250/Prototype-Design-Pattern.png)](http://stacktips.com)\n\n### Cake.java\n\n```java\npackage com.javatechig.designpattern.prototype;\n\npublic interface Cake extends Cloneable {\n\n    public Cake prepareCake();\n}\n```\n\n### CheeseCake.java\n\n```java\npackage com.javatechig.designpattern.prototype;\n\npublic class CheeseCake implements Cake {\n\n    private String sugar;\n    private String butter;\n    private String cheese;\n    private String name;\n\n    public Cake prepareCake() {\n        Cake cake = null;\n        try {\n            cake = (Cake) super.clone();\n        } catch (CloneNotSupportedException e) {\n            e.printStackTrace();\n        }\n        return cake;\n    }\n\n    void addSugar(String sugar) {\n        this.sugar = sugar;\n    }\n\n    void addButter(String butter) {\n        this.butter = butter;\n    }\n\n    public void addCheese(String cheese) {\n        this.cheese = cheese;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    @Override\n    public String toString() {\n        return \"Sugar:\" + sugar + \", Butter:\" + butter + \", Name:\" + name\n                + \", Cheese:\" + cheese;\n    }\n\n}\n```\n\n### CakeStore.java\n\n```java\npackage com.javatechig.designpattern.prototype;\n\npublic class CakeStore {\n\n    public static void main(String[] args) {\n\n        /* Cheese cake preparation */\n        CheeseCake cake = new CheeseCake();\n        cake.addSugar(\"100g\");\n        cake.addButter(\"200g\");\n        cake.addCheese(\"Acapella\");\n        System.out.println(\"Cake = \" + cake.toString());\n\n\n        /* Order with custom name */\n        CheeseCake cake1 = (CheeseCake) cake.prepareCake();\n        cake1.setName(\"Bastien\");\n        System.out.println(\"Cake1 = \" + cake1.toString());\n\n        /* Order with custom name and customized cheese */\n        CheeseCake cake2 = (CheeseCake) cake.prepareCake();\n        cake2.addCheese(\"Extra Cheese\");\n        cake2.setName(\"Adams\");\n        System.out.println(\"Cake3 = \" + cake2.toString());\n    }\n}\n```\n\n### Output\n\n```text\nCake = Sugar:100g, Butter:200g, Name:null, Cheese:Acapella\nCake1 = Sugar:100g, Butter:200g, Name:Bastien, Cheese:Acapella\nCake3 = Sugar:100g, Butter:200g, Name:Adams, Cheese:Extra Cheese\n```\n"])</script>
1<script>self.__next_f.push([1,"ee:T1b86,"])</script>
1<script>self.__next_f.push([1,"\nOver the course of this article, we will examine Adapter design pattern in Java. Adapter design pattern belongs to the structural family of pattern, that enables two incompatible interfaces to work together. The Adapter pattern allows two incompatible classes to work together by converting the interface of one class into an interface expected by the clients. This pattern is also known as Wrapper. The definition of Adapter pattern provided in the original Gang of Four book is,\n\n\u003e Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.\n\nIn order to understand this pattern, let us have a look into some of the real-time examples of adapter\n\n1.  Suppose you have bought a laptop from India, and in recent past you have just moved to United Kingdom. The electric sockets used in UK is different from the indian electric sockets. And hence, your laptop charger wont work directly. You need to buy an adapter that can charge your indian charger on UK electric socket.\n2.  When you have an legacy library interface to be integrated with new system. The new system is not directly accepting the way the legacy library works. As the library is intended to use is not longer on development, we need an adapter to make the two incompatible types to work.\n\nIn this pattern,\n\n1.  The Client makes a request to the adapter by calling a method on it using the target interface.\n2.  The Adapter translates that request into one or more calls on adaptee using adapter interface.\n3.  The client receives the result of the call and never knows there is an adapter doing the translation.\n\nUse the adapter design pattern when,\n\n1.  You want to use the existing class and its interfaces that meet your interface requirements at your end.\n2.  You want to create a reusable class that helps to interface between two incompatible classes.\n\n## Adapter Design Pattern Example\n\nLloyds bank is an international bank offers services worldwide. For offshore account holders, the tax rate is 0.03%. And, in India it offers two types of accounts, Standard and Platinum. Tax rules are not applied to indian bank accounts. Now the offshore bank is incompatible to Indian account types. We need to design an AccountAdapter to make both the incompatible account types to work together.\n\nIn the above example, the interaction diagram will be represented as shown below. Here client is just calling the `getBalance()` method of adapter. Adapter calls `getOffshoreBalance()` on adaptee and returns the result that client is expecting. The getBalance() methods inside Adapter will calculate the account balance by deducing the taxes applied for the offshore account.\n\n[![Adapter Design Pattern Sequence Diagram](/media/articles/251/Adapter-Design-Pattern-Sequence-Diagram-620x492.png)](http://stacktips.com)\n\nIn this example we are using object adapters. The object adapters uses composition to adapt one incompatible interface to another. The adapter inherits the target interface that the client expects to see, while it holds an instance of adaptee. This enables the client and the adaptee to be completely decoupled from each other. Only the adapter knows about both of them.\n\n[![Adapter Design Pattern Class Diagram](/media/articles/251/Adapter-Design-Pattern-Class-Diagram-620x330.png)](http://stacktips.com)\n\n### OffshoreAccount.java\n\n```java\npackage com.javatechig.designpattern.adapter;\n\npublic class OffshoreAccount {\n    private double balance;\n\n    /** The tax for the country where the account is */\n    private static final double TAX_RATE = 0.04;\n\n    public OffshoreAccount(final double balance) {\n        this.balance = balance;\n    }\n\n    public double getTaxRate() {\n        return TAX_RATE;\n    }\n\n    public double getOffshoreBalance() {\n        return balance;\n    }\n\n    public void debit(final double debit) {\n        if (balance \u003e= debit) {\n            balance -= debit;
1\n        }\n    }\n\n    public void credit(final double credit) {\n        balance += balance;\n    }\n}\n```\n\n### Account.java\n\n```java\npackage com.javatechig.designpattern.adapter;\n\npublic interface Account {\n    public double getBalance();\n    public boolean isOverdraftAvailable();\n    public void credit(final double credit);\n}\n```\n\n### AbstractAccount.java\n\n```java\npackage com.javatechig.designpattern.adapter;\n\npublic class AbstractAccount implements Account {\n    private double balance;\n    private boolean isOverdraftAvailable;\n\n    public AbstractAccount(final double size) {\n        this.balance = size;\n    }\n\n    @Override\n    public double getBalance() {\n        return balance;\n    }\n\n    @Override\n    public boolean isOverdraftAvailable() {\n        return isOverdraftAvailable;\n    }\n\n    public void setOverdraftAvailable(boolean isOverdraftAvailable) {\n        this.isOverdraftAvailable = isOverdraftAvailable;\n    }\n\n    @Override\n    public String toString() {\n        return getClass().getSimpleName() + \" Balance=\" + getBalance()\n                + \" Overdraft:\" + isOverdraftAvailable();\n    }\n\n    @Override\n    public void credit(final double credit) {\n        balance += credit;\n    }\n}\n```\n\n### PlatinumAccount.java\n\n```java\npublic class PlatinumAccount extends AbstractAccount {\n\n    public PlatinumAccount(final double balance) {\n        super(balance);\n        setOverdraftAvailable(true);\n    }\n}\n```\n\n### StandardAccount.java\n\n```java\npublic class StandardAccount extends AbstractAccount {\n\n    public StandardAccount(final double balance) {\n        super(balance);\n        setOverdraftAvailable(false);\n    }\n}\n```\n\n### AccountAdapter.java\n\n```java\npublic class AccountAdapter extends AbstractAccount {\n\n    // Adaptee - The class we are adapting from\n    private OffshoreAccount offshoreAccount;\n\n    /**\n     *\n     * @param offshoreAccount\n     *            the instance of OffshoreAccount we are going to adapt from.\n     */\n    public AccountAdapter(final OffshoreAccount offshoreAccount) {\n        super(offshoreAccount.getOffshoreBalance());\n\n        // holds adaptee reference\n        this.offshoreAccount = offshoreAccount;\n    }\n\n    /**\n     * Calculate offshore account balance after deducting the tax owed for\n     * offshore account\n     */\n    @Override\n    public double getBalance() {\n        final double taxRate = offshoreAccount.getTaxRate();\n        final double grossBalance = offshoreAccount.getOffshoreBalance();\n\n        final double taxableBalance = grossBalance * taxRate;\n        final double balanceAfterTax = grossBalance - taxableBalance;\n        return balanceAfterTax;\n    }\n}\n```\n\n### Client.java\n\n```java\npublic class AdapterTest {\n    public static void main(String[] args) {\n\n        StandardAccount sa = new StandardAccount(2000);\n        System.out.println(\"Account Balance= \" + sa.getBalance());\n\n        //Calling getBalance() on Adapter\n        AccountAdapter adapter = new AccountAdapter(new OffshoreAccount(2000));\n        System.out.println(\"Account Balance= \" + adapter.getBalance());\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"ef:T13bd,"])</script>
1<script>self.__next_f.push([1,"\nThe observer design pattern belongs to the behavioural family of patterns, that defines a common communication pattern between objects.\n\nObserver design pattern defines a one-to-many dependency between objects in which one object changes state, all its dependents are notified.\n\nObserver design pattern is sometimes called publisher-subscriber design pattern in networked models. Dependent objects are called observers and the object they are registering to is called a Subject.\n\nWhen the subject changes its state, all the observers get notified. In this pattern,\n\n-   Observers register themselves with the subject.\n-   The subject maintains the list of its dependents (Observers), and it broadcasts notifications to all its dependents when its state changes.\n-   Observers de-register explicitly when they no longer want to be notified.\n\nTo understand this pattern, let us look at some of the real-time examples:\n\n-   This design pattern is widely used on most of the user interface frameworks\n-   Most commonly used in most of the MVC (Model-View-Controller) models\n-   Consider the different charts in an Excel document. A chart is drawn based on the data shown on the grid. If there is any change to data in Excel grid, the chart is automatically redrawn.\n\n## Observer Design Pattern Example in Java\n\nIn this example, let us take the case of a news publisher. In a typical flow, the new readers subscribe for news. Once new news is published by the publisher, all the observers get notified. Here the publisher acts as the subject and subscribers are observers.\n\nA single publisher can have one or many subscribers.\n\n[![Observer Design Pattern Class Diagram](/media/articles/252/Observer-Design-Pattern-Class-Diagram.png)](http://stacktips.com)\n\nThe above class diagram represents, two observers  `Subscriber1` and `Subscriber2` register with publisher. Once there is a change in Publisher both the subscribers gets notified.\n\n**Observer.java**\n\n```java\npublic interface Observer {\n     public void update(String editon);\n}\n```\n\n**Subscriber1.java**\n\n```java\npublic class Subscriber1 implements Observer {\n\n    @Override\n    public void update(String  edition) {\n        System.out.println(\"New Edition from Subscriber1\");\n    }\n}\n```\n\n**Subscriber2.java**\n\n```java\npublic class Subscriber2 implements Observer {\n\n    @Override\n    public void update(String  edition) {\n        System.out.println(\"New Edition from Subscriber2\");\n    }\n}\n```\n\n**Subject.java**\n\n```java\npublic interface Subject {\n    public void registerObserver(Observer observer);\n\n    public void removeObserver(Observer observer);\n\n    public void notifyObservers();\n}\n```\n\n**Publisher.java**\n\n```java\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Publisher implements Subject {\n\n    private List\u003cObserver\u003e _observers = new ArrayList\u003cObserver\u003e();\n\n    @Override\n    public void registerObserver(Observer observer) {\n        System.out.println(\"Registered observer\");\n        _observers.add(observer);\n    }\n\n    @Override\n    public void removeObserver(Observer observer) {\n        System.out.println(\"Deregister observer\");\n        _observers.remove(observer);\n    }\n\n    @Override\n    public void notifyObservers() {\n\n        for (Observer observer : _observers) {\n            observer.update(\"Weekly Edition\");\n        }\n    }\n}\n```\n\n**Test.java**\n\n```java\npublic class Test {\n\n    public static void main(String[] args) {\n\n        /* News Publisher */\n        Subject publisher = new Publisher();\n\n        /* registering observers */\n        Observer subscriber1 = new Subscriber1();\n        publisher.registerObserver(subscriber1);\n\n        Observer subscriber2 = new Subscriber2();\n        publisher.registerObserver(subscriber2);\n\n        /* Notify observers */\n        publisher.notifyObservers();\n\n        /* Delete observers */\n        publisher.removeObserver(subscriber2);\n\n        /* Notify observers */\n        publisher.notifyObservers();\n    }\n}\n```\n\n**Output**\n\n```text\nRegistered observer\nRegistered observer\nNew Edition from Subscriber1\nNew Edition from Subscriber2\nDeregister observer\nNew Edition from Subscriber1\n```\n\n### Advantages of Observer Design Pattern\n\n-   Provides loose coupling between objects called observer and observable. The subject only know the list of observers it don’t care about their implementation. All the observers are notified by subject in a single message broadcast.\n-   You can add and remove observers at anytime. No modification is need to be done to the subject to add new observers.\n\n### Drawback of Observer Design Patterns\n\n-   Sometimes if there is a problem, it becomes complex to debug between the chain of observers.\n-   The subject holds reference of all the observers, if we not unregister the object it can cause memory leak. This common problem is called as lapsed listener problem.\n\n### Rules of thumb\n\n-   Explicitly unregister the observers, when no longer it is required to listen to Subject.\n-   It is recommended for subject to hold, weakreference of objects to avoid memory leak.\n"])</script>
1<script>self.__next_f.push([1,"f0:T2383,"])</script>
1<script>self.__next_f.push([1,"\nTestFairy is an android application beta testing and deployment platform. Read TestFairy platform features and detailed description [**here**.](http://stacktips.com/android/testfairy-android-app-beta-testing-platform)\n\nAs you upload a build to TestFairy, its process on the uploaded build and do some dynamic code injection. During the process, it forgets that the build was signed with a keystore. Before the build is made available for beta testers to download, TestFairy sign your build with a keystore key of its own. This will result in your application not working properly for the services that like Facebook, Google Map, In-App Purchases, Google Cloud Messaging (GCM) etc.\n\nHere is the workaround!! Instead of you just uploading your build to TestFairy, you can use the command line uploader script mentioning your keystore details. In this post, we’ll see the configurations and how to execute test fairy command line uploader script. This will be helpful for integrating bamboo, Jenkins or other CI build automation tools.\n\n### 1. Download TestFairy Command Line Upload Script\n\nLet us download the TestFairy command line upload script from **[GitHub](https://github.com/testfairy/command-line-uploader).** Once you have the `testfairy-upload.sh` the file you can change the following parameters as per your project configurations.\n\n```bash\n# Put your TestFairy API_KEY here. Find it in your TestFairy account settings.\nTESTFAIRY_API_KEY=\"Put your TestFairy API key here\"\n\n# Your Keystore, Store pass and Alias, the ones you use to sign your app.\nKEYSTORE=build-dir/MyProject/keystore/myapp.keystore\nSTOREPASS=android\nALIAS=myapp\n\n# Tester Groups that will be notified when the app is ready. Setup groups in your TestFairy account testers page.\n# This parameter is optional, leave empty if not required\nTESTER_GROUPS=\"Distribution Group Name\"\n\n# Comment text will be included in the email sent to testers\nCOMMENT=\"Put your update comment here\"\n\n# locations of various tools\nCURL=/usr/bin/curl\nZIP=/usr/bin/zip\nKEYTOOL=/usr/bin/keytool\nZIPALIGN=/Applications/adt-bundle-mac-x86_64-20130917/sdk/build-tools/19.1.0/zipalign\nJARSIGNER=/usr/bin/jarsigner\n```\n\n### 2. Executing Command Line Upload Script\n\n```bash\n$ chmod a+x testfairy-upload.sh\n\n$ ./testfairy-upload.sh bin/MyApp.apk\n```\n\nIf the script execute successfully, you will see the output in the code\n\n```text\nUploading bin/MyApp.apk to TestFairy.. OK!\nDownloading instrumented APK.. OK!\nRe-signing APK file.. jar signed.\n\nWarning:\nNo -tsa or -tsacert is provided and this jar is not timestamped. Without a timestamp, users may not be able to validate this jar after the signer certificate's expiration date (2283-11-17) or after any future revocation date.\nOK!\nUploading signed APK to TestFairy.. OK!\n\nThe build was successfully uploaded to TestFairy and is available at:\nhttps://app.testfairy.com/projects/6521-myapp/builds/142823\n```\n\nThe above code works fine and build getting uploaded to TestFairy. But there is one problem, if you are uploading build from CI tool, you would like to see the comments from developers for each build. In such case, you have to pass another command line parameter containing the release comment. This release comment will be sent over invitation email.\n\n```bash\n#!/bin/sh\n\nUPLOADER_VERSION=1.09\n\n# Put your TestFairy API_KEY here. Find it in your TestFairy account settings.\nTESTFAIRY_API_KEY=\"Put your TestFairy API key here\"\n\n# Your Keystore, Storepass and Alias, the ones you use to sign your app.\nKEYSTORE=build-dir/MyProject/keystore/myapp.keystore\nSTOREPASS=android\nALIAS=myapp\n\n# Tester Groups that will be notified when the app is ready. Setup groups in your TestFairy account testers page.\n# This parameter is optional, leave empty if not required\nTESTER_GROUPS=\"Distribution Group Name\"\n\n# Should email testers about new version. Set to \"off\" to disable email notifications.\nNOTIFY=\"on\"\n\n# If AUTO_UPDATE is \"on\" all users will be prompt to update to this build next time they run the app\nAUTO_UPDATE=\"off\"\n\n# The maximum recording duration for every test.\nMAX_DURATION=\"10m\"\n\n# Is video recording enabled for this build\nVIDEO=\"on\"\n\n# Add a TestFairy watermark to the application icon?\nICON_WATERMARK=\"on\"\n\n# Comment text will be included in the email sent to tester
1s\nCOMMENT=\"New Build\"\n\n# locations of various tools\nCURL=/usr/bin/curl\nZIP=/usr/bin/zip\nKEYTOOL=/usr/bin/keytool\nZIPALIGN=/Applications/adt-bundle-mac-x86_64-20130917/sdk/build-tools/19.1.0/zipalign\nJARSIGNER=/usr/bin/jarsigner\n\nSERVER_ENDPOINT=http://app.testfairy.com\n\nusage() {\n    echo \"Usage: testfairy-upload.sh bin/TennisTV.apk\"\n    echo\n}\n\nverify_tools() {\n\n    # Windows users: this script requires zip, curl, and sed. If not installed please get from http://cygwin.com/\n\n    # Check 'zip' tool\n    ${ZIP} -h \u003e/dev/null\n    if [ $? -ne 0 ]; then\n        echo \"Could not run zip tool, please check settings\"\n        exit 1\n    fi\n\n    # Check 'curl' tool\n    ${CURL} --help \u003e/dev/null\n    if [ $? -ne 0 ]; then\n        echo \"Could not run curl tool, please check settings\"\n        exit 1\n    fi\n\n    OUTPUT=$( ${JARSIGNER} -help 2\u003e\u00261 | grep \"verify\" )\n    if [ $? -ne 0 ]; then\n        echo \"Could not run jarsigner tool, please check settings\"\n        exit 1\n    fi\n\n    # Check 'zipalign' tool\n    OUTPUT=$( ${ZIPALIGN} 2\u003e\u00261 | grep -i \"Zip alignment\" )\n    if [ $? -ne 0 ]; then\n        echo \"Could not run zipalign tool, please check settings\"\n        exit 1\n    fi\n\n    OUTPUT=$( ${KEYTOOL} -help 2\u003e\u00261 | grep \"keypasswd\" )\n    if [ $? -ne 0 ]; then\n        echo \"Could not run keytool tool, please check settings\"\n        exit 1\n    fi\n}\n\nverify_settings() {\n    if [ -z \"${TESTFAIRY_API_KEY}\" ]; then\n        usage\n        echo \"Please update API_KEY with your private API key, as noted in the Settings page\"\n        exit 1\n    fi\n\n    if [ -z \"${KEYSTORE}\" -o -z \"${STOREPASS}\" -o -z \"{$ALIAS}\" ]; then\n        usage\n        echo \"Please update KEYSTORE, STOREPASS and ALIAS with your jar signing credentials\"\n        exit 1\n    fi\n\n    # verify KEYSTORE, STOREPASS and ALIAS at once\n    OUTPUT=$( ${KEYTOOL} -list -keystore \"${KEYSTORE}\" -storepass \"${STOREPASS}\" -alias \"${ALIAS}\" 2\u003e\u00261 )\n    if [ $? -ne 0 ]; then\n        usage\n        echo \"Please check keystore credentials; keytool failed to verify storepass and alias\"\n        exit 1\n    fi\n}\n\nif [ $# -ne 2 ]; then\n    usage\n    exit 1\nfi\n\n# before even going on, make sure all tools work\nverify_tools\nverify_settings\n\nAPK_FILENAME=$1\nif [ ! -f \"${APK_FILENAME}\" ]; then\n    usage\n    echo \"Can't find file: ${APK_FILENAME}\"\n    exit 2\nfi\n\nCOMMENT=$2\n\n# temporary file paths\nDATE=`date`\nTMP_FILENAME=.testfairy.upload.apk\nZIPALIGNED_FILENAME=.testfairy.zipalign.apk\nrm -f \"${TMP_FILENAME}\" \"${ZIPALIGNED_FILENAME}\"\n\n/bin/echo -n \"Uploading ${APK_FILENAME} to TestFairy.. \"\nJSON=$( ${CURL} -s ${SERVER_ENDPOINT}/api/upload -F api_key=${TESTFAIRY_API_KEY} -F apk_file=\"@${APK_FILENAME}\" -F icon-watermark=\"${ICON_WATERMARK}\" -F video=\"${VIDEO}\" -F max-duration=\"${MAX_DURATION}\" -F comment=\"${COMMENT}\" -A \"TestFairy Command Line Uploader ${UPLOADER_VERSION}\" )\n\nURL=$( echo ${JSON} | sed 's/\\\\//\\//g' | sed -n 's/.*\"instrumented_url\"\\s*:\\s*\"\\([^\"]*\\)\".*/\\1/p' )\nif [ -z \"${URL}\" ]; then\n    echo \"FAILED!\"\n    echo\n    echo \"Upload failed, please check your settings\"\n    exit 1\nfi\n\nURL=\"${URL}?api_key=${TESTFAIRY_API_KEY}\"\n\necho \"OK!\"\n/bin/echo -n \"Downloading instrumented APK.. \"\n${CURL} -L -o ${TMP_FILENAME} -s ${URL}\n\nif [ ! -f \"${TMP_FILENAME}\" ]; then\n    echo \"FAILED!\"\n    echo\n    echo \"Could not download APK back from the server, please contact [email protected]\"\n    exit 1\nfi\n\necho \"OK!\"\n\n/bin/echo -n \"Re-signing APK file.. \"\n${ZIP} -qd ${TMP_FILENAME} 'META-INF/*'\n${JARSIGNER} -keystore \"${KEYSTORE}\" -storepass \"${STOREPASS}\" -digestalg SHA1 -sigalg MD5withRSA ${TMP_FILENAME} \"${ALIAS}\"\n${JARSIGNER} -verify ${TMP_FILENAME} \u003e/dev/null\nif [ $? -ne 0 ]; then\n    echo \"FAILED!\"\n    echo\n    echo \"Jarsigner failed to verify, please check parameters and try again\"\n    exit 1\nfi\n\n${ZIPALIGN} -f 4 ${TMP_FILENAME} ${ZIPALIGNED_FILENAME}\nrm -f ${TMP_FILENAME}\necho \"OK!\"\n\n/bin/echo -n \"Uploading signed APK to TestFairy.. \"\nJSON=$( ${CURL} -s ${SERVER_ENDPOINT}/api/upload-signed -F api_key=${TESTFAIRY_API_KEY} -F apk_file=@${ZIPALIGNED_FILENAME} -F testers-groups=\"${TESTER_GROUPS}\" -F auto-update=\"${AUTO_UPDATE}\" -F notify=\"${NOTIFY}\")\nrm -f ${ZIPALIGNED_FILENAME}\n\nURL=$( echo ${JSON} | sed 's/\\\\//\\//g' | sed -n 's/.*\"build_url\"\\s*:\\s*\"\\([^\"]*\\)\".*/\\1/p' )\nif [ -z \"$URL\" ]; then\n    echo \"FAILED!\"\n    echo\n    echo \"Build uploaded, but no reply from the server. Please contact [email protected]\"\n    exit 1\nfi\n\necho \"OK!\"\necho\necho \"Build was successfully uploaded to TestFairy and is available at:\"\necho ${URL}\n```\n\nNow, we can run the above script by passing two arguments. One for the APK path and other is for comment for your build. This comment will be sent to the tester over email.\n\n```bash\n$ chmod a+x testfairy-upload.sh\n\n$ ./testfairy-upload.sh bin/MyApp.apk \"$@Your build update comment here\"\n```\n"])</script>
1<script>self.__next_f.push([1,"f1:T3a9b,"])</script>
1<script>self.__next_f.push([1,"\n### What is RecyclerView?\n\nIn Android 5.0 Lollipop, Android introduced RecyclerView widget. RecyclerView is flexible and efficient version of ListView. It is an container for rendering larger data set of views that can be recycled and scrolled very efficiently. RecyclerView is like traditional [ListView](/articles/android-listview-tutorial) widget, but with more flexibility to customizes and optimized to work with larger datasets. It uses a subclass of `RecyclerView.Adapter` for providing views that represent items in a data set.\n\nAndroid SDK doesn’t includes the `RecyclerView` class. You need to add the following support library graddle dependency to project `build.graddle` file.\n\n```groovy\ncompile 'com.android.support:recyclerview-v7:24.0.0'\n```\n\nThis guide explains how to use and customize RecyclerView in Android applications.\n\n### RecyclerView Example\n\nIn the course of this example we will download the data from JSON API, parse and display the items on RecyclerView. As you can notice in the following image, we will be using both RecyclerView and [CardView](/articles/android-cardview-example) for creating the App UI.\n\n[![android-recyclerview-example](/media/articles/258/Android-RecyclerView-Example-1.png)](http://stacktips.com)\n\nFollowing steps are required to complete the example:\n\n-   Create a new Android Application and add the required graddle dependencies\n-   Layout activity and add RecyclerView and ProgressBar\n-   Layout the RecyclerView row  item using CardView widget\n-   Create a Custom Adapter for RecyclerView\n-   Create main Activity to initialize UI, make HTTP Server request and render data on RecyclerView\n-   Responding to RecyclerView click event\n\n### Creating Android Project\n\nLet us begin with creating a new Android project in Android Studio. After the project is created, open app `build.graddle` file and add the following dependency libraries.\n\n```groovy\ndependencies {\n    compile 'com.android.support:recyclerview-v7:24.0.0'\n    compile 'com.android.support:cardview-v7:24.0.0'\n    compile 'com.squareup.picasso:picasso:2.5.2'\n    // ...\n}\n```\n\nNotice that, we have added RecyclerView, [CardView](/articles/android-cardview-example) support libraries and [Picasso](/articles/how-to-use-picasso-library-in-android) dependency module.\n\nPicasso is an Open Source image loader library created and maintained by Square. It is among the powerful image download and caching [library for Android.](http://stacktips.com/android/android-third-party-libraries-sdks \"Android third party libraries and SDK’s\")\n\n#### Adding Internet Permission:\n\nYou might be aware that, Android application must declare all the permissions that are required for application. As we need to download the data form server, we need to add the `INTERNET` permission. Declare the following permission in `AndroidManifest.xml` file.\n\n```xml\n\u003cuses-permission android:name=\"android.permission.INTERNET\" /\u003e\n```\n\n### Declaring RecyclerView Layout\n\nLet us now define the layout for Activity. We will add a RecyclerView and ProgressBar inside a [RelativeLayout](/articles/android-relativelayout-example). The progress bar will be displayed while the data data from REST API is being downloaded.\n\nCreate a new file `activity_main.xml` inside layout resource folder and paste the following snippets.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:id=\"@+id/activity_main\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:background=\"#f1f1f1\"\n    android:padding=\"12dp\"\n    tools:context=\"com.stacktips.recyclerview.MainActivity\"\u003e\n\n    \u003candroid.support.v7.widget.RecyclerView\n        android:id=\"@+id/recycler_view\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:layout_centerInParent=\"true\"/\u003e\n\n    \u003cProgressBar\n        android:id=\"@+id/progress_bar\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerInParent=\"true\"/\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n### RecyclerView Row Layout\n\nIn the example, each row item is represented by a `CardView` that hosts a RelativeLayout with an `ImageView` for the thumbnail and a `TextView` title. This layout resides in the file list\\_row.xml.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003candroid.support.v7.widget.CardView\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:cardview=\"http://schemas.android.com/apk/res-auto\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:layout_marginBottom=\"5dp\"\n    cardview:cardCornerRadius=\"2dp\"\n    cardview:cardElevation=\"3dp\"\n    cardview:cardUseCompatPadding=\"true\"\u003e\n\n    \u003cRelativeLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\u003e\n\n        \u003cImageView\n            android:id=\"@+id/thumbnail\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"180dp\"\n            android:layout_alignParentTop=\"true\"\n            android:scaleType=\"centerCrop\"\n            android:src=\"@drawable/placeholder\"/\u003e\n\n        \u003cTextView\n            android:id=\"@+id/title\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:layout_below=\"@+id/thumbnail\"\n            android:layout_centerVertical=\"true\"\n            android:layout_marginLeft=\"12dp\"\n            android:maxLines=\"3\"\n            android:padding=\"8dp\"\n            android:textAppearance=\"@style/TextAppearance.AppCompat.Headline\"\n            android:textColor=\"#444\"\n            android:textSize=\"18dp\"\n            android:textStyle=\"bold\"/\u003e\n\n    \u003c/RelativeLayout\u003e\n\u003c/android.support.v7.widget.CardView\u003e\n```\n\n### Creating RecyclerView Adapter\n\nAndroid RecyclerView includes special kind of adapter which works pretty much same as traditional Android adapters but with additional functionalities.It uses a subclass of `RecyclerView.Adapter` for providing views that represent items in a data set.\n\nThe additional functionalities of RecyclerView.Adapter are:\n\n-   It adds two new methods like `onCreateViewHolder()` and `onBindViewHolder()` to organize the code. You must override these two methods for inflate the view and to bind data to the view\n-   Implements a ViewHolder by default. Conceptually `RecyclerView.ViewHolder` works same as the ViewHolder design pattern which we have been using with other Adapters\n-   Takes care of the overhead of recycling and gives better performance and scrolling\n\nCreate a new class MyRecyclerViewAdapter.class and copy the following snippets.\n\n```java\npublic class MyRecyclerViewAdapter extends RecyclerView.Adapter\u003cMyRecyclerViewAdapter.CustomViewHolder\u003e {\n    private List\u003cFeedItem\u003e feedItemList;\n    private Context mContext;\n\n    public MyRecyclerViewAdapter(Context context, List\u003cFeedItem\u003e feedItemList) {\n        this.feedItemList = feedItemList;\n        this.mContext = context;\n    }\n\n    @Override\n    public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {\n        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);\n        CustomViewHolder viewHolder = new CustomViewHolder(view);\n        return viewHolder;\n    }\n\n    @Override\n    public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {\n        FeedItem feedItem = feedItemList.get(i);\n\n        //Render image using Picasso library\n        if (!TextUtils.isEmpty(feedItem.getThumbnail())) {\n            Picasso.with(mContext).load(feedItem.getThumbnail())\n                    .error(R.drawable.placeholder)\n                    .placeholder(R.drawable.placeholder)\n                    .into(customViewHolder.imageView);\n        }
1\n\n        //Setting text view title\n        customViewHolder.textView.setText(Html.fromHtml(feedItem.getTitle()));\n    }\n\n    @Override\n    public int getItemCount() {\n        return (null != feedItemList ? feedItemList.size() : 0);\n    }\n\n    class CustomViewHolder extends RecyclerView.ViewHolder {\n        protected ImageView imageView;\n        protected TextView textView;\n\n        public CustomViewHolder(View view) {\n            super(view);\n            this.imageView = (ImageView) view.findViewById(R.id.thumbnail);\n            this.textView = (TextView) view.findViewById(R.id.title);\n        }\n    }\n}\n```\n\nNotice that we have created an private ViewHolder class. The ViewHolder class contains the reference to the each of the ui widget on the row.\n\nThe `FeedItem` class is an model class that holds the parsed data retrieved from JSON API. Add a new new file `FeedItem.java` class in your project source folder and add the following.\n\n```java\npublic class FeedItem {\n    private String title;\n    private String thumbnail;\n\n    public String getTitle() {\n        return title;\n    }\n\n    public void setTitle(String title) {\n        this.title = title;\n    }\n\n    public String getThumbnail() {\n        return thumbnail;\n    }\n\n    public void setThumbnail(String thumbnail) {\n        this.thumbnail = thumbnail;\n    }\n}\n```\n\n### Activity Using RecyclerView\n\nThe resulting RecyclerView implementation for this example app consists of MainActivity initialization code. MainActivity creates the mRecyclerView instance, download and parse the data from JSON API, instantiates the adapter and plugs in the adapter to RecyclerView.\n\nThe focus of this tutorial is narrow down to RecyclerView, hence it doesn’t include any explanation for download and parse data from server. For learning how to download data from server, you may read [Android Networking Tutorial.](http://stacktips.com/android/android-networking-tutorial)\n\nOnce data is downloaded, inside `onPostExecute()` we are initializing the adapter and setting adapter to RecyclerView instance by just calling `setAdapter()` method.\n\n```java\npublic class MainActivity extends AppCompatActivity {\n    private static final String TAG = \"RecyclerViewExample\";\n    private List\u003cFeedItem\u003e feedsList;\n    private RecyclerView mRecyclerView;\n    private MyRecyclerViewAdapter adapter;\n    private ProgressBar progressBar;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);\n        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));\n        progressBar = (ProgressBar) findViewById(R.id.progress_bar);\n\n        String url = \"http://stacktips.com/?json=get_category_posts\u0026slug=news\u0026count=30\";\n        new DownloadTask().execute(url);\n    }\n\n    public class DownloadTask extends AsyncTask\u003cString, Void, Integer\u003e {\n\n        @Override\n        protected void onPreExecute() {\n            progressBar.setVisibility(View.VISIBLE);\n        }\n\n        @Override\n        protected Integer doInBackground(String... params) {\n            Integer result = 0;\n            HttpURLConnection urlConnection;\n            try {\n                URL url = new URL(params[0]);\n                urlConnection = (HttpURLConnection) url.openConnection();\n                int statusCode = urlConnection.getResponseCode();\n\n                // 200 represents HTTP OK\n                if (statusCode == 200) {\n                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n                    StringBuilder response = new StringBuilder();\n                    String line;\n                    while ((line = r.readLine()) != null) {\n                        response.append(line);\n                    }\n                    parseResult(response.toString());\n                    result = 1; // Successful\n                } else {\n                    result = 0; //\"Failed to fetch data!\";\n                }\n            } catch (Exception e) {\n                Log.d(TAG, e.getLocalizedMessage());\n            }\n            return result; //\"Failed to fetch data!\";\n        }\n\n        @Override\n        protected void onPostExecute(Integer result) {\n            progressBar.setVisibility(View.GONE);\n\n            if (result == 1) {\n                adapter = new MyRecyclerViewAdapter(MainActivity.this, feedsList);\n                mRecyclerView.setAdapter(adapter);\n            } else {\n                Toast.makeText(MainActivity.this, \"Failed to fetch data!\", Toast.LENGTH_SHORT).show();\n            }\n        }\n    }\n\n    private void parseResult(String result) {\n        try {\n            JSONObject response = new JSONObject(result);\n            JSONArray posts = response.optJSONArray(\"posts\");\n            feedsList = new ArrayList\u003c\u003e();\n\n            for (int i = 0; i \u003c posts.length();
1 i++) {\n                JSONObject post = posts.optJSONObject(i);\n                FeedItem item = new FeedItem();\n                item.setTitle(post.optString(\"title\"));\n                item.setThumbnail(post.optString(\"thumbnail\"));\n                feedsList.add(item);\n            }\n        } catch (JSONException e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n\n### Handle RecyclerView Click Event\n\nHandling click event on RecyclerView is not as sweet as handling click listener in ListView or GridView. Android RecyclerView doesn’t provide any built in listeners or handy way of handling click events.\n\nLet us declare a interface that specifies listener’s behavior. When user clicks on the RecyclerView the listener will return the FeedItem for the selected row.\n\n```java\npublic interface OnItemClickListener {\n    void onItemClick(FeedItem item);\n}\n```\n\nNow turn on to adapter and declare an instance variable of OnItemClickListener along with getter and setter methods.\n\n```java\nprivate OnItemClickListener onItemClickListener;\npublic OnItemClickListener getOnItemClickListener() {\n    return onItemClickListener;\n}\n\npublic void setOnItemClickListener(OnItemClickListener onItemClickListener) {\n    this.onItemClickListener = onItemClickListener;\n}\n```\n\nIn activity class, let set the click listener to adapter by calling setOnItemClickListener() method.\n\n```java\nadapter.setOnItemClickListener(new OnItemClickListener() {\n    @Override\n    public void onItemClick(FeedItem item) {\n        Toast.makeText(MainActivity.this, item.getTitle(), Toast.LENGTH_LONG).show();\n\n    }\n});\n```\n\nNow, attach the View.OnClickListener to each of the view you want to handle click. Add the following snippet to onBindViewHolder of the RecyclerView.Adapter. When ImageView or TextView is clicked, we will receive the event back to the caller activity.\n\n```java\nView.OnClickListener listener = new View.OnClickListener() {\n    @Override\n    public void onClick(View v) {\n        onItemClickListener.onItemClick(feedItem);\n    }\n};\ncustomViewHolder.imageView.setOnClickListener(listener);\ncustomViewHolder.textView.setOnClickListener(listener);\n```\n"])</script>
1<script>self.__next_f.push([1,"f2:T1725,"])</script>
1<script>self.__next_f.push([1,"\n### 1. What is the purposes of Service in Android?\n\nAndroid Service is used to perform long running jobs off the UI thread. A typical long running tasks can be periodic downloading of data from internet, saving multiple records into database, perform file I/O, fetching your phone contacts list, etc. For such long running tasks, Service is used to avoid UI lags and makes user experience better.\n\n### 2. Explain service lifecycle methods?\n\nA service can be run by the system, If someone calls Context.startService() or bindService() method.\n\n1.  **onStartCommand()** – This method is called when the service be started by calling startService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). If you are defining your service as, bounded service then you don’t need to implement this method.\n2.  **onBind()** – You need to override this method, only if you are defining your service as bounded service. This method is called, when another component wants to bind with the service by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don’t want to allow binding, then you should return null.\n3.  **onCreate()**– This method is called while the service is first created. Here all the service initialization is done. This method is never called again.\n4.  **onDestroy()** – The system calls this method when the service is no longer used and is being destroyed. This method is used to, clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.\n\n### 3. What is the difference between bound and unbounded service?\n\n1.  **Bound Service –** Service which call indefinitely in between activity. An Android component may bind itself to a Service using bindservice (). A bound service would run as long as the other application components are bound to it. As soon as they unbind, the service destroys itself.\n2.  **Unbound Service –** Service which call at the life span of calling activity. In this case, an application component starts the service, and it would continue to run in the background, even if the original component that initiated it is destroyed. For instance, when started, a service would continue to play music in the background indefinitely.\n\n### 4. What are the different clock types supported for AlarmService?\n\nAndroid supports two clock types for alarm service. Once is elapsed real time and other is real time clock (RTC). Elapsed real time uses the time since device last booted. Real time clock (RTC) uses UTC time for alarm service clock. RTC is most commonly used for setting alarm service in android.\n\n### 5. How to define a service in manifest\n\nAll the services used in the app need to be registered in application Manifest. Services are declared as shown below\n\n```xml\n\u003c!--Service declared in manifest --\u003e\n\u003cservice android:name=\".HelloService\"\nandroid:exported=\"false\"/\u003e\n```\n\n### 6. How to pass data to an IntentService ?\n\nYou can pass data as bundle to IntentService before you start.\n\n```java\nIntent intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class);\n\n/* Send optional extras to Download IntentService */\nintent.putExtra(\"url\", url);\nintent.putExtra(\"receiver\", mReceiver);\nintent.putExtra(\"requestId\", 101);\n\nstartService(intent);\n```\n\n### 7. What is an alarm service and explain it’s need with real-world example\n\nAlarm service is used to run tasks periodically at given interval. You can design application like alrm, birthday reminder, or AlarmManager can be used to initiate long running operations such as syncing data from server once a day. Once an Alarm Started, this will execute until it is stopped explicitly or until device reboots.\n\n### 8. How to stop service?\n\nBounded service stops itself once it finishes its tasks. But for unbounded service we need to call stopSelf() or stopService() method.\n\n### 9. Can an IntentService execute multiple tasks sequentially?\n\nNo. Intent Services are designed to perform one task at single point of time. However tasks can be queued.\n\n### 10. How can we make the AlarmService run forever even after device reboot\n\nOnce you start an AlarmService, it runs forever until your device restarts. Once your device restart, you have to start the service explicitly to run it forever again. You have to register BroadcastReceiver to handle boot event.\n\n### 11. What are the key differences between a service and IntentService in Android?\n\n| Service | IntentService |\n| --- | --- |\n| Service can be used in tasks with 
1no UI, but shouldn’t be too long. If you need to perform long tasks, you must create a new thread with in Service | IntentService can be used in long running tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. |\n| Service can be started using startService() method | IntentService can be started using startService() method and it triggers onHandleIntent() method. |\n| Service can be triggered from any thread | IntentService must be triggered from Main Thread |\n| Service runs in background but it runs on the Main Thread of the application. | IntentService runs on a separate worker thread |\n| The Service may block the Main Thread of the application. | The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially. |\n| You must call stopSelf() or stopService() to stop a service once your its job is done. | IntentService stops itself when it finishes its job so you never have to call stopSelf() |\n"])</script>
1<script>self.__next_f.push([1,"f3:T13c6,"])</script>
1<script>self.__next_f.push([1,"\nHere in this post, you will find compiled set of android interview questions and answers. These questions are intended for freshers and android learners. I am on my way publishing the more advance interview questions sets.\n\n### 1. When does onResume() method called?\n\nonResume() method is an activity lifecycle method. This is called when the activity come to foreground. You can override this method in your activity to execute code when activity is started, restarted or comes to foreground.\n\n### 2. How to launch an activity in your application?\n\nFor launching an activity, we need to create an explicit intent that defines the activity that we wish to start. In the below code snippet, the first parameter to Intent constructor is the current activity context and the second parameter is your new activity `class.startActivity()` method can be called on Activity context.\n\n```java\nIntent intent = new Intent(this, SecondActivity.class);\nstartActivity(intent);\n```\n\nIf you want to start an activity from fragment\n\n```java\nIntent intent = new Intent(getActivity(), SecondActivity.class);\ngetActivity().startActivity(intent);\n```\n\n### 3. How to define an Activity as launcher activity in application Manifest file?\n\nAll the activities used in the application should be defined in application manifest file. For launcher activity you need to define intent filter as shown in the below code snippets.\n\n```xml\n\u003cactivity android:name=\".MyActivity\"\n              android:label=\"@string/app_name\"\u003e\n        \u003cintent-filter\u003e\n            \u003caction android:name=\"android.intent.action.MAIN\" /\u003e\n            \u003ccategory android:name=\"android.intent.category.LAUNCHER\" /\u003e\n        \u003c/intent-filter\u003e\n    \u003c/activity\u003e\n```\n\n### 4. What is a ANR ?\n\nANR is short for Application Not Responding. Android systems shows this dialog, if application is performing too much of task on main thread and been unresponsive for a long period of time.\n\n### 5. What are the measures to avoid application ANR?\n\nANR in application is annoying to user. It can be caused due to various reasons. Below are some of the tips to avoid ANR\n\n-   Perform all you long running network or database operation in separate thread\n-   If you have too much of background tasks, then take it off the UI thread. You may use IntentService\n-   Server not responding for longer period can be guilt for ANR. To avoid always define HTTP time out for your all your webs service calls.\n-   Be watchful of infinite loops during your complex calculations\n\n### 6. What is the difference between a regular .png and a nine-patch image?\n\nThe nine patch images are extension with `.9.png`. Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.\n\n### 7. How to share text using android share Intent ?\n\nShare intent is an easy and convenient way of sharing content of your application with other apps.\n\n```java\nIntent sendIntent = new Intent();\nsendIntent.setAction(Intent.ACTION_SEND);\nsendIntent.putExtra(Intent.EXTRA_TEXT, \"This is my text to send.\");\nsendIntent.setType(\"text/plain\");\nstartActivity(sendIntent);\n```\n\n### 8. What is the use of WebView in android?\n\nA WebView is an android UI component that displays webpages. It can either display a remote webpage or can also load static HTML data. This encompasses the functionality of a browser that can be integrated to application. WebView uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, etc.\n\n### 9. Define different kind of context in android\n\nContext defines the current state of application or object. Context provides access to things such as creating new activity instance, access databases, start a service, etc. You can get the context by invoking `getApplicationContext()`, `getContext()`, `getBaseContext()` or `this` when in the activity class.\n\n```java\n//Creating ui instance\nImageButton button = new ImageButton(getContext());\n\n//creating adapter\nListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);\n\n//querying content provider\ngetApplicationContext().getContentResolver().query(uri, ...);\n\n//start activity. Here this means activity context\nIntent intent = new Intent(this, SecondActivity.class);\n```\n\n### 10. What are the different storage methods in android\n\nAndroid offers several different options for data persistence.\n\n1.  **Shared Preferences** – Store private primitive data in key-value pairs. This sometimes gets limited as it offers only key value pairs. You cannot save your own java types.\n2.  **Internal Storage** – Store private data on the device memory\n3.  **External Storage** – Store public data on the shared external storage\n4.  **SQLite Databases** – Store structured data in a private database. You can define many number of tables and can store data like other RDBMS.\n"])</script>
1<script>self.__next_f.push([1,"f4:T2bff,"])</script>
1<script>self.__next_f.push([1,"\nScheduling and repeating alarms are generally used as a local reminder to notify user about some event. For example, a mobile live TV streaming application can use local reminder to notify users when a specific program starts. Note that, this is different form Server push notification, mainly because it is purely managed by mobile client.\n\n## 1. AlarmManager in Android\n\n`AlarmManager` is a class in Android allows you to access device system alarm service. Using AlarmManager, you can schedule to execute certain piece of code a particular time. Let us dive into details of AlarmManager specifics:\n\n-   AlarmManager runs outside the lifetime of your application. Once an alarm is scheduled, it will invoke even when your application is not running or in sleep mode.\n-   An scheduled alarm will execute unless it is stopped explicitly by calling cancel() method, or until device reboots.\n-   All scheduled alarms will be stopped when device reboots. This means, you need to re-schedule them explicitly when device boot completes.\n-   AlarmManger fires an `Intent` at given intervals. This can be used along with broadcast receivers to start a service to perform network operations.\n-   AlarmManager is different form java `Timer` and `TimerTask.`\n\nNote, You need to take extra care while working with AlarmManager. A poorly designed AlarmManager can drain your device battery.\n\n## 2. Setting Repeat Alarm\n\nAndroid supports two clock types for alarm service; elapsed real time and real time clock (RTC). Elapsed real time uses the time since device last booted. Real time clock (RTC) uses UTC time for alarm service clock. RTC is most commonly used for setting alarm service in android. The following example, using RTC to schedule alarm.\n\nThe application using a single activity containing three buttons. One button is for starting an alarm service, another to cancel scheduled alarm. The third button is to start the alarm at specified calendar time. For example, if you have set a time for your birthday reminder. It will invoke at 10:30 PM and will repeat on every 30 mins.\n\nLet us have a look into our activity layout file (my\\_activity.xml)\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:paddingBottom=\"@dimen/activity_vertical_margin\"\n    android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n    android:paddingRight=\"@dimen/activity_horizontal_margin\"\n    android:paddingTop=\"@dimen/activity_vertical_margin\"\n    tools:context=\".MyActivity\"\u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginBottom=\"20dp\"\n        android:text=\"@string/hint\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/startAlarm\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentLeft=\"true\"\n        android:layout_alignParentStart=\"true\"\n        android:layout_below=\"@+id/textView\"\n        android:layout_marginBottom=\"20dp\"\n        android:text=\"Start Alarm Service\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/stopAlarm\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_below=\"@+id/startAlarm\"\n        android:layout_marginBottom=\"20dp\"\n        android:text=\"Stop Alarm\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/stopAlarmAt10\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_below=\"@+id/stopAlarm\"\n        android:text=\"Stop Alarm at 10:30\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n[![AlarmManager Example in Android](/media/articles/261/AlarmManager-Example-in-Android-620x433.png)](http://stacktips.com)\n\n## 3. Defining Alarm BroadcastReceiver\n\nIn this example, we are associating alarm service with broadcast receiver. Alarm service will invoke this receiver on scheduled time. For the sake of simplicity we are just showing an toast to user for each time the alarm is invoked. You may write your logic to start a service or download task.\n\n**Note:** If your alarm has to perform network task, then start a download service inside `onRecieve()` method of your alarm broadcast.\n\n```java\npackage com.javatechig.alarmservice;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.widget.Toast;\n\npublic class AlarmReceiver extends BroadcastReceiver {\n\n    @Override\n    public void onReceive(Context context, Intent intent) {\n\n        // For our recurring task, we'll just display a message\n        Toast.makeText(context, \"I'm running\", Toast.LENGTH_SHORT).show();\n    }\n}\n```\n\n## 4. Schedule \u0026 Cancel Alarm\n\nIn the above two steps we have defined activity layout and alarm broadcast receiver. Let us have a look into MainActivity.java file. Inside MyActivity class, we have defined three simple methods start(), stop() and startAt10(). The start() method schedule the alarm, cancel() method cancel the scheduled alarm, and startAt!0() method will start the alarm at 10:30 PM with a fixed 20 minutes interval.\n\n```java\npackage com.javatechig.alarmservice;\n\nimport android.app.Activity;\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Toast;\nimport java.util.Calendar;\n\npublic class MyActivity extends Activity {\n\n    private PendingIntent pendingIntent;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_my);\n\n        /* Retrieve a PendingIntent that will perform a broadcast */\n        Intent alarmIntent = new Intent(MyActivity.this, AlarmReceiver.class);\n        pendingIntent = PendingIntent.getBroadcast(MyActivity.this, 0, alarmIntent, 0);\n\n        findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                start();\n            }\n        });\n\n        findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                cancel();\n            }\n        });\n\n        findViewById(R.id.stopAlarmAt10).setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                startAt10();\n            }\n        });\n    }\n\n    public void start() {\n        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);\n        int interval = 8000;\n\n        manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);\n        Toast.makeText(this, \"Alarm Set\", Toast.LENGTH_SHORT).show();\n    }\n\n    public void cancel() {\n        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);\n        manager.cancel(pendingIntent);\n        Toast.makeText(this, \"Alarm Canceled\", Toast.LENGTH_SHORT).show();\n    }\n\n    public void startAt10() {\n        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);\n        int interval = 1000 * 60 * 20;\n\n        /* Set the alarm to start at 10:30 AM */\n        Calendar calendar = Calendar.getInstance();\n        calendar.setTimeInMillis(System.currentTimeMillis());\n        calendar.set(Calendar.HOUR_OF_DAY, 10);\n        calendar.set(Calendar.MINUTE, 30);\n\n        /* Repeating on every 20 minutes interval */\n        manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),\n                1000 * 60 * 20, pendingIntent);\n    }\n\n}\n```\n\n## 5. Re-Starting Alarm Service on Device Reboot\n\nAs discussed earlier, once an alarm service is started, it execute until it is explicitly stopped or until device reboots. This means that, if your device is restarted then your alarm is stopped. To avoid such situation, you have to restart your alarm service as soon as device boot completes. Below code snippet will help you to start alarm service once device reboots.\n\n```java\npackage com.javatechig.alarmservice;\n\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.widget.Toast;\n\n/**\n * @author Nilanchala\n *         \u003cp/\u003e\n *         Broadcast reciever, starts when the device gets starts.\n *         Start your repeating alarm here.\n */\npublic class DeviceBootReceiver extends BroadcastReceiver {\n\n    @Override\n    public void onReceive(Context context, Intent intent) {\n        if (intent.getAction().equals(\"android.intent.action.BOOT_COMPLETED\")) {\n            /* Setting the alarm here */\n            Intent alarmIntent = new Intent(context, AlarmReceiver.class);\n            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);\n\n            AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n            int interval = 8000;\n            manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);\n\n            Toast.makeText(context, \"Alarm Set\", Toast.LENGTH_SHORT).show();\n        }\n    }\n}\n```\n\n## 6. Declaring Application Manifest\n\nTo start your alarm on device reboot, you have to register your above declared `DeviceBootReciever` class in your application manifest. This also need `android.permission.RECEIVE_BOOT_COMPLETED`\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cmanifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.javatechig.alarmservice\" \u003e\n\n    \u003capplication\n        android:allowBackup=\"true\"\n        android:icon=\"@drawable/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:theme=\"@style/AppTheme\" \u003e\n\n        \u003c!-- Permission to start Alarm on device reboot --\u003e\n        \u003cuses-permission android:name=\"android.permission.RECEIVE_BOOT_COMPLETED\"/\u003e\n\n        \u003cactivity\n            android:name=\".MyActivity\"\n            android:label=\"@string/app_name\" \u003e\n            \u003cintent-filter\u003e\n                \u003caction android:name=\"android.intent.action.MAIN\" /\u003e\n                \u003ccategory android:name=\"android.intent.category.LAUNCHER\" /\u003e\n            \u003c/intent-filter\u003e\n        \u003c/activity\u003e\n\n        \u003creceiver android:name=\".AlarmReceiver\"\u003e\n          \u003cintent-filter\u003e\n               \u003caction android:name=\"android.intent.action.BOOT_COMPLETED\"/\u003e\n          \u003c/intent-filter\u003e\n        \u003c/receiver\u003e\n\n        \u003c!-- Will not be called unless the application explicitly enables it --\u003e\n        \u003creceiver android:name=\".DeviceBootReceiver\"\n            android:enabled=\"false\"\u003e\n            \u003cintent-filter\u003e\n                \u003caction android:name=\"android.intent.action.BOOT_COMPLETED\"/\u003e\n            \u003c/intent-filter\u003e\n        \u003c/receiver\u003e\n\n    \u003c/application\u003e\n\u003c/manifest\u003e\n```\n\n## 7. Download Source Code\n\nDownload Complete source code from [**GitHub**](https://github.com/javatechig/Android-Alarm-Service-Example)\n"])</script>
1<script>self.__next_f.push([1,"f5:Tef4,"])</script>
1<script>self.__next_f.push([1,"\nExcel is a widely used software for creating and managing data. In this tutorial, we will show you how to create an Excel file in Android using Java for Excel library. The Java for Excel library provides a simple and easy-to-use API for working with Excel files in Java.\n\n[android SQLite database tutorial](/articles/android-sqlite-database-tutorial \"Android SQLite Database Tutorial\"). We recommend you to have a glance at it before going through this example.  \n\nIn our previous example, we have explained you how to create an TODO application in android using SQLite database. Now in this post we will export the data saved in database to an excel file and will store it on SDCard.\n\n### Step-1\n\nDownload Java for Excel library from below path.  \n[http://jexcelapi.sourceforge.net/](http://jexcelapi.sourceforge.net/)  \n[http://sourceforge.net/projects/jexcelapi/files/](http://sourceforge.net/projects/jexcelapi/files/)\n\n### Step-2\n\nExport and save data from cursor into excel spreadsheet and saves the spreadsheet into external storage directory.\n\n```java\nprivate void exportToExcel(Cursor cursor) {\n    final String fileName = \"TodoList.xls\";\n\n    //Saving file in external storage\n    File sdCard = Environment.getExternalStorageDirectory();\n    File directory = new File(sdCard.getAbsolutePath() + \"/javatechig.todo\");\n\n    //create directory if not exist\n    if(!directory.isDirectory()){\n        directory.mkdirs();\n    }\n\n    //file path\n    File file = new File(directory, fileName);\n\n    WorkbookSettings wbSettings = new WorkbookSettings();\n    wbSettings.setLocale(new Locale(\"en\", \"EN\"));\n    WritableWorkbook workbook;\n\n    try {\n        workbook = Workbook.createWorkbook(file, wbSettings);\n        //Excel sheet name. 0 represents first sheet\n        WritableSheet sheet = workbook.createSheet(\"MyShoppingList\", 0);\n\n        try {\n            sheet.addCell(new Label(0, 0, \"Subject\")); // column and row\n            sheet.addCell(new Label(1, 0, \"Description\"));\n            if (cursor.moveToFirst()) {\n                do {\n                    String title = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TODO_SUBJECT));\n                    String desc = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TODO_DESC));\n\n                    int i = cursor.getPosition() + 1;\n                    sheet.addCell(new Label(0, i, title));\n                    sheet.addCell(new Label(1, i, desc));\n                } while (cursor.moveToNext());\n            }\n            //closing cursor\n            cursor.close();\n        } catch (RowsExceededException e) {\n            e.printStackTrace();\n        } catch (WriteException e) {\n            e.printStackTrace();\n        }\n        workbook.write();\n        try {\n            workbook.close();\n        } catch (WriteException e) {\n            e.printStackTrace();\n        }\n    } catch (IOException e) {\n        e.printStackTrace();\n    }\n}\n```\n\nThis code exports the contents of a Cursor object to an Excel file in the external storage of an Android device.\n\nThe method exportToExcel takes a Cursor object as a parameter, which contains the data to be exported. It first creates a file with the name \"TodoList.xls\" in a directory named \"javatechig.todo\" in the external storage of the device.  \n\nAfter creating the file, it creates a new Workbook object using the jxl library to create a new Excel workbook. It then creates a new sheet called \"MyShoppingList\" in the workbook.  \n\nThe code then loops through each row in the Cursor object, retrieves the data from the columns, and adds the data to the cells in the Excel sheet using the addCell method. The first row of the sheet contains the column headers \"Subject\" and \"Description\".  \n\nFinally, the workbook is written to the file, and the workbook and cursor objects are closed to release resources.\n"])</script>
1<script>self.__next_f.push([1,"f6:T14ca,"])</script>
1<script>self.__next_f.push([1,"\nOver past few years, the age of mobile development become an fiercely-competitive world of serious money making business. Android developers network is growing rapidly. As the network grows, there are many open source libraries available. Although using someone written code is not be recommended always, but sometimes it helps in getting the application quicker to market.\n\nThis post outlines some of the popular third party Android Libraries and SDK’s.\n\nIf you find some Library is missing from your favourite list, or discovered a new one, just drop us a comment. We will add it to the list.\n\n### User Interface Libraries\n\n| ActionBarSherlock | ActionBarSherlock is an extension of the support library designed to facilitate the use of the action bar design pattern across all versions of Android with a single API. ActionBarSherlock was widely used before Google introduced AppCompact. |\n| --- | --- |\n| ActionBar PullToRefresh | ActionBar PullToRefresh provides an easy way to add a modern version of the pull-to-refresh interaction to your application. |\n| Android PullToRefresh | This project aims to provide a reusable Pull to Refresh widget for Android. It was originally based on Johan Nilsson’s library (mainly for graphics, strings and animations), but these have been replaced since. |\n| View Pager Indicator | Paging indicator widgets compatible with the ViewPager from the Android Support Library and ActionBarSherlock. |\n| Nine Old Android | Android library for using the Honeycomb (Android 3.0) animation API on all versions of the platform back to 1.0! Animation prior to Honeycomb was very limited in what it could accomplish so in Android 3.x a new API was written. |\n| A Chart Engine | AChartEngine is a charting library for Android applications. It currently supports all major and widely used chart types. |\n\n### Android Networking Libraries\n\n| okHttp | HTTP is the way modern applications network. It’s how we exchange data \u0026 media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth. |\n| --- | --- |\n| Volley | Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available through the open AOSP repository. |\n| Android Asynchronous Http Client | An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing. |\n| Google GSON | Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. |\n| Retrofit | Retrofit is a type-safe REST client for Android and Java. This uses annotation to describe HTTP server calls. This is an elegant solution for managing REST API calls in in android application. |\n| Fast Android Networking | Fast Android Networking Library is a powerful library for doing any type of networking in Android applications which is made on top of OkHttp Networking Layer. |\n\n### Image Downloading And Caching Libraries\n\n| Picasso | A powerful image downloading and caching library for Android.Example |\n| --- | --- |\n| Universal Image Loader | UIL aims to provide a powerful, flexible and highly customizable instrument for image loading, caching and displaying. It provides a lot of configuration options and good control over the image loading and caching process.Example |\n\n### Database Helper Libraries\n\n| ActiveAndroid | ActiveAndroid is an active record style ORM (object relational mapper). It allows you to save and retrieve SQLite database records without ever writing a single SQL statement. Each database record is wrapped neatly into a class with methods like save() and delete(). |\n| --- | --- |\n| ORM Lite | Object Relational Mapping Lite (ORM Lite) provides some simple, lightweight functionality for persisting Java objects to SQL databases while avoiding the complexity and overhead of more standard ORM packages. |\n| Green DOA | GreenDAO is an open source project to help Android developers working with data stored in SQLite. GreenDAO does all the SQLite helper work for you. It maps Java objects to database tables (often called ORM). This way you can store, update, delete, and query for Java objects using a simple object oriented API. |\n\n### Other Android Libraries\n\n| Android Anotaion Framework | AndroidAnnotations is an Open Source framework that speeds up Android development. It takes care of the plumbing, and lets you concentrate on what’s really important. By simplifying your co
1de, it facilitates its maintenance. |\n| --- | --- |\n| EventBus | EventBus works on publisher, subscriber model similar to Observer design pattern. This helps in hassel free communication between Activities, Fragments, and background threads. |\n| Otto | An enhanced Guava-based event bus with emphasis on Android support. Otto is an event bus designed to decouple different parts of your application while still allowing them to communicate efficiently. |\n| Dragger | Dragger is a faster dependency injector for Android and Java |\n"])</script>
1<script>self.__next_f.push([1,"f7:T386d,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial we will take a look into one of most important and commonly used Android concept called IntentService. This post explains steps involved in creating a background service in Android using IntentService. Before you start with this post, we recommend you to have a glance at below posts\n\n**\\* [Checkout Android Service Tutorial](http://stacktips.com/android/android-service-example \"Android Service Example\")**\n\n**\\* [Android Networking Tutorial](http://stacktips.com/android/android-networking-tutorial \"Android Networking Tutorial\")**\n\n# 1. What is IntentService?\n\nIntentService is a subclass of `android.app.Service` class. A stated intent service allows to handle long running tasks without effecting the application UI thread. This is not bound to any activity so, it is not getting effected for any change in activity lifecycle. Once IntentService is started, it handles each Intent using a worker thread and stops itself when it runs out of work.\n\nIntentService would be an best solution, If you have an work queue to process. For example, if your application using analytics you will likely to send event name and related parameter to your tracking server for each user generated event. Although each event means a tiny piece of data, creating networking request on each click will result an overhead to your application. Instead, you can use work queue processor design pattern and process the events in a batch.\n\n# 2. IntentService Limitations\n\n1.  No easy or direct way to interact with user interface directly from IntentService. Later in this example, we will explain to pass result back from IntentService to\n2.  With IntentService, there can only be one request processed at any single point of time. If you request for another task, then the new job will wait until the previous one is completed. This means that IntentService process the request\n3.  An tasks stated using IntentService cannot be interrupted\n\n# 3. Why do we need IntentService?\n\nAndroid design guidelines strongly suggests to perform all the long running tasks off the UI thread. For example, if you have to periodically download the largest chunk of data from server, you must use IntentService to avoid ANR. ANR (Application not responding) message often occurs, if your main thread is doing too much of work. In this course of this tutorial, we will learn the below concepts\n\n1.  How to create and use IntentService\n2.  How to pass data from activity to service as parameter\n3.  How to pass result back to activity\n4.  Update activity based on the result\n\n#### Case Study\n\nTo make this tutorial easy to understand we will extend our previous tutorial ([Android Networking Tutorial](http://stacktips.com/android/android-networking-tutorial \"Android Networking Tutorial\")) to use Intent Service for downloading the data from server. We suggest you to checkout **[Android Networking Example](http://stacktips.com/android/android-networking-tutorial)** to get familiar with downloading data from server using different http clients available in Android.\n\n**Feed Url : [http://stacktips.com/api/get\\_category\\_posts/?dev=1\u0026slug=android](http://stacktips.com/api/get_category_posts/?dev=1\u0026slug=android)**\n\n**Expected Result** Start service to download the data when application is started. Once download is complete, update ListView present in your activity.\n\n**Feed Response Object**\n\n[![JSON Feed Response](/media/articles/264/JSON-Feed-Response.png)](http://stacktips.com)\n\n# 4. Create an IntentService\n\nIn the context of our example, we will create an IntentService to download the data from server. Once download is completed, the response will be sent back to activity. Lets create a new class `DownloadService.java` and extend it from `android.app.IntentService`. Now let us override `onHandleIntent()` method.\n\nWhen service is started the onHandleIntent() method is called on the worker thread.Unlike Service, IntentService stops itself once it completes its task, so you don’t need to call stopSelf() for stoping the IntentService.\n\n```java\npackage com.javatechig.intentserviceexample;\n\nimport android.app.IntentService;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.os.ResultReceiver;\nimport android.text.TextUtils;\nimport android.util.Log;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\nimport java.io.BufferedInputStream;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\npublic class DownloadService extends IntentService {\n\n    public static final int STATUS_RUNNING = 0;\n    public static final int STATUS_FINISHED = 1;\n    public static final int STATUS_ERROR = 2;
1\n\n    private static final String TAG = \"DownloadService\";\n\n    public DownloadService() {\n        super(DownloadService.class.getName());\n    }\n\n    @Override\n    protected void onHandleIntent(Intent intent) {\n\n        Log.d(TAG, \"Service Started!\");\n\n        final ResultReceiver receiver = intent.getParcelableExtra(\"receiver\");\n        String url = intent.getStringExtra(\"url\");\n\n        Bundle bundle = new Bundle();\n\n        if (!TextUtils.isEmpty(url)) {\n            /* Update UI: Download Service is Running */\n            receiver.send(STATUS_RUNNING, Bundle.EMPTY);\n\n            try {\n                String[] results = downloadData(url);\n\n                /* Sending result back to activity */\n                if (null != results \u0026\u0026 results.length \u003e 0) {\n                    bundle.putStringArray(\"result\", results);\n                    receiver.send(STATUS_FINISHED, bundle);\n                }\n            } catch (Exception e) {\n\n                /* Sending error message back to activity */\n                bundle.putString(Intent.EXTRA_TEXT, e.toString());\n                receiver.send(STATUS_ERROR, bundle);\n            }\n        }\n        Log.d(TAG, \"Service Stopping!\");\n        this.stopSelf();\n    }\n\n    private String[] downloadData(String requestUrl) throws IOException, DownloadException {\n        InputStream inputStream = null;\n        HttpURLConnection urlConnection = null;\n\n        /* forming th java.net.URL object */\n        URL url = new URL(requestUrl);\n        urlConnection = (HttpURLConnection) url.openConnection();\n\n        /* optional request header */\n        urlConnection.setRequestProperty(\"Content-Type\", \"application/json\");\n\n        /* optional request header */\n        urlConnection.setRequestProperty(\"Accept\", \"application/json\");\n\n        /* for Get request */\n        urlConnection.setRequestMethod(\"GET\");\n        int statusCode = urlConnection.getResponseCode();\n\n        /* 200 represents HTTP OK */\n        if (statusCode == 200) {\n            inputStream = new BufferedInputStream(urlConnection.getInputStream());\n            String response = convertInputStreamToString(inputStream);\n            String[] results = parseResult(response);\n            return results;\n        } else {\n            throw new DownloadException(\"Failed to fetch data!!\");\n        }\n    }\n\n    private String convertInputStreamToString(InputStream inputStream) throws IOException {\n\n        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));\n        String line = \"\";\n        String result = \"\";\n\n        while ((line = bufferedReader.readLine()) != null) {\n            result += line;\n        }\n\n            /* Close Stream */\n        if (null != inputStream) {\n            inputStream.close();\n        }\n\n        return result;\n    }\n\n    private String[] parseResult(String result) {\n\n        String[] blogTitles = null;\n        try {\n            JSONObject response = new JSONObject(result);\n            JSONArray posts = response.optJSONArray(\"posts\");\n            blogTitles = new String[posts.length()];\n\n            for (int i = 0; i \u003c posts.length(); i++) {\n                JSONObject post = posts.optJSONObject(i);\n                String title = post.optString(\"title\");\n                blogTitles[i] = title;\n            }\n\n        } catch (JSONException e) {\n            e.printStackTrace();\n        }\n        return blogTitles;\n    }
1\n\n    public class DownloadException extends Exception {\n\n        public DownloadException(String message) {\n            super(message);\n        }\n\n        public DownloadException(String message, Throwable cause) {\n            super(message, cause);\n        }\n    }\n}\n```\n\n#### How it works\n\n1.  DownloadService class extending `IntentService` and overriding `onHandleIntent()` method. In onHandleIntent() method we will perform our network request to download data from server\n2.  Before it downloads the data from server, the request is being fetched from bundle. Our Activity will send this data as extras while starting the\n3.  Once Download is successful we will send the response back to activity via `ResultReceiver`\n4.  For any exceptions or error, we will pass the error response back to activity via ResultReceiver.\n5.  We have declared custom exception class `DownloadException` for handling all our custom error messages. You may do this\n\n# 5. Declaring Service in the Manifest\n\nLike `Service`, an IntentService also needs an entry in your application manifest. Provide the element entry and declare all your IntentServices you using. Additionally as we are performing operation to download data from internet, we will request for `android.permission.INTERNET` permission.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cmanifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.javatechig.intentserviceexample\"\u003e\n\n    \u003c!-- Internet permission, as we are accessing data from server --\u003e\n    \u003cuses-permission android:name=\"android.permission.INTERNET\" /\u003e\n\n    \u003capplication\n        android:allowBackup=\"true\"\n        android:icon=\"@drawable/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:theme=\"@style/AppTheme\"\u003e\n        \u003cactivity\n            android:name=\".MyActivity\"\n            android:label=\"@string/app_name\"\u003e\n            \u003cintent-filter\u003e\n                \u003caction android:name=\"android.intent.action.MAIN\" /\u003e\n\n                \u003ccategory android:name=\"android.intent.category.LAUNCHER\" /\u003e\n            \u003c/intent-filter\u003e\n        \u003c/activity\u003e\n\n        \u003c!-- Declaring Service in Manifest --\u003e\n        \u003cservice\n            android:name=\".DownloadService\"\n            android:exported=\"false\" /\u003e\n\n    \u003c/application\u003e\n\n\u003c/manifest\u003e\n```\n\n# 6. Sending Work Requests to the IntentService\n\nTo start the DownloadService to download data, you must create an explicit Intent and add all the request parameters to it. A service can be started by calling `startService()` method. You can start an IntentService either form an `Activity` or a `Fragment`.\n\nWhat is the additional `DownloadResultReceiver` here, huh?. Remember that we have to pass the result of download request from service to activity. This will be done through `ResultReceiver`.\n\n```java\n/* Starting Download Service */\nmReceiver = new DownloadResultReceiver(new Handler());\nmReceiver.setReceiver(this);\nIntent intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class);\n\n/* Send optional extras to Download IntentService */\nintent.putExtra(\"url\", url);\nintent.putExtra(\"receiver\", mReceiver);\nintent.putExtra(\"requestId\", 101);\n\nstartService(intent);\n```\n\n# 7. Report Status From IntentService to Activity\n\nTo send the status of a work request in an IntentService to other components, get the instance of ResultReceiver. Send the status by calling send() method.\n\n```java\nfinal ResultReceiver receiver = intent.getParcelableExtra(\"receiver\");\nBundle bundle = new Bundle();\n\n/* Service Started */\nreceiver.send(STATUS_RUNNING, Bundle.EMPTY);\n\n/* Status Finished */\nbundle.putStringArray(\"result\", results);\nreceiver.send(STATUS_FINISHED, bundle);\n\n/* Sending error message back to activity */\nbundle.putString(Intent.EXTRA_TEXT, \"Error message here..\");\nreceiver.send(STATUS_ERROR, bundle);\n```\n\n# 8. Receive Status Broadcasts from an IntentService\n\nTo re
1ceive results back from IntentService, we can use subclass of `ResultReciever`. Once results are sent from Service the `onReceiveResult()` method will be called. Your activity handles this response and fetches the results from the Bundle. Once results are recieved, accordingly the activity instance updates the UI.\n\n#### DownloadResultReceiver.java\n\n```java\npackage com.javatechig.intentserviceexample;\n\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.ResultReceiver;\n\npublic class DownloadResultReceiver extends ResultReceiver {\n    private Receiver mReceiver;\n\n    public DownloadResultReceiver(Handler handler) {\n        super(handler);\n    }\n\n    public void setReceiver(Receiver receiver) {\n        mReceiver = receiver;\n    }\n\n    public interface Receiver {\n        public void onReceiveResult(int resultCode, Bundle resultData);\n    }\n\n    @Override\n    protected void onReceiveResult(int resultCode, Bundle resultData) {\n        if (mReceiver != null) {\n            mReceiver.onReceiveResult(resultCode, resultData);\n        }\n    }\n}\n```\n\n#### MainActivity.java\n\n```java\n@Override\n    public void onReceiveResult(int resultCode, Bundle resultData) {\n        switch (resultCode) {\n            case DownloadService.STATUS_RUNNING:\n                setProgressBarIndeterminateVisibility(true);\n                break;\n            case DownloadService.STATUS_FINISHED:\n                /* Hide progress \u0026 extract result from bundle */\n                setProgressBarIndeterminateVisibility(false);\n                String[] results = resultData.getStringArray(\"result\");\n\n                /* Update ListView with result */\n                arrayAdapter = new ArrayAdapter(MyActivity.this, android.R.layout.simple_list_item_2, results);\n                listView.setAdapter(arrayAdapter);\n                break;\n            case DownloadService.STATUS_ERROR:\n                /* Handle the error */\n                String error = resultData.getString(Intent.EXTRA_TEXT);\n                Toast.makeText(this, error, Toast.LENGTH_LONG).show();\n                break;\n        }\n    }\n```\n\n# 9. Output\n\n[![Android Networking Example](/media/articles/264/Android-Networking-Example-620x1048.png)](http://stacktips.com)\n\n# 11. Download Source Code\n\nDownload complete example source code from [**GitHub**](https://github.com/javatechig/Android-IntentService-Example)\n"])</script>
1<script>self.__next_f.push([1,"f8:T2e9a,"])</script>
1<script>self.__next_f.push([1,"\n## Introduction\n\nIn this android networking tutorial we will create a sample application that illustrates how to perform network operations in android. By going through this lesson, you will learn the following topics\n\n1.  How to create network connection? What are the different available Http clients in android\n2.  How download, parse and consume JSON data?\n3.  What are the best approaches and design practices?\n\nNetworking in android means the ability to send and receive data from remote server. This data can be either a plain text, xml, json, image or a video stream. Android primarily supports two HTTP clients for networking, one by using `Apache HttpClient` and other using `HttpURLConnection`.\n\n### Apache HttpClient vs HttpURLConnection\n\nOlder version of android was supporting only Apache HttpClient for all network operations. But since `Gingerbread (Android 2.3`) , android recommend to use HttpURLConnection. HttpURLConnection is simple and thin API’s supporting transparent compression and response caching. Response cache is used to improve speed and loading time.\n\n## Android Networking Using Apache HttpClient\n\nIn this tutorial we will create a sample application that illustrates how to perform network operations in android. To make this post simplified, we will download the data from the following url and will show the article titles on a ListView. Refer the screenshot for an overview of how application looks\n\nFeed request Url: [http://stacktips.com/api/get\\_category\\_posts/?dev=1\u0026slug=android](http://stacktips.com/api/get_category_posts/?dev=1\u0026slug=android)\n\nBelow is the format of response we are expecting from server. We will get the list of posts and each post contains details like title, content, excerpt, etc. We will take all the list of titles and will display on the ListView.\n\n[![JSON Feed Response](/media/articles/265/JSON-Feed-Response.png)](http://stacktips.com)\n\n## Application Manifest Permissions\n\nAs our application is connecting to remote server, we have to provide internet permission. Just add the below line of code in your application manifest. This should be a direct child of \u003cmanifest\u003e element.\n\n```xml\n \u003cuses-permission android:name=\"android.permission.INTERNET\"/\u003e\n```\n\n  \n\n## Downloading Data Using HttpGet\n\nDownloading data is an long running task and it is recommended that all the long running task should be performed off the UI thread. And in this example we will create a simple downloader asynchronous task that performs the feed download action.\n\n#### What is AsyncTask?\n\nAsync task enables you to implement multi threading without get hands dirty into threads. AsyncTask enables proper and easy use methods that allows performing background operations and passing the results back to the UI thread. Learn more about android AsyncTask from below links\n\n**\\* [Handler and AsyncTask in Android](http://stacktips.com/android/handler-and-asynctask-in-android)**\n\n#### AsyncHttpTask.java\n\n```java\npublic class AsyncHttpTask extends AsyncTask\u003cString, Void, Integer\u003e {\n\n        @Override\n        protected Integer doInBackground(String... params) {\n            InputStream inputStream = null;\n            Integer result = 0;\n            try {\n                /* create Apache HttpClient */\n                HttpClient httpclient = new DefaultHttpClient();\n\n                /* HttpGet Method */\n                HttpGet httpGet = new HttpGet(params[0]);\n\n                /* optional request header */\n                httpGet.setHeader(\"Content-Type\", \"application/json\");\n\n                /* optional request header */\n                httpGet.setHeader(\"Accept\", \"application/json\");\n\n                /* Make http request call */\n                HttpResponse httpResponse = httpclient.execute(httpGet);\n                int statusCode = httpResponse.getStatusLine().getStatusCode();\n\n                /* 200 represents HTTP OK */\n                if (statusCode ==  200) {\n                    /* receive response as inputStream */\n                    inputStream = httpResponse.getEntity().getContent();\n                    String response = convertInputStreamToString(inputStream);\n                    parseResult(response);\n                    result = 1; // Successful\n                } else{\n                    result = 0; //\"Failed to fetch data!\";\n                }\n            } catch (Exception e) {\n                Log.d(TAG, e.getLocalizedMessage());\n            }\n            return result; //\"Failed to fetch data!\";\n        }\\\n\n        @Override\n        protected void onPostExecute(Integer result) {\n            /* Download complete. Lets update UI */\n            if(result == 1){\n                arrayAdapter = new ArrayAdapter(MyActivity.this, android.R.layout.simple_list_item_1, blogTitles);\n                listView.setAdapter(arrayAdapter);\n            }
1else{\n                Log.e(TAG, \"Failed to fetch data!\");\n            }\n        }\n    }\n```\n\n#### Code Explanation\n\n-   `AsyncHttpTask` is used to perform http connection and download data from server.\n-   `doInBackground()` method is executed on a new thread. This method takes feed request url as input parameter.\n-   This is using apache `HttpClient` method to download the data from server\n-   Once the response is received it checks for the response status code. HTTP status 200 means, the request is successful. You may validate for other http error code types and do the required validations. Once request is successful, it fetches the content stream.\n-   Now we have to convert the stream to string and then process your parser. The stream to string conversation and the JSON parser is done in two different method. Later on this tutorial we will see them.\n-   Once the data is parsed, the `doInBackground()` method completes its tasks and then `onPostExecute()` method invokes.\n-   `onPostExecute()` method we will update the adapter value and the list content.\n\n## Converting Stream to String\n\n```java\nprivate String convertInputStreamToString(InputStream inputStream) throws IOException {\n        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));\n        String line = \"\";\n        String result = \"\";\n        while((line = bufferedReader.readLine()) != null){\n            result += line;\n        }\n\n            /* Close Stream */\n        if(null!=inputStream){\n            inputStream.close();\n        }\n        return result;\n    }\n```\n\n  \n\n## JSON Response Parsing\n\nNote: The focus of this tutorial is more on explaining network connections in android and not focused towards explaining the json parser. If you are looking for some help on JSON parsing, you may read the below post\n\n**\\* [JSON Feed Reader in Android](http://stacktips.com/android/json-feed-reader-in-android \"JSON Feed Reader in Android\")**\n\n```java\nprivate void parseResult(String result) {\n        try{\n            JSONObject response = new JSONObject(result);\n            JSONArray posts = response.optJSONArray(\"posts\");\n            blogTitles = new String[posts.length()];\n\n            for(int i=0; i\u003c posts.length();i++ ){\n                JSONObject post = posts.optJSONObject(i);\n                String title = post.optString(\"title\");\n                blogTitles[i] = title;\n            }\n        }catch (JSONException e){\n            e.printStackTrace();\n        }\n    }\n```\n\n  \n\n## Using AsyncHttpTask From Activity\n\nAs discussed earlier, our ui contains a simple ListView and uses basic `ArrayAdapter`. You may customise your ListView of the kind you want. Need guide on building custom list? Checkout our below tutorial.\n\n\\* [Android ListView Tutorial](http://stacktips.com/android/android-listview-tutorial \"Android ListView Tutorial\")  \n\\* [ListView with Section Header in Android](http://stacktips.com/android/listview-with-section-header-in-android \"ListView with Section Header in Android\")\n\n#### Activity layout (activity\\_my.xml)\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n    android:paddingRight=\"@dimen/activity_horizontal_margin\"\n    android:paddingTop=\"@dimen/activity_vertical_margin\"\n    android:paddingBottom=\"@dimen/activity_vertical_margin\"\n    tools:context=\".MyActivity\"\u003e\n\n    \u003cListView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:id=\"@+id/listView\"\n        android:layout_alignParentLeft=\"true\"\n        android:layout_alignParentStart=\"true\"\n        android:choiceMode=\"singleChoice\" /\u003e\n\u003c/RelativeLayout\u003e\n```\n\n#### Activity Java class\n\nLet us have a look into Activity onCreate() method\n\n```java\n@Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_my);\n\n        listView = (ListView) findViewById(R.id.listView);
1\n        final String url = \"http://stacktips.com/api/get_category_posts/?dev=1\u0026slug=android\";\n        new AsyncHttpTask().execute(url);\n    }\n```\n\n  \n\n## Android Networking Using HttpURLConnection\n\nIn the above example, we have used Apache `HttpClient` to connect to server and download data. Now let us use `HttpURLConnection` in the same example. The only place we need to change is inside `doInBackgrond()` method of AsyncHttpTask class.\n\n```java\n @Override\n        protected Integer doInBackground(String... params) {\n            InputStream inputStream = null;\n            HttpURLConnection urlConnection = null;\n            Integer result = 0;\n            try {\n                /* forming th java.net.URL object */\n                URL url = new URL(params[0]);\n                urlConnection = (HttpURLConnection) url.openConnection();\n\n                 /* optional request header */\n                urlConnection.setRequestProperty(\"Content-Type\", \"application/json\");\n\n                /* optional request header */\n                urlConnection.setRequestProperty(\"Accept\", \"application/json\");\n\n                /* for Get request */\n                urlConnection.setRequestMethod(\"GET\");\n                int statusCode = urlConnection.getResponseCode();\n\n                /* 200 represents HTTP OK */\n                if (statusCode ==  200) {\n                    inputStream = new BufferedInputStream(urlConnection.getInputStream());\n                    String response = convertInputStreamToString(inputStream);\n                    parseResult(response);\n                    result = 1; // Successful\n                }
1else{\n                    result = 0; //\"Failed to fetch data!\";\n                }\n            } catch (Exception e) {\n                Log.d(TAG, e.getLocalizedMessage());\n            }\n            return result; //\"Failed to fetch data!\";\n        }\n```\n\n  \n\n## Android Networking Best Practices\n\n-   Do not ever download data in main thread. That will cause Application Not Responding (ANR)\n-   Use `HttpURLConnection` instead of apache `HttpClient` if your application is targeted from Android 2.3 onwards\n-   If you have a very long running task like uploading a video, use IntentService\n-   Let user know what is going on. This means there should be some visual representation of download progress. In this example we have not used any (which will show an empty screen while data is being downloaded). Without a progress representation, your application will mislead user.\n\nDownload the Android Networking Example using Apache HttpClient from from [**GitHub**](https://github.com/javatechig/Android-HttpGet-Apache-HttpClient).\n\nDownload the Android Networking Example using HttpURLConnection from [**GitHub**](https://github.com/javatechig/Android-HttpGet-HttpURLConnection).\n\n# 12. Screenshot\n\n[![Android Networking Example](/media/articles/265/Android-Networking-Example-620x1048.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"f9:Tc55,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we’ll see how to count line, word and characters in file.\n\n```java\npackage com.javatechig;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.LineNumberReader;\n\npublic class FileCountExample {\n\n    public static void main(String[] args) {\n        File file = new File(\"file1.txt\");\n\n        if (file.exists()) {\n            System.out.println(\"Total Lines=\" + getLineCount(file));\n            System.out.println(\"Total Words=\" + getWordCount(file));\n            System.out.println(\"Total Characters=\" + getCharacterCount(file));\n        } else {\n            System.out.println(\"File does not exists!\");\n        }\n    }\n\n    /**\n     * Use a BufferedReader to read the file line-by-line using readLine(). Then\n     * split each line on whitespace using String.split(\"\\s\") and the size of\n     * the resulting array is the total words count.\n     */\n    private static int getWordCount(File file) {\n        int count = 0;\n        try {\n            FileReader fr = new FileReader(file);\n            BufferedReader br = new BufferedReader(fr);\n\n            String line = br.readLine();\n            while (line != null) {\n                String[] parts = line.split(\" \");\n                for (String w : parts) {\n                    count++;\n                }\n                line = br.readLine();\n            }\n\n        } catch (FileNotFoundException e) {\n            e.printStackTrace();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        return count;\n\n    }\n\n    private static int getCharacterCount(File file) {\n        FileReader fr = null;\n        int charCount = 0;\n\n        try {\n                    fr = new FileReader(file);\n            while (fr.read() \u003e -1) {\n               charCount++;\n               }\n\n        } catch (FileNotFoundException e1) {\n            e1.printStackTrace();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        finally {\n                   if (null != fr)\n                    try {\n                           fr.close();\n            } catch (IOException e) {\n                 e.printStackTrace();\n             }\n        }\n        return charCount;\n    }\n\n    private static int getLineCount(File file) {\n        int linenumber = 0;\n        FileReader fr = null;\n        try {\n            fr = new FileReader(file);\n\n            /**\n             * buffered character-input stream that keeps track of line numbers\n             */\n            LineNumberReader lnr = new LineNumberReader(fr);\n            while (lnr.readLine() != null) {\n                linenumber++;\n            }\n            lnr.close();\n\n            return linenumber;\n        } catch (FileNotFoundException e) {\n            e.printStackTrace();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        finally {\n            if (null != fr)\n               try {\n                r.close();\n               } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n        return linenumber;\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"fa:T612,"])</script>
1<script>self.__next_f.push([1,"\nThis post provides sample program explaining how to delete and rename a file in java\n\n### Rename file in Java\n\n```java\npackage com.javatechig;\n\nimport java.io.File;\nimport java.io.IOException;\n\npublic class RenameFile {\n\n    public static void main(String[] args) {\n\n        /* File (or directory) with old name */\n        File file = new File(\"/Users/Neel/Documents/Workspace/file.txt\");\n\n        /* File (or directory) with new name */\n        File file2 = new File(\"/Users/Neel/Documents/Workspace/new-file.txt\");\n\n        if (file2.exists()) {\n            try {\n                throw new java.io.IOException(\"File already exists!\");\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n\n        /* Rename file */\n        boolean success = file.renameTo(file2);\n        if (!success) {\n            System.out.println(\"Couldn't rename file!\");\n        } else {\n            System.out.println(\"File renamed successfully!\");\n        }\n    }\n\n}\n```\n\n### Delete file in Java\n\n```java\npackage com.javatechig;\n\nimport java.io.File;\n\npublic class DeleteFile {\n\n    public static void main(String[] args) {\n        try {\n            File file = new File(\n                    \"/Users/Neel/Documents/Workspace/file1.txt\");\n\n            if (file.delete()) {\n                System.out.println(file.getName() + \" is deleted!\");\n            } else {\n                System.out.println(\"Delete operation is failed.\");\n            }\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"fb:T88f,"])</script>
1<script>self.__next_f.push([1,"\nThis example explains how to Copy file from one folder to another in java.\n\n```java\npackage com.javatechig;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.channels.FileChannel;\n\npublic class CopyFile {\n\n    public static void main(String[] args) {\n        File sourceFile = new File(\n                \"/Users/Neel/Documents/Workspace/file1.txt\");\n\n        File destFile = new File(\n                \"/Users/Neel/Documents/Workspace/file2.txt\");\n\n        /* verify whether file exist in source location */\n        if (!sourceFile.exists()) {\n            System.out.println(\"Source File Not Found!\");\n        }\n\n        /* if file not exist then create one */\n        if (!destFile.exists()) {\n            try {\n                destFile.createNewFile();\n\n                System.out.println(\"Destination file doesn't exist. Creating one!\");\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n\n        FileChannel source = null;\n        FileChannel destination = null;\n\n        try {\n\n            /**\n             * getChannel() returns unique FileChannel object associated a file\n             * output stream.\n             */\n            source = new FileInputStream(sourceFile).getChannel();\n\n            destination = new FileOutputStream(destFile).getChannel();\n\n            if (destination != null \u0026\u0026 source != null) {\n                destination.transferFrom(source, 0, source.size());\n            }\n\n        } catch (FileNotFoundException e) {\n            e.printStackTrace();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        finally {\n            if (source != null) {\n                try {\n                    source.close();\n                } catch (IOException e) {\n                    e.printStackTrace();\n                }\n            }\n            if (destination != null) {\n                try {\n                    destination.close();\n                } catch (IOException e) {\n                    e.printStackTrace();\n                }\n            }\n        }\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"fc:T74b,"])</script>
1<script>self.__next_f.push([1,"\nIn this example, we will see a sample program to copying the contents of one text file to another in Java.\n\n```java\npackage com.javatechig;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\n\npublic class CopyFileContent {\n\n    public static void main(String[] args) {\n\n        /* Source file, from which content will be copied */\n        File sourceFile = new File(\"file1.txt\");\n\n        /* destination file, where the content to be pasted */\n        File destFile = new File(\"file2.txt\");\n\n        /* if file not exist then create one */\n        if (!destFile.exists()) {\n            try {\n                destFile.createNewFile();\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n\n        InputStream input = null;\n        OutputStream output = null;\n\n        try {\n\n            /* FileInputStream to read streams */\n            input = new FileInputStream(sourceFile);\n\n            /* FileOutputStream to write streams */\n            output = new FileOutputStream(destFile);\n\n            byte[] buf = new byte[1024];\n            int bytesRead;\n\n            while ((bytesRead = input.read(buf)) \u003e 0) {\n                output.write(buf, 0, bytesRead);\n            }\n\n        } catch (FileNotFoundException e) {\n            e.printStackTrace();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        finally {\n            try {\n\n                if (null != input) {\n                    input.close();\n                }\n\n                if (null != output) {\n                    output.close();\n                }\n\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"fd:T2d52,"])</script>
1<script>self.__next_f.push([1,"\nTesting apps and getting feedback from users has never been an easy task in mobile development. Managing alpha and beta tests with internal and external testers alike, is a special kind of madness. So, what service will make testing Android apps easier? I’ve compiled a few below, and give you some highlights on my pick [TestFairy](http://testfairy.com/).\n\n## 1. Beta testing and its importance\n\nIf we cast our memories back a few years, mobile apps often meant market presence for companies, but today they’re serious money-making businesses. If you plan to make money in the fiercely-competitive world of mobile apps, then you have to seriously consider every aspect of your application: from design and usability to performance and stability.\n\nBeta testing helps you take those aforementioned considerations into account, and address them before you’re finished app is pushed into the wild.\n\n## 2. Choosing right beta platform\n\nAs there are numerous tools available, each that claim to be more useful than the other, it’s important to consider the following criteria.\n\n-   Enterprise app store: Ability to create your own private app store and restrict access to external users\n-   User and test group management\n-   Ability for beta users to download app easily and provide their feedback\n-   SDK for integration with the apps in beta environment\n-   Multiple app stores, multiple groups and ability to publish multiple applications\n-   Easy app distributions: over-air and support for tester apps\n-   Device management: list and control users and devices who have access to apps\n-   Notifying users of new versions\n-   Crash reports (symbolication)\n-   Support for Continuous Integration (CI) tools like Bamboo, Jenkins, etc.\n-   And perhaps most importantly, a reasonable price\n\n## 3. Beta testing in Android\n\nTesting the application and getting feedback from you user is never been easy in mobile application development lifecycle. Each mobile platform follows certain steps to build and distribution process. Normally the build and distribution process differs from platform to platform.\n\nHere, in this section we will discuss Android specific beta testing and distribution tool. There are various platforms out there in market, that provides solution for distributing and managing the beta testing workflow. Some of the major ones are.\n\n1.  TestFlight (Suspended Support for Android)\n2.  TestFairy\n3.  AppBlade\n4.  HockeyApp\n5.  Google Play Native App Beta Testing\n\n[![Beta distribution platforms feature comparisons](/media/articles/273/Beta-distribution-platforms-feature-comparisons-620x393.png)](http://stacktips.com)\n\nDuring my initial exploration on this matter, TestFlight arose as one the best platforms for build distribution, but its dominance came to an abrupt halt when Apple acquired it and shut down its Android operations.\n\nIn my hunt to find a replacement, [App Blade](https://appblade.com/), [Google Play](https://support.google.com/googleplay/android-developer/answer/3131213?hl=en) and [Hockey App](http://hockeyapp.net/features/) emerged as solid options, but TestFairy leads the pack. In fact, it provides awesome support and documentation for abandoned TestFlight users so they can easily migrate over.\n\n## 4. How testFairy works\n\nTestFairy follows very simple steps while it comes to distributing the build. All you need to do is just upload your android build (.apk) file to your TestFairy account and invite the beta testers. Once you upload the build, TestFairy server process your apk file and inject the required code to your apk. All this process takes places in the background, and you don’t have to do anything for this.\n\nOnce your build is processed and ready for download, you can invite beta testers via their email or from TestFairy official community page. And now, you are all done. Just sit back and relax. Once users start playing around with the app, you will get to see the reports real time.\n\n[![testfairy-archiecture](/media/articles/273/testfairy-archiecture-620x409.png)](http://stacktips.com)\n\n## 5. TestFairy highlights\n\n-   Test Users And Group Management\n-   Test fairy allows you to invite users and provide role based user access. You can be either an administrator, developer or a tester.\n-   You can define multiple administrators to control different projects (Enterprise license only)\n-   You are allowed till maximum of 500 tester
1s for any free type account. However the enterprise license goes endless.\n-   The free account can host maximum of 10 applications\n-   Once a new version of the application is available, it notifies test user with email and a link to download the application. Alternatively user can download the TestFairy testers app and browse and install the available application versions.\n\n### 5.1. Advance reporting\n\n-   Know how much time spent on testing each build.\n-   Geo chart, gives you the information on the different location the application is tested from.\n-   You can also have the application deep analysis like Activities per device name, activities per session, checkpoints, etc.\n-   Coverage information, including OS coverage, resolution coverage device demographics. You can see the chart of activities, and fragments covered per devices, sessions and users that participated in testing this project. This info will help you verify that your testers went through all the app’s activities or fragments and in case they did not, you will easily understand where and what should be improved.\n-   TestFairy takes screenshots and record videos of each application test sessions. This sometimes help to reproduce the bugs which was never been easy to reproduce.\n\n### 5.2. Stats\n\nA geographical chart gives you an idea of where your app is being tested from, while coverage information includes details on operating systems and device resolutions. What’s more, you can see a chart of activities and fragments covered per device, as well as sessions and users that participated in testing.\n\n[![TestFairy Geo Chat](/media/articles/273/testfairy-geo-chart-620x336.png)](http://stacktips.com)\n\n[![TestFairy Advance Reports](/media/articles/273/resoluations-device-and-android-os-charts-620x180.png)](http://stacktips.com)\n\n[Checkout this video](https://www.youtube.com/watch?v=g0nQ3oMhdjw) for more report examples.\n\nCheckpoints help you to monitor when a tester has reached key points in your app, such as making an in-app purchase. To monitor checkpoints, you don’t even need to integrate with their API, you just use a simple code snippet to register a checkpoint.\n\nFor example, a purchase could be tracked like so:\n\n```java\n//Purchase started\nLog.v(\"testfairy-checkpoint\", \"Purchase Initiated\");\n// your code to make the purchase\n..\nLog.v(\"testfairy-checkpoint\", \"Purchase Successful!\");\n```\n\n### 5.3. Performance reporting\n\nHere’s the kicker: TestFairy monitors each and every possible aspect of an application and generates reports. It monitors sessions, battery life, CPU usage, allocated runtime memory, threads and more. All this, again, with no additional configuration or integration of their SDK.\n\n### 5.4. Visual comparison\n\nIn addition to videos of user sessions, TestFairy takes screenshots of each activity and fragments on the different devices applications are tested on. You can filter the screen grabs by activity or fragment, and can spot the differences across devices.\n\n### 5.5. Heatmap analysis\n\nHeatmap analysis provides the information on how user is using your application. As you can see in the image below, heatmap report will give the brief idea of the buttons, or widgets clicked by user and what’s trendy on a particular screen. This report is a visual screen shot of the application screen (a sample below). This sometimes helps in taking serious business decisions. Like if you are performing testing with some of your external consultants, you can capture the areas it is covered and which are not.\n\n[![Heatmap Analysis Report](/media/articles/273/heatmap-analysis.png)](http://stacktips.com)\n\nHeat map Analysis Report\n\n### 5.6. Crash reporting\n\nCrash reporting is yet another important feature, that every developers need it. It helps in identifying the defect root and the place of its occurrence. This helps for the quick root cause analysis and fix the issue before making the product live. TestFairy records the video and takes screenshot sequences for each crash log.\n\nAgain, TestFairy stands out as you don’t have to do any coding or no integration to their SDK is required. Everything happens in the background while you upload your build. This feature may not be as advanced as “Crashlytics”, but it fulfills the basic needs for identifying the crash root cause.\n\n[![Testfairy Crash Reports](/media/articles/273/testfairy-crash-reports-620x175.png)](http://stacktips.com)\n\n### 5.7. Beta tester feedback\n\nAlong with your video feedback and crash reports, an enterprise account allows for c
1ollecting feedback from individual testers, who simply shake the device to send a message.\n\n## 6. Enterprise license\n\nTestFairy provides fairly many options to the free users. Free account is limited to number of applications, testers and group. There is no official record for the application limit on their website, but it is restricted to 10 apps (Information taken from personal interview with TestFairy CEO “Yair Bar-On”). Below are some of the enterprise license feature highlights\n\n1.  Enterprise account support unlimited apps, users and distribution list\n2.  White labeling for your enterprise account. You can have you own label and customization.\n3.  Advance reporting like heatmap analysis, CPU and memory usages\n4.  Taking beta testers feedback\n5.  Crash reporting with series of screenshots and video recording\n\n## 7. CI integration\n\nTestFairy is very simple when it comes to integrate with CI (Continuous integration) tools like Bamboo or Jenkins. CI tools can use the below script to upload the scripts\n\n```bash\ncurl    --sslv3 https://app.testfairy.com/api/upload\n-F api_key='YOUR API KEY HERE'\n-F apk_file=@trunk/bin/YourApplication.apk\n-F metrics='cpu,network,logcat'\n-F testers_groups='YOUR_DISTRIBUTION_LIST'\n-F comment='What’s new in this build?'\n```\n\n## 8. TestFairy command line uploader\n\nOnce a build is uploaded, TestFairy process the build and it do some dynamic code injection. It again sign the application with keystore before the build is ready to download. And hence, if your application using features that are dependent on your production keystore key then, those features will fail to work in TestFairy generated build. Such features includes Google Map, In-App Purchases, Google Cloud Messaging (GCM) etc. To avoid such issues, with the [command line uploader script](https://github.com/testfairy/command-line-uploader), you can send TestFairy builds signed with your production keystore key, which makes sure that features dependent on Google Maps, Google Cloud Messaging and the like work.\n\n## 9. Additional resources\n\n1.  [Gradle / Android Studio Plugin](https://github.com/testfairy/testfairy-gradle-plugin)\n2.  [Command line uploader](https://github.com/testfairy/command-line-uploader)\n3.  [TestFairy API Documentation](http://docs.testfairy.com/)\n\n## 10. Which works for you?\n\nClearly, TestFairy has treated me well, but what works for you? If I neglected to list an alternative — or one I did mention does the trick for you — let me know in the comments! If you’d like to give TestFairy a try, take advantage of their free account, which allows for 10 applications and a maximum of 500 testers.\n"])</script>
1<script>self.__next_f.push([1,"fe:T1d36,"])</script>
1<script>self.__next_f.push([1,"\n# 1. Introduction to Service\n\nAndroid user interface is restricted to perform long running jobs to make user experience smoother. A typical long running tasks can be periodic downloading of data from internet, saving multiple records into database, perform file I/O, fetching your phone contacts list, etc. For such long running tasks, Service is the alternative.\n\n1.  A service is a application component used to perform long running tasks in background.\n2.  A service doesn’t have any user interface and neither can directly communicate to an activity.\n3.  A service can run in the background indefinitely, even if component that started the service is destroyed.\n4.  Usually a service always performs a single operation and stops itself once intended task is complete.\n5.  A service runs in the main thread of the application instance. It doesn’t create its own thread. If your service is going to do any long running blocking operation, it might cause Application Not Responding (ANR). And hence, you should create a new thread within the service.\n\n# 2. Bound and Unbound Service\n\n#### Bound Service\n\nService which call indefinitely in between activity. An Android component may bind itself to a Service using bindservice (). A bound service would run as long as the other application components are bound to it. As soon as they unbind, the service destroys itself.\n\n#### Unbound Service\n\nService which call at the life span of calling activity. In this case, an application component starts the service, and it would continue to run in the background, even if the original component that initiated it is destroyed. For instance, when started, a service would continue to play music in the background indefinitely.\n\n# 3. Android Service Lifecycle\n\nA service can be run by the system, If someone calls Context.startService() or bindService() method.\n\n#### onStartCommand()\n\nThis method is called when the service be started, by calling `startService()`. Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling `stopSelf()` or `stopService()`. If you are defining your service as, bounded service then you don’t need to implement this method.\n\n#### onBind()\n\nYou need to override this method, only if you are defining your service as bounded service. This method is called, when another component wants to bind with the service by calling `bindService()`. In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don’t want to allow binding, then you should return null.\n\n#### onCreate()\n\nThis method is called while the service is first created. Here all the service initialization is done. This method is never called again.\n\n#### onDestroy()\n\nThe system calls this method when the service is no longer used and is being destroyed. This method is used to, clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.\n\n# 4. Creating a Android Service\n\nCreate a new class and extend it from `android.app.Service`. You need to override `onStartCommand()`, `onBind()`, `onCreate()` and `onDestroy()` method to handle the service lifecycle.\n\n```java\npackage com.javatechig.serviceexample;\n\nimport android.app.Service;\nimport android.content.Intent;\nimport android.os.IBinder;\nimport android.util.Log;\n\npublic class HelloService extends Service {\n\n    private static final String TAG = \"HelloService\";\n\n    private boolean isRunning  = false;\n\n    @Override\n    public void onCreate() {\n        Log.i(TAG, \"Service onCreate\");\n\n        isRunning = true;\n    }\n\n    @Override\n    public int onStartCommand(Intent intent, int flags, int startId) {\n\n        Log.i(TAG, \"Service onStartCommand\");\n\n        //Creating new thread for my service\n        //Always write your long running tasks in a separate thread, to avoid ANR\n        new Thread(new Runnable() {\n            @Override\n            public void run() {\n\n                //Your logic that service will perform will be placed here\n                //In this example we are just looping and waits for 1000 milliseconds in each loop.\n                for (int i = 0; i \u003c 5;
1 i++) {\n                    try {\n                        Thread.sleep(1000);\n                    } catch (Exception e) {\n                    }\n\n                    if(isRunning){\n                        Log.i(TAG, \"Service running\");\n                    }\n                }\n\n                //Stop service once it finishes its task\n                stopSelf();\n            }\n        }).start();\n\n        return Service.START_STICKY;\n    }\n\n    @Override\n    public IBinder onBind(Intent arg0) {\n        Log.i(TAG, \"Service onBind\");\n        return null;\n    }\n\n    @Override\n    public void onDestroy() {\n\n        isRunning = false;\n\n        Log.i(TAG, \"Service onDestroy\");\n    }\n}\n```\n\n# 5. Service Manifest Declaration\n\nIn theory, A service can be called from other application unless it is restricted. You can ensure that your service is available to only your app by including the `android:exported` attribute and setting it to “false”. This effectively stops other apps from starting your service, even when using an explicit intent.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cmanifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.javatechig.serviceexample\" \u003e\n\n    \u003capplication\n        android:allowBackup=\"true\"\n        android:icon=\"@drawable/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:theme=\"@style/AppTheme\" \u003e\n        \u003cactivity\n            android:name=\".HelloActivity\"\n            android:label=\"@string/app_name\" \u003e\n            \u003cintent-filter\u003e\n                \u003caction android:name=\"android.intent.action.MAIN\" /\u003e\n\n                \u003ccategory android:name=\"android.intent.category.LAUNCHER\" /\u003e\n            \u003c/intent-filter\u003e\n        \u003c/activity\u003e\n\n        \u003c!--Service declared in manifest --\u003e\n        \u003cservice android:name=\".HelloService\"\n            android:exported=\"false\"/\u003e\n    \u003c/application\u003e\n\n\u003c/manifest\u003e\n```\n\n# 6. Starting Android Service\n\nYou can start a service from an activity or other application component by passing an Intent to `startService()`. The Android system calls the service’s `onStartCommand()` method and passes it the Intent.\n\nIn our example, we will start service by calling `startService()` method while start service button is clicked.\n\n```java\nIntent intent = new Intent(this, HelloService.class);\nstartService(intent);\n```\n\n# 7. Stop Running Android Service\n\n-   A service must be stopped itself by calling `stopSelf()` method, once it is finishes execution. However, you can also stop a service yourself by calling `stopService()` method.\n-   A call to stopService method will call `onDestroy()` callback in your service. You have to manually stop your operation being performed by your application. To do this in the above example, we have taken a boolean variable to control the execution of service.\n\n# 8. Output\n\n[![Android Service Example](/media/articles/274/Android-Service-Example-300x533.png)](http://stacktips.com)\n\nAndroid Service Example\n\n# 9. Download Source Code\n\n[Download Android Service Example](https://github.com/javatechig/Android-Service-Example \"Download Android Service Example\")\n"])</script>
1<script>self.__next_f.push([1,"ff:Tc10,"])</script>
1<script>self.__next_f.push([1,"\nIn this example, we will learn how to create Android notification using NotificationCompat class available in the Android Support library. This class supports big style notification with backward compatibility. Big style notification was introduced on Android version 4.1.x. If you are building app that supports older android phones like android 2.3 or above, in such cases you may like to go for NotificationCompat.Builder for showing notifications.\n\nIf you are using this library, then your newer version of android phone will show big styled notification, while older android phones will show old style notification.\n\n# Example using NotificationCompat\n\n```java\npackage com.javatechig.notification;\n\nimport android.app.Activity;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.content.Intent;\nimport android.graphics.BitmapFactory;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v4.app.NotificationCompat;\nimport android.view.View;\n\npublic class MainActivity extends Activity {\n\n    // A integer, that identifies each notification uniquely\n    public static final int NOTIFICATION_ID = 1;\n\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n\n        // Your application layout file\n        setContentView(R.layout.sample_layout);\n    }\n\n    /**\n     * Send simple notification using the NotificationCompat API.\n     */\n    public void sendNotification(View view) {\n\n        // Use NotificationCompat.Builder to set up our notification.\n        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);\n\n        //icon appears in device notification bar and right hand corner of notification\n        builder.setSmallIcon(R.drawable.ic_stat_notification);\n\n        // This intent is fired when notification is clicked\n        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http://stacktips.com/\"));\n        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);\n\n        // Set the intent that will fire when the user taps the notification.\n        builder.setContentIntent(pendingIntent);\n\n        // Large icon appears on the left of the notification\n        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));\n\n        // Content title, which appears in large type at the top of the notification\n        builder.setContentTitle(\"Notifications Title\");\n\n        // Content text, which appears in smaller text below the title\n        builder.setContentText(\"Your notification content here.\");\n\n        // The subtext, which appears under the text on newer devices.\n        // This will show-up in the devices with Android 4.2 and above only\n        builder.setSubText(\"Tap to view documentation about notifications.\");\n\n        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\n\n        // Will display the notification in the notification bar\n        notificationManager.notify(NOTIFICATION_ID, builder.build());\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"100:T54a,\n[![Android Studio IDE](/media/articles/276/Android-Studio-IDE.png)](http://developer.android.com/sdk/index.html#Other)\n\nAndroid Studio brings tons of keyboard shortcuts that helps developers to keep hands more on keyboard rather than relying much on the mouse. The lesser you use mouse, results in faster development. Well, let us see some of the shortcuts for android studio for Mac user.\n\n## Android Studio Shortcuts for Mac OS X\n\n| Android Studio Command Type | Mac OS X Shortcuts |\n| --- | --- |\n| Reformat code | OPTION + CMD + L |\n| Show selected API documentation | F1 / FUNCTION + F1 |\n| Generate Source Code | CMD + N |\n| Jump to source | CMD + DOWN ARROW KEY |\n| Delete Line | CMD + BACKSPACE |\n| Search by symbol name | OPTION + CMD + O |\n| Build | CMD + F9 |\n| Build and Run | CTRL + R |\n| Toggle Project Sidebar Visibility | CMD + 1 |\n| Open Class | CMD + O |\n| Open File ( including resources) | CMD + SHIFT + O |\n| Recent Files Opened | CMD + E |\n| Recently edited files | CMD + SHIFT + E |\n| Previous Next/Previous Error | F2 / FUNCTION F2 |\n| Last Edited Location | CMD + SHIFT + BACKSPACE |\n| Last Location | CMD + [ and CMD + ] |\n| Go to Declaration | CMD + B |\n| Go to Super | CMD + Y |\n| Next Word Navigation | ALT + LEFT/RIGHT ARROW KEY |\n| Find | CMD + F |\n| Find in Path | SHIFT + CMD + F |\n| Refactor Class, Method | CTRL + T |\n101:T1386,"])</script>
1<script>self.__next_f.push([1,"\nAndroid application development is never been easy due to its raw nature and rapid growth and changes to the platform. If we cast our memories back a few years, Eclipse was the only IDE used for Android development. Eclipse is developed and maintained by open source alliance. Due to its open source and free nature, it always failed to match its all-time competitor platform IDE like XCode.\n\nBut now Android development looks very promising with the introduction of Android Studio IDE. Android Studio is an IDE based on IntelliJ IDEA that is used for android application development. The initial developer preview was released on 15th may 2013. This tool has more options that will enable developers to speed up application development. In the later section of this tutorial, we will understand the Android Studio project structure in the context of traditional eclipse based project structure.\n\nCheck out the following related articles,\n\n-   [Android Studio Features](http://stacktips.com/android/android-studio-features)\n-   [Installing Android Studio](http://stacktips.com/android/installing-android-studio)\n\n## Gradle Based Build System\n\n-   Android Studio is an IDE based on IntelliJ IDEA that uses Gradle build system. In eclipse, you can create only one build at a time. Which means, first create debug build and later you can create a release build by signing with your Keystore.\n-   Android Studio projects are set up to build both a debug and a release version of the application. The debug version is signed with the developer key store key which is created automatically (Same as eclipse debug builds). The release is not signed during the build, this needs to happen after.\n-   Android Studio, makes it easy to create several variants of an application, either for multi-apk distribution or for different flavors of an application. This means you can have different builds for debugging, release or maybe a different variant build from the same code.\n-   Eclipse ADT plugin, always generate single R.java file but, Android Studio supports multiple. The generated R.java is located in the debug folder. You can change your build variant between debug and release and accordingly it will create the R.java file in selected debug or release directory.\n\nChange the build type configuration here from the bottom left corner in your Android Studio.\n\n[![Change Build Variants in Android Studio](/media/articles/277/Change-Build-Variants-in-Android-Studio-620x410.png)](http://stacktips.com)\n\n[![Change Build Variants in Android Studio](/media/articles/277/Change-Build-Variants-in-Android-Studio2-620x411.png)](http://stacktips.com)\n\n## Android Studio Project Structure\n\n### 1. Main Project\n\nThis would be the entire project context. Whatever you do in IntelliJ IDEA, you do that in the context of a project. A project is an organizational unit that represents a complete software solution. A project in Android Studio is like a workspace in Eclipse. In Android Studio a project can contain multiple modules. A module in Android Studio is like a project in Eclipse. In the above screenshot, “LoginAuthenticator” is the name of my project\n\nThis means that, in theory, it is possible to build multiple apps within the same project. From my personal experience, creating multiple apps within the same project doesn’t work well. So, I recommend not to make your hands dirty trying the same thing. Instead, It is a better idea to create a single app per single project.\n\n![Android Studio Project Structure](/media/articles/277/Android-Studio-Project-Structure-620x388.png)\n\n### 2. .idea\n\nEclipse uses project.properties file for project-specific metadata. Here in the Android studio, this .idea does the same thing. This means the project-specific metadata is stored by Android Studio.\n\n### 3. Project Module (app)\n\nThis is the actual project folder where your application code resides. The application folder has following sub directories\n\na. **build:** This has all the complete output of the make process i.e. classes.dex, compiled classes and resources, etc.\n\nIn the Android Studio GUI, only a few folders are shown. The important part is that your R.java is found here under build/source/r/\u003cbuild variant\u003e/\u003cpackage\u003e/R.java\n\nb. **libs :** This is a commonly seen folder in eclipse land too, which optionally can hold the libraries or .jar files.\n\nc. **src:** The src folder can have both application code and android unit test script. You will find two folders named “androidTest” and “main” correspond to the “src” folder. The main folder contains two subfolders java and res. The java folder contains all the java codes and res contains drawables, layouts, etc.\n\n### 4. gradle\n\nThis is where the Gradle build system’s jar wrapper i.e. this jar is how AS communicates with Gradle installed in Windows (the OS in my case).\n\n### 5. Exter
1nal Libraries\n\nThis is not actually a folder but a place where Referenced Libraries and information on targeted platform SDK is shown.\n"])</script>
1<script>self.__next_f.push([1,"102:T10c8,"])</script>
1<script>self.__next_f.push([1,"\nJava provides reflection API to do introspection of an object and modify its behavior on the run time. The class Class in the Java API forms the basis to identify the object class and its internal structure of that particular Class. The below three functions are important to get the class behavior. In this articles we will see example invoke method using java reflection.\n\n# Example: Invoking method runtime using reflection\n\nIn mobile manufacturing company, the company wants to perform the quality check for each functionality of the product before it goes into market. The functionality of the product can be added or removed for each release.\n\nFor the above scenario consider a validator class which contains all the methods to check the quality of the product. A product class which contains describes the attributes of the product. Quality check class which is invoked by the client to check the product quality before it is checked. In this approach only validator class needs to change if any criteria will be added in future. The client code need not be changed.\n\n### Product.java\n\n```java\npublic class Product {\n\n    String productName;\n    String category;\n    String outgoingCallAbility;\n    String ChargingCapability;\n\n    public String getProductName() {\n        return productName;\n    }\n\n    public void setProductName(String productName) {\n        this.productName = productName;\n    }\n\n    public String getCategory() {\n        return category;\n    }\n\n    public void setCategory(String category) {\n        this.category = category;\n    }\n\n    public String getOutgoingCallAbility() {\n        return outgoingCallAbility;\n    }\n\n    public void setOutgoingCallAbility(String outgoingCallAbility) {\n        this.outgoingCallAbility = outgoingCallAbility;\n    }\n\n    public String getChargingCapability() {\n        return ChargingCapability;\n    }\n\n    public void setChargingCapability(String chargingCapability) {\n        ChargingCapability = chargingCapability;\n    }\n\n}\n```\n\n### ProductValidator.java\n\n```java\npublic class ProductValidator {\n\n    public boolean checkChargingCapability(Product p)\n    {\n        if(\"Y\".equalsIgnoreCase(p.getChargingCapability()))\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n\n    public boolean CheckOutgoingCallAbility(Product p)\n    {\n        if(p.getOutgoingCallAbility()!=null \u0026\u0026 p.getOutgoingCallAbility().equalsIgnoreCase(\"Y\"))\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n```\n\n### QualityCheckClient.java\n\n```java\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\n\npublic class QualityCheckClient {\n\n    /**\n     * @param args\n     * @throws ClassNotFoundException\n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     * @throws InvocationTargetException\n     * @throws IllegalArgumentException\n     */\n    public static void main(String[] args) throws ClassNotFoundException,\n            InstantiationException, IllegalAccessException,\n            IllegalArgumentException, InvocationTargetException {\n\n        String dispatch = \"proceed\";\n\n        Product p = new Product();\n        p.setOutgoingCallAbility(\"N\");\n        p.setProductName(\"Nokia\");\n        p.setChargingCapability(\"Y\");\n\n        ProductValidator validate = (ProductValidator) Class.forName(\n                \"reflection.ProductValidator\").newInstance();\n\n        Method[] methods = Class.forName(\"reflection.ProductValidator\")\n                .getDeclaredMethods();\n\n        for (Method m : methods) {\n            boolean test = (Boolean) m.invoke(validate, p);\n            if (test) {\n                System.out.println(\"Successfully Executed \" + m.getName() + \" method\");\n            } else {\n                System.out.println(\"Execution failed for\" + m.getName());\n                dispatch = \"fail\";\n                break;\n            }\n        }\n\n        if (\"fail\".equalsIgnoreCase(dispatch)) {\n            System.out.println(\"Product cant be proceed for dispatching\");\n        }\n    }\n\n}\n```\n\n### Output\n\n```text\nSuccessfully Executed the method--\u003echeckChargingCapability\nExecution failed for--\u003eCheckOutgoingCallAbility\nProduct can’t be proceed for dispatching\n```\n"])</script>
1<script>self.__next_f.push([1,"103:T1a6c,"])</script>
1<script>self.__next_f.push([1,"\nIhis tutorial, we’ll show you the importance of continuous integration tools in software development process and steps to configure Bamboo for building android code.  \n\nMost developers use Eclipse as IDE for their development. IDE makes life simplified with the ease to set up, code and build the source. All you have to do is to install and follow some of the screen instructions to run your code.\n\nEclipse will help you to build your source code and run it on device. Now let us move a step ahead. What if we need to have a continuous integration for android project? Before we begin, let us understand the importance of continuous integration in project.\n\n## Why Continuous Integration?\n\nContinuous integration or “CI” is the process of fully automating the compilation and build generation process. There are several benefits of having a Continuous Integration system integrated in your project\n\n-   Fully automated: Saves time of developers for making build for each release\n-   From Source Control: A CI takes the code from your favourite source code from repository, it could be SVN, git etc. CI server will check for any updates available on the source code, as soon as there is an update, it will trigger the build process\n-   Always Compile latest code: This is a way to make sure we are building from the latest source code from repository\n-   Distribute the latest application build to your beta testers (Optional).\n\n## Getting Started with Bamboo\n\nThe building process of Continuous integration tool is slightly different than your eclipse IDE. This uses several steps for setting up the project and lines to compile your code.\n\n1.  Download Source Code\n2.  Compile and Build Source code\n3.  Generate .APK file\n4.  Sign APK file\n5.  Distribute APK file (out of scope in this tutorial)\n\nThe above steps are important to prepare your android build and distribute to your beta testers. Distribution application to beta tester is optional in this case. I will include it in another tutorial.\n\nHere in this example, we will see how to configure bamboo for building android.\n\n### Create a New Plan\n\nLogin to Bamboo with your valid bamboo account credentials.\n\nSelect “Create” and then “Create a new plan” button in the top navigation bar. Create a new plan under an existing project or as a new project.\n\n**Plan**: Plan defines the build process. Here you define what gets built, how the build is triggered and what job gets executed. Each plan will have a default job when it is created. You can add more jobs later.\n\nOnce created, click on Atlassian Bamboo – Build Dashboard and select the project and then newly created plan from the list.\n\n[![Create New Plan in Bamboo](/media/articles/283/Create-New-Plan-in-Bamboo1-620x420.png)](http://stacktips.com)\n\n## Configuring the Plan\n\nSelect your plan. Find “Actions” drop down to the right side of your screen and then click “Configure plan” option.\n\nYou will notice a default “Job” will be created for you.\n\n### Checkout Source Code\n\nAdd task as source code checkout (by default this will get created). In this step bamboo connects you to git, github, svn or any other source code version controller system. This step will pull the source code from the specified path and will place the code in “build-dir” folder.  \n[![Create New Plan in Bamboo](/media/articles/283/Create-New-Plan-in-Bamboo1-620x420.png)](http://stacktips.com)\n\n### Update Android Project\n\nAdd Another task “Command” type and do the below configurations. Add below snippet as arguments and save the task\n\n```bash\nupdate project --target \"android-19\" --path ./Android_LoginApp --name LoginTestApp\n```\n\n[![Update Android Project](/media/articles/283/Update-Android-Project-620x465.png)](http://stacktips.com)\n\nMore more info on above command visit\n\n[http://developer.android.com/tools/projects/projects-cmdline.html](http://developer.android.com/tools/projects/projects-cmdline.html)\n\n### Build Android Code using Ant\n\nAdd another task to build the project. Select “Ant” form add task. And do the below configurations\n\n1.  Add new executable as “ant” if not available before and add the ant executable path in your computer\n2.  Add arguments as below syntax.\n\n```text\nrelease\n```\n\n[![Add ant  task](/media/articles/283/Add-ant-task-620x378.png)](http://stacktips.com)\n\nAnd now you’re done. Just hit “Run” button in your top right. This should start executing the batch and build the .apk for you.\n\n[![Task Ant Build Configuration](/media/articles/283/Task-Ant-Build-Configuration-620x481.png)](http://stacktips.com)\n\n### Sign Android Project\n\nNow 
1we have the apk ready after the above step. Once we have the .apk file, we need to sign it with jarsigner.\n\nThe jarsigner tool is used for two purposes. To sign Java ARchive (JAR) files, and to verify the signatures and integrity of signed JAR files. The JAR feature enables the packaging of class files, images, sounds, and other digital data in a single file for faster and easier distribution.\n\nA tool named jar enables developers to produce JAR files. (Technically, any zip file can also be considered a JAR file, although when created by jar or processed by jarsigner, JAR files also contain a META-INF/MANIFEST.MF file.).  \n\nAdd Another task “Command” type and do the following configurations.\n\n1.  Add new executable as “jarsigner” if not available before. “jarsigner” will be present in your java SDK. Redirect to your jarsigner sdk.\n2.  Add arguments as below syntax.\n\n```text\n-verbose -sigalg MD5withRSA -digestalg SHA1 -keystore docs/android.keystore-storepass \u003ckeystore password\u003e \u003cPath to your unsigned apk\u003e  \u003cyour_alias\u003e\n```\n\n[![Sign Android Project in Bamboo](/media/articles/283/Sign-Android-Project-in-Bamboo-620x378.png)](http://stacktips.com)\n\n### Zip Align your APK\n\nzipalign is an archive alignment tool that provides important optimization to Android application (.apk) files. The purpose is to ensure that all uncompressed data starts with a particular alignment relative to the start of the file. Specifically, it causes all uncompressed data within the .apk, such as images or raw files, to be aligned on 4-byte boundaries.\n\nThis allows all portions to be accessed directly with mmap() even if they contain binary data with alignment restrictions. The benefit is a reduction in the amount of RAM consumed when running the application.\n\nAdd Another task “Command” type and do the following configurations.\n\n```text\n -v 4 \u003cpath to your unsigned apk\u003e \u003cname of your new apk include .apk extn\u003e\n```\n\n[![Zip Align andorid APK](/media/articles/283/Zip-Align-andorid-APK-620x371.png)](http://stacktips.com)\n\nThe result of the above path is the apk that can be distributed to your beta or internal testing team.\n"])</script>
1<script>self.__next_f.push([1,"104:Tf3f,"])</script>
1<script>self.__next_f.push([1,"\nIn Java 5, we have feature called covariant return type. Prior to Java5, we could not change the return type of the overridden method. It means that if you override the method in the subclass you need to downcast it to the subclass type.\n\nThe covariant return type in java, allows narrowing down return type of the overridden method. This feature will help to avoid down casting on the client side. It allows programmer to program without the need of type checking and down casting. The covariant return type always works only for non-primitive return types.\n\nThe Clone method will return the object where we need to downcast the Object to the subclass type. After Java5, we can override the clone method to return the object of subclass type.\n\nConsider the scenario, where we have two types of manufacturer Mobile Phone and Washing Machine. Based on the customer requirement if the user wants to purchase Mobile Phone the overridden method will return the Mobile Phone object. Here the method getProductType will return the Mobile Phone object instead of Product object (Mobile Phone implements the Product interface). I.e. returns the object of subclass instead of superclass. Similarly the clone method in the Mobile Phone class will return the object of Mobile Phone instead of object of the class Object. The same rule applies to the Washing Machine class too.\n\n### Product.Java\n\n```java\npublic interface Product {\n    public void makeProduct(String productName, String ProductOwner, int IMEINo);\n}\n```\n\n### MobilePhone.Java\n\n```java\npublic class MobilePhone implements Product, Cloneable {\n\n    String _productName;\n    String _ownerName;\n    int _IMEINo;\n    MobilePhone _clonedProduct;\n\n    @Override\n    public void makeProduct(String productName, String ownerName, int IMEINo) {\n        // TODO Auto-generated method stub\n        _productName = productName;\n        _ownerName = ownerName;\n        _IMEINo = IMEINo;\n    }\n\n    protected MobilePhone clone() throws CloneNotSupportedException {\n        _clonedProduct = (MobilePhone) super.clone();\n        return _clonedProduct;\n        // return super.clone();\n    }\n}\n```\n\n### WasingMachine.java\n\n```java\npublic class WasingMachine implements Product {\n\n    String _productName;\n    String _ownerName;\n    int _modelNo;\n\n    @Override\n    public void makeProduct(String productName, String ownerName, int modelNo) {\n        // TODO Auto-generated method stub\n        _productName = productName;\n        _ownerName = ownerName;\n        _modelNo = modelNo;\n    }\n\n}\n```\n\n### Manufacture.java\n\n```java\npublic interface Manufacture {\n\n    public Product getProductType();\n\n}\n```\n\n### Apple.java\n\n```java\npublic class Apple implements Manufacture {\n\n    @Override\n    public MobilePhone getProductType() {\n        // TODO Auto-generated method stub\n        return new MobilePhone();\n    }\n\n}\n```\n\n### Samsung.java\n\n```java\npublic class Samsung implements Manufacture {\n\n    @Override\n    public WasingMachine getProductType() {\n        // TODO Auto-generated method stub\n        return new WasingMachine();\n    }\n\n}\n```\n\n### ManufactureImpl.java\n\n```java\npublic class ManufactureImpl {\n\n    /**\n     * @param args\n     * @throws CloneNotSupportedException\n     */\n    public static void main(String[] args) throws CloneNotSupportedException {\n        // TODO Auto-generated method stub\n\n        Apple s1 = new Apple();\n        MobilePhone b1 = s1.getProductType();\n        b1.makeProduct(\"Iphone5S\", \"XXXX\", 1234);\n        MobilePhone b2 = b1.clone();\n        b2._IMEINo = 6789;\n        System.out.println(\"IMEI Number Of Phone1-\u003e\" + b1._IMEINo);\n        System.out.println(\"IMEI Number Of Phone2-\u003e\" + b2._IMEINo);\n        Samsung f1=new Samsung();\n        WasingMachine c1=f1.getProductType();\n        c1.makeProduct(\"samsungWashingMachine\",\"XYZ\", 2014);\n        System.out.println(\"Owner Name Of WasingMachine-\u003e\" + c1._ownerName);\n    }\n\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"105:Tc99,"])</script>
1<script>self.__next_f.push([1,"\nThis example will show you how to run Running Infinite TimerTask in Java Servlet.\n\nFor achieving this we can initialize TimerTask inside ServletContextListener and schedule it for a certain time period. ServletContextListener is used to, make your code run before your web application started. For more understanding on ServletContextListener, refer my post on ServletContextListener Example in Servlet.\n\nFollowing example explains how to implement the ServletContextListener\n\n### 1) Create a class and implement the ServletContextListener interface\n\n```java\npackage com.javatechig;\n\nimport java.util.Date;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.servlet.ServletContextEvent;\nimport javax.servlet.ServletContextListener;\n\npublic class AppContextListener implements ServletContextListener {\n\n    @Override\n    public void contextDestroyed(ServletContextEvent arg0) {\n\n        // Your code here\n        System.out.println(\"HelloWorld Listener has been shutdown\");\n\n    }\n\n    @Override\n    public void contextInitialized(ServletContextEvent servletContextEvent) {\n\n        // Your code here\n        System.out.println(\"HelloWorld Listener initialized.\");\n\n        TimerTask vodTimer = new VodTimerTask();\n\n        Timer timer = new Timer();\n        timer.schedule(vodTimer, 1000, (2 * 1000));\n\n    }\n\n    class VodTimerTask extends TimerTask {\n\n        @Override\n        public void run() {\n            System.out.println(\"TimerTask \" + new Date().toString());\n        }\n    }\n\n}\n```\n\n### 2) Configure deployment descriptor\n\nJust add the listener tag and listener-class tag with the class path, as shown in the example.\n\n```xml\n\u003c ?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cweb -app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xmlns=\"http://java.sun.com/xml/ns/javaee\"\n    xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n    id=\"WebApp_ID\" version=\"3.0\"\u003e\n    \u003cdisplay -name\u003eHelloServlet\u003c/display\u003e\n\n    \u003cservlet\u003e\n        \u003c/servlet\u003e\u003cservlet -name\u003eHelloServlet\u003c/servlet\u003e\n        \u003cservlet -class\u003ecom.javatechig.HelloServlet\u003c/servlet\u003e\n\n    \u003cservlet -mapping\u003e\n        \u003c/servlet\u003e\u003cservlet -name\u003eHelloServlet\u003c/servlet\u003e\n        \u003curl -pattern\u003e/HelloServlet\u003c/url\u003e\n\n\n    \u003clistener\u003e\n        \u003c/listener\u003e\u003clistener -class\u003ecom.javatechig.AppContextListener\u003c/listener\u003e\n\n\u003c/web\u003e\n```\n\n### 3) Start Tomcat and deploy your application\n\nYou will see the output in the console\n\n```text\nJun 13, 2014 3:52:25 PM org.apache.catalina.core.AprLifecycleListener init\nJun 13, 2014 3:52:27 PM org.apache.catalina.core.ApplicationContext log\nINFO: No Spring WebApplicationInitializer types detected on classpath\nHelloWorld Listener initialized.\nJun 13, 2014 3:52:27 PM org.apache.coyote.AbstractProtocol start\nINFO: Starting ProtocolHandler [\"http-bio-8080\"]\nJun 13, 2014 3:52:27 PM org.apache.coyote.AbstractProtocol start\nINFO: Starting ProtocolHandler [\"ajp-bio-8009\"]\nJun 13, 2014 3:52:27 PM org.apache.catalina.startup.Catalina start\nINFO: Server startup in 1787 ms\nTimerTask Fri Jun 13 15:52:28 BST 2014\nTimerTask Fri Jun 13 15:52:30 BST 2014\nTimerTask Fri Jun 13 15:52:32 BST 2014\nTimerTask Fri Jun 13 15:52:34 BST 2014\nTimerTask Fri Jun 13 15:52:36 BST 2014\n```\n"])</script>
1<script>self.__next_f.push([1,"106:Tfbf,"])</script>
1<script>self.__next_f.push([1,"\nThis example explains how to use ServletContextListener in Servlets. `ServletContextListener` is used to, make your code run before your web application started. Below use case examples will help for more understanding\n\n-   You may need to initialise database pool before the web application started\n-   If you have a web application for your business, which runs a policy control system for monitoring, then you will have to start a worker thread soon before the application gets initialised.\n\nThere can be only one `ServletContext` for each web application. The instance of `ServletContext` will be created while deploying the application before application instance is created. A single ServletContext instance can be used by all the servlets and .jsp files in the same application. ServletContext is also called as the application scope variables in the web application scenario. `ServletContextListener` has the following two methods\n\n```java\npublic void contextInitialized(ServletContextEvent event)\npublic void contextDestroyed(ServletContextEvent event)\n```\n\nFollowing example explains how to implement the ServletContextListener\n\n### 1) Create a class and implement the ServletContextListener interface\n\n```java\npackage com.javatechig;\n\nimport javax.servlet.ServletContextEvent;\nimport javax.servlet.ServletContextListener;\n\npublic class AppContextListener implements ServletContextListener {\n\n    @Override\n    public void contextDestroyed(ServletContextEvent arg0) {\n        //Your code here\n        System.out.println(\"HelloWorld Listener has been shutdown\");\n    }\n\n    @Override\n    public void contextInitialized(ServletContextEvent servletContextEvent) {\n        //Your code here\n        System.out.println(\"HelloWorld Listener initialised.\");\n    }\n}\n```\n\n### 2) Configure deployment descriptor\n\nJust add the listener tag and listener-class tag with the class path, as shown in the example.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cweb-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xmlns=\"http://java.sun.com/xml/ns/javaee\"\n    xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n    id=\"WebApp_ID\" version=\"3.0\"\u003e\n    \u003cdisplay-name\u003eHelloServlet\u003c/display-name\u003e\n\n    \u003cservlet\u003e\n        \u003cservlet-name\u003eHelloServlet\u003c/servlet-name\u003e\n        \u003cservlet-class\u003ecom.javatechig.HelloServlet\u003c/servlet-class\u003e\n    \u003c/servlet\u003e\n    \u003cservlet-mapping\u003e\n        \u003cservlet-name\u003eHelloServlet\u003c/servlet-name\u003e\n        \u003curl-pattern\u003e/HelloServlet\u003c/url-pattern\u003e\n    \u003c/servlet-mapping\u003e\n\n    \u003clistener\u003e\n        \u003clistener-class\u003ecom.javatechig.AppContextListener\u003c/listener-class\u003e\n    \u003c/listener\u003e\n\n\u003c/web-app\u003e\n```\n\n### 3) Start Tomcat and deploy your application\n\nYou will see the output in the console\n\n```text\nJun 13, 2014 3:25:12 PM org.apache.catalina.core.AprLifecycleListener init\nJun 13, 2014 3:25:12 PM org.apache.coyote.AbstractProtocol init\nINFO: Initializing ProtocolHandler [\"http-bio-8080\"]\nJun 13, 2014 3:25:12 PM org.apache.coyote.AbstractProtocol init\nINFO: Initializing ProtocolHandler [\"ajp-bio-8009\"]\nJun 13, 2014 3:25:12 PM org.apache.catalina.startup.Catalina load\nINFO: Initialization processed in 645 ms\nJun 13, 2014 3:25:12 PM org.apache.catalina.core.StandardService startInternal\nINFO: Starting service Catalina\nJun 13, 2014 3:25:12 PM org.apache.catalina.core.StandardEngine startInternal\nINFO: Starting Servlet Engine: Apache Tomcat/7.0.54\nJun 13, 2014 3:25:13 PM org.apache.tomcat.websocket.server.WsSci onStartup\nHelloWorld Listener initialised.\nJun 13, 2014 3:25:13 PM org.apache.coyote.AbstractProtocol start\nINFO: Starting ProtocolHandler [\"http-bio-8080\"]\nJun 13, 2014 3:25:13 PM org.apache.coyote.AbstractProtocol start\nINFO: Starting ProtocolHandler [\"ajp-bio-8009\"]\nJun 13, 2014 3:25:13 PM org.apache.catalina.startup.Catalina start\nINFO: Server startup in 639 ms\nJun 13, 2014 3:25:53 PM org.apache.catalina.core.StandardContext reload\nINFO: Reloading Context with name [/HelloServlet] has started\nHelloWorld Listener has been shutdown\n```\n"])</script>
1<script>self.__next_f.push([1,"107:T91f,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we will show you how to set ANDROID\\_HOME Environmental Variable on Mac OS X.\n\n## Setting ANDROID\\_HOME environmental variable on Maverick Mac OS X Lion (10.7.5)\n\nThe ANDROID\\_HOME environment variable can be used to tell maven where to find the Android SDK. In your home directory, add a file called `.bash_profile`\n\nSet the ANDROID\\_HOME variable to your SDK directory example,\n\n```bash\nexport ANDROID_HOME=/Users/alebirke/apps/adt-bundle-mac-x86_64/sdk\n```\n\n## Setting ANDROID\\_HOME environmental variable on Maverick Mac OS X (10.9.x)\n\nConfigure the ANDROID\\_HOME environment variable based on the location of the Android SDK. Additionally, consider adding ANDROID\\_HOME/tools, and ANDROID\\_HOME/platform-tools to your PATH.\n\n```bash\n$  export ANDROID_HOME=/Users/Neel/Documents/Softwares/adt-bundle-mac-x86_64-20140321/sdk\n$  export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools\n```\n\n## Setting ANDROID\\_HOME environment variable to .bash\\_profile\n\nOpen the Terminal program present in your (this is in your Ap
1plications/Utilities folder by default). Follow the below steps.\n\n### Step-1\n\nStart up Terminal and go to your home folder.\n\n```bash\ncd ~/\n```\n\n### Step-2\n\nOpen and edit .bash\\_profile file\n\n```bash\n$ open -e .bash_profile\n```\n\nIf you don’t have .bash\\_profile file in your computer path, then create one. Enter below command to create a new file. Once created follow Step-2.\n\n```bash\ntouch .bash_profile\n```\n\n### Step-3\n\nSave the below line)\n\n```bash\nexport PATH=${PATH}:/Applications/adt-bundle-mac-x86_64-20140321/sdk/tools\nexport PATH=${PATH}:/Applications/adt-bundle-mac-x86_64-20140321/sdk/platform-tools\n```\n\n### Step-4\n\nRefresh the file using below command\n\n```bash\n$ source .bash_profile\n```\n\n### Step-5\n\nCheck if the JAVA\\_HOME is set properly\n\n```bash\n$ echo $PATH\n```\n\nYou will see the result similar to below. Find for your path in there. If available, then you are good\n\n```text\n/Users/Neel/.rvm/gems/ruby-2.1.2/bin:/Users/Neel/.rvm/gems/ruby-2.1.2@global/bin:/Users/Neel/.rvm/rubies/ruby-2.1.2/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Applications/adt-bundle-mac-x86_64-20140321/sdk/tools:/Applications/adt-bundle-mac-x86_64-20140321/sdk/platform-tools:/Users/Neel/.rvm/bin\n```\n\nAlternatively, You can run `android` command, it will start android SDK manager\n"])</script>
1<script>self.__next_f.push([1,"108:T882,"])</script>
1<script>self.__next_f.push([1,"\n# What is API Level?\n\nAPI Level is an integer value that indicates the Android framework API release versions for Android platform. Each revision made is assigned with a new incremental API Level value.\n\nThe framework API that an Android platform delivers is specified using an integer identifier called “API Level”. Each Android platform version supports exactly one API Level. The initial release of the Android platform provided API Level 1 and subsequent releases have incremented the API Level.\n\nThe API Level identifier lets the Android platform describe the minimum and maximum framework API revision that it supports\n\nThe framework API’s are used to build Android application to interact with Android system. The framework API consists of following components\n\n1.  A core set of packages and classes\n2.  A set of XML elements and attributes for declaring a manifest file\n3.  A set of XML elements and attributes for declaring and accessing resources\n4.  A set of Intents\n5.  A set of permissions that applications can request, as well as permission enforcements included in the system\n6.  Each successive version of the Android platform can include updates to the Android application framework API that it delivers.\n\nThe table below specifies the API Level supported by each version of the Android platform.\n\n| Platform Version | API Level | VERSION_CODE |\n| --- | --- | --- |\n| Android 5.0 | 21 | LOLLIPOP |\n| Android 4.4W | 20 | KITKAT_WATCH |\n| Android 4.4 | 19 | KITKAT |\n| Android 4.3 | 18 | JELLY_BEAN_MR2 |\n| Android 4.2, 4.2.2 | 17 | JELLY_BEAN_MR1 |\n| Android 4.1, 4.1.1 | 16 | JELLY_BEAN |\n| Android 4.0.3, 4.0.4 | 15 | ICE_CREAM_SANDWICH_MR1 |\n| Android 4.0, 4.0.1, 4.0.2 | 14 | ICE_CREAM_SANDWICH |\n| Android 3.2 | 13 | HONEYCOMB_MR2 |\n| Android 3.1.x | 12 | HONEYCOMB_MR1 |\n| Android 3.0.x | 11 | HONEYCOMB |\n| Android 2.3.4, 2.3.3 | 10 | GINGERBREAD_MR1 |\n| Android 2.3.2, 2.3.1, 2.3 | 9 | GINGERBREAD |\n| Android 2.2.x | 8 | FROYO |\n| Android 2.1.x | 7 | ECLAIR_MR1 |\n| Android 2.0.1 | 6 | ECLAIR_0_1 |\n| Android 2.0 | 5 | ECLAIR |\n| Android 1.6 | 4 | DONUT |\n| Android 1.5 | 3 | CUPCAKE |\n| Android 1.1 | 2 | BASE_1_1 |\n| Android 1.0 | 1 | BASE |\n"])</script>
1<script>self.__next_f.push([1,"109:T1009,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we’ll show you how to display progress notification in Android using `NotificationManager` class. For the sake of simplicity the below example shows an simple `AsyncTask` that does the background operation and update the progress bar displayed on android notification area.\n\nAs described above this example, using an simple layout with an single button. While user clicking on the button the `AsyncTask` starts and the it displays the progress notification.\n\n## Application Layout\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:id=\"@+id/container\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\" \u003e\n\n    \u003cButton\n        android:id=\"@+id/button1\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"20dp\"\n        android:text=\"Start Download\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n## Activity Class\n\n```java\nimport android.app.Activity;\nimport android.app.NotificationManager;\nimport android.content.Context;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.support.v4.app.NotificationCompat;\nimport android.support.v4.app.NotificationCompat.Builder;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\n\npublic class MainActivity extends Activity {\n    private NotificationManager mNotifyManager;\n    private Builder mBuilder;\n    int id = 1;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        Button b1 = (Button) findViewById(R.id.button1);\n        b1.setOnClickListener(new View.OnClickListener() {\n\n            public void onClick(View arg0) {\n                mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n                mBuilder = new NotificationCompat.Builder(MainActivity.this);\n                mBuilder.setContentTitle(\"Download\")\n                        .setContentText(\"Download in progress\")\n                        .setSmallIcon(R.drawable.ic_download);\n\n                new Downloader().execute();\n            }\n        });\n    }\n\n    private class Downloader extends AsyncTask\u003cVoid, Integer, Integer\u003e {\n\n        @Override\n        protected void onPreExecute() {\n            super.onPreExecute();\n\n            // Displays the progress bar for the first time.\n            mBuilder.setProgress(100, 0, false);\n            mNotifyManager.notify(id, mBuilder.build());\n        }\n\n        @Override\n        protected void onProgressUpdate(Integer... values) {\n            // Update progress\n            mBuilder.setProgress(100, values[0], false);\n            mNotifyManager.notify(id, mBuilder.build());\n            super.onProgressUpdate(values);\n        }\n\n        @Override\n        protected Integer doInBackground(Void... params) {\n            int i;\n            for (i = 0; i \u003c= 100; i += 5) {\n                // Sets the progress indicator completion percentage\n                publishProgress(Math.min(i, 100));\n                try {\n                    // Sleep for 5 seconds\n                    Thread.sleep(2 * 1000);\n                } catch (InterruptedException e) {\n                    Log.d(\"TAG\", \"sleep failure\");\n                }\n            }\n            return null;\n        }\n\n        @Override\n        protected void onPostExecute(Integer result) {\n            super.onPostExecute(result);\n            mBuilder.setContentText(\"Download complete\");\n            // Removes the progress bar\n            mBuilder.setProgress(0, 0, false);\n            mNotifyManager.notify(id, mBuilder.build());\n        }\n    }\n}\n```\n\n## Download Source Code\n\n#### Download Source Code from **[GitHub.](https://github.com/javatechig/Progress-Notification-Example-Android)**\n\n## Output\n\n[
1![Displaying Progress Notification in Android Example](/media/articles/296/Displaying-Progress-Notification-in-Android-Example.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"10a:Tb44,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we’ll show you how to support hindi, bangala, marathi fonts in Android application. Android phone doesn’t support Devanagari fonts. However if you want to use hindi, tamil, bangali or other Devanagari fonts in your Android Application you have an alternative of using external fonts. Follow below steps to achieve this\n\n1.  Download an external Devanagari font that you like to use in your application. Here in this example, I have downloaded “**[Ananda-Lipi-Bold](http://hindi-fonts.com/fonts/download/Ananda-Lipi-Bold-Cn-Bt)**” font. You can also download from **[here](http://hindi-fonts.com/fonts/download/Ananda-Lipi-Bold-Cn-Bt \"Download Ananda-Lipi-Bold font\")**\n2.  Create a new folder “fonts” under assets and copy the downloaded .ttf font to your assets/font folder.\n3.  Load .ttf to your TextView\n\n## Activity Layout\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:background=\"#900001\"\n    android:padding=\"@dimen/activity_vertical_margin\" \u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView\"\n        android:gravity=\"center_horizontal\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerInParent=\"true\"\n        android:text=\"@string/hanuman_chalisa\"\n        android:textColor=\"#ecaa00\"\n        android:textSize=\"28sp\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n## String.xml file\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cresources\u003e\n\n    \u003cstring name=\"app_name\"\u003eHindiFont\u003c/string\u003e\n    \u003cstring name=\"hanuman_chalisa\"\u003e श्रीगुरु चरण् सरोजरज, निजमनमुकुर सुधार ।\\n बरणौ रघुबर बिमल यश, जो दायक फलचार ॥\\n\\n बुद्धिहीन तनु जानिके, सुमिरौं पवन कुमार ।\\n बल बुद्धिविद्या देहु मोहिं, हरहु कलेश विकार ॥\n\u003c/string\u003e\n\n\u003c/resources\u003e\n```\n\n## Activity Java Code\n\n```java\nimport android.app.Activity;\nimport android.graphics.Typeface;\nimport android.os.Bundle;\nimport android.widget.TextView;\n\npublic class MainActivity extends Activity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        TextView tv = (TextView) findViewById(R.id.textView);\n        Typeface fontHindi = Typeface.createFromAsset(getAssets(),\n                \"fonts/Ananda Lipi Bold Cn Bt.ttf\");\n        tv.setTypeface(fontHindi);\n    }\n}\n```\n\n## Output\n\n[![Screenshot_2014-05-23-17-13-49](/media/articles/298/Screenshot_2014-05-23-17-13-49-620x348.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"10b:T719,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we explain selection sort in data structure. A selection sort is slightly more complicated. but relatively easy to understand and to code. It is one of the slow sorting technique. Given an unsorted array of integer values, a selection sort visits each element of the array, in turn. As it visits an element, it employs a second index to scan the array from the present location to the end while it identifies the least (smallest) value in that segment of the array. It then swaps that least value with the current value. Because one index scans the array once while another index scans part of the array each time, this sort algorithm is also O(n2).\n\nSimple steps for selection sort. \\[Assume we are sorted the n items in array A\\] for i = 1 to n do\n\nfor j = j+1 to n do\n\nif A\\[i\\] \u003e A\\[j\\] then swap(A\\[i\\],A\\[j\\])\n\n## Example: C program, Function to arrange number in ascending order using Selection sort technique.\n\n```c\n#include\u003cstdio.h\u003e\nvoid selection_sort(int a[],int n);\n{\n    int i,j,pos,small,temp;\n    for(i=0;i\u003cn-1;i++)\n    {\n        small=a[i]; /* Initial small number in ith pass */\n        pos=i; /* Position of smaller number */\n        /* Find the minimum of remaining elements along with the position */\n        for(j=i+1;j\u003cn;j++)\n        {\n            if(a[i]\u003csmall)\n            {\n                small=a[j];\n                pos=j;\n            }\n        }\n\n        /* Exchange ith item with least item */\n        temp=a[pos];\n        a[pos] = a[i];\n        a[i]=temp;\n    }\n}\n\nvoid main()\n{\n    int i,n,a[20];\n    printf(\"Enter the number of elements to sort\");\n    scanf(\"%d\",\u0026n);\n    printf(\"Enter %d elements to sort \",n);\n    for(i=0;i\u003cn;i++)\n    scanf(\"%d\",\u0026a[i]);\n    selection_sort(a,n)\n    printf(\"The sort elements are\");\n    for(i=0;i\u003cn;i++)\n    printf(\"%d\",\u0026a[i]);\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"10c:Tcbf,"])</script>
1<script>self.__next_f.push([1,"\nIn this example, we will see bubble sort example In data structure .\n\n1.  In bubble sort we’ll compare each element of list to the element that follows it. If the current element is greater than the element at next location, then they are in the wrong order, and we’ll swap them. In this way, the element with large value will be percolate upward. Now the last element in the array is guaranteed to be where it belongs. In the next step we do exactly the same thing. Repeating the above step will result a sorted array.\n2.  The bubble sort can be made to work in the opposite direction. moving the least value to the beginning of the array on each pass. This is sometimes referred to as a stone sort.\n3.  In this sorting algorithm, multiple Swapping take place in one pass. Smaller elements move or ‘bubble’ up to the top of the list, hence the name given to the algorithm.\n4.  In this method adjacent members of the list to be sorted are compared. If the item on top is greater than the item immediately below it, they are swapped. This process is carried on till the list is sorted.\n5.  **Note:** At least one pass is required to check whether the items are sorted. So, the best case time complexity is O(1).\n\n## Algorithm for Bubble Sort\n\n```text\nINPUT: LIST [] of N items in random order\nO UTPUT: LIST [] of N items sorted in ascending order.\n1. SWAP = TRUE\nPASS = 0/\n\n2. WHILE SWAP = TRUE DO\nBEGIN.\n\n2.1 FOR I = 0 TO (N-PASS) DO\nBEGIN\n\n2.1.1 IFA[I] \u003eA [I+1]\nBEGIN\nTMP = A[I]\nA[I] = A[I + 1]\nA[I + 1] = TMP\nSWAP = TRUE\nEND\nELSE\nSWAP = FALSE\n\n2.1.2 PASS = PASS + 1\nEND\nEND\n```\n\n## Example : C program, Function to arrange numbers in ascending order using bubble sort technique.\n\n```c\n#include\u003cstdio.h\u003e\n\nvoid bubble_sort(int a[], int n)\n{\n    int i; /* To access subsequent item while comparing*/\n    int j; /* Keep track of the passes */\n    int temp; /* Used to exchange the item */\n    int sum; /* Holds the total number of exchanges */\n    int pass; /*Holds the number of passes required */\n    int exchag; /* Holds the number of exchanges in each pass */\n    int flag; /* Indicate any exchange has been done or not */\n    sum = 0;\n    pass = 0;\n\n    for(j=1;j\u003cn;j++)\n    {\n        exchg = 0; /* number of exchanges just before the pass */\n        flage = 0; /* No exchange been done */\n        for(i=0;i\u003cn-j;i++)\n        {\n            if(a[i]\u003e=a[i+1])\n            {\n\n                /* Exchange and update the number of exchange in the current pass*/\n                temp=a[i];\n                a[i]=a[i+1];\n                a[i+1=temp;\n                exchg++;\n                sum++ /* Update the total number of exchanges */\n                flag=1; /* Exchange has been done */\n            }\n        }\n\n        pass++; /* update the number of passes */\n        printf(\"Number of exchanges in pass : %d=%dn\",j,exchg);\n        print(\"Total number of exchanges = %dn\",sum);\n    }\n\n    void main()\n    {\n        int i,n,a[20];\n        printf(\"Enter the number of items to sort\");\n        scanf(\"%d\",\u0026n);\n        print(\"Enter the items to sort\");\n        for(i=0;i\u003cn;i++)\n        scanf(\"%d\",\u0026a[i]);\n        bubble_sort(a,n);\n        printf(\"The sorted items are\");\n        for(i=0;i\u003cn;i++)\n        {\n            printf(\"%dn\",a[i]);\n        }\n    }\n```\n"])</script>
1<script>self.__next_f.push([1,"10d:Ta93,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we will see insertion sort example In data structure . An insertion sort is quite simple to understand and simple to implement.\n\n1.  An insertion sort visits each element of the array, in turn. As it visits a particular element, it scans the array from the beginning to end to determines where in that segment of the array the current value belongs.\n2.  It then inserts the current value in that location and shifts every element of the array to the right, up to the present location. It then goes on to the next location (value) in the array.\n3.  Notice that one index is going from 0 to n and for each such value and another index is scanning the array from 0 to the value of the first index. The result of this is – that this type of sort is O(n2). Insertion sort is slower.\n\n## Case Study\n\nThis is a naturally occurring sorting method exemplified by a card player arranging the cards dealt to him. He picks up the cards as they are dealt and inserts them into the required position. Thus at every step, we insert an item into its proper place in an already ordered list.\n\nExample: Sort the following list (8,6,4,1,3) using insertion sort\n\n[![Insertion Sort](/media/articles/301/Insertion-Sort.png)](http://stacktips.com)\n\n## Insertion sort algorithm\n\nThus to find the correct position search the list till an item just greater than the target is found. Shift all the items from this point one, down the list. Insert the target in the vacated slot.\n\n```text\nINPUT: LIST[ ] of N items in random order.\nOUTPUT: LIST[ ] of N items in sorted order.\n1. BEGIN\n2. FORI = 2 TO N DO\n3. BEGIN\n4. IF LIST[I] LIST[I-1]\n5. THEN BEGIN\n6. J = I.\n7. T = LIST [I] /*STORE LIST [I] */\n8. REPEAT /* MOVE OTHER ITEMS DOWN THE LIST.\n9. J = J-1\n10. LIST [J + 1] = LIST [J];\n11. IF J = 1 THEN\n12. FOUND = TRUE\n13. UNTIL (FOUND = TRUE)\n14. LIST [I] = T\n15. END\n16. END\n17. END\n```\n\n## Example: Program to sort n numbers using insertion sort.\n\n```c\n#include\u003cstdio.h\u003e\n\nvoid insertion_sort(int a[],int n)\n{\n    int i,j,item;\n    for(i=0;i\u003cn;i++)\n    {\n        /* item to be inserted */\n        item = a[i];\n        /* Try from (i-1)th position */\n        j=i-1;\n        while(j\u003e=0 \u0026\u0026 item\u003ca[j])\n        {\n            A[j+1] = a[j] /* Move the item to the next position */\n            j--; /* and update the position */\n        }\n        A[j+1]=item; /* appropriate position found and so insert item */\n    }\n}\n\nvoid main()\n{\n    int i, n,a[20];\n    printf(\"Enter the no. of elements to sort n\");\n    scanf(\"%d\", \u0026n);\n    printf(\"Enter n elements n\");\n    for(i=0;i\u003cn;i++)\n    scanf(\"%d\",\u0026a[i]);\n    insertion_sort(a,n);\n    printf(\"The sorted array is n\");\n    for(i=0;i\u003cn;i++)\n\n    printf(\"%dn\",a[i]);\n\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"10e:T17fe,"])</script>
1<script>self.__next_f.push([1,"\nRetrieval of information is made easier when it is stored in some predefined order. Sorting is, therefore, a very important computer application activity. Many sorting algorithms are available. Differing environments require differing sorting methods.\n\nSorting algorithms can be characterized in the two ways\n\n1.  Simple algorithms which require the order of n2 (written as O (n2) comparisons to sort n items.\n2.  Sophisticated algorithms that require the O(nlog2n) comparisons to sort items.\n\nThe difference lies in the fact that the first method move data only over small distances in the process of sorting, whereas the second method method large distances, so that items settle into the proper order sooner, thus resulting in fewer comparisons. Performance of a sorting algorithm can also depend on the degree of order a heady present in the data.\n\nThere are two basic categories of sorting methods:\n\n1.  Internal Sorting\n2.  External Sorting\n\nInternal sorting are applied when the entire collection of data to be sorted is small enough that the sorting can take place within main memory. The time required to read or write is not considered to be significant in evaluating the performance of internal sorting methods. External sorting methods are applied to larger collection of data which reside on secondary devices read and write access time are major concern in determine sort performances.\n\n## Overview of Sorting Methods\n\nIn my previous post on Binary search, searching data was efficient when the array was sorted. Indeed, sorting method is one of the most common operation in computing. The general sorting problem is simple enough to describe; Given an initially un-ordered array of N records, with one field distinguished as the key, rearrange the records so they are sorted into increasing (or decreasing) order according to each record’s key.\n\nSorting is the problem of taking an arbitrary permutation of n items and rearranging them into the total order.\n\n-   **Increasing or Decreasing Order?** The same algorithm can be used by both all we need do is change condition in the comparison function as we desire.\n-   **What about equal keys?** Does the order matter or not? May be we need to sort on secondary keys or leave in the same order as the original permutations.\n-   **What about non-numerical data?** Alphabetizing is sorting text strings and libraries have very complicated rules concerning punctuation etc. Is Brown-Williams before or after Brown America before or after Brown John?\n\nSorting algorithms are used in all kinds of applications and are necessary for instance, if we plan to use efficient searching algorithms like Binary Search or Interpolation Search since these require their data to be sorted.\n\nThere are dozens of algorithms, the choice of which depends on factors such as the number of items relative to working memory, knowledge of the orderliness of the items or the range of the keys, the cost of comparing keys vs. the cost of moving items, etc.\n\nTo choose an algorithm we attempt to characterize the performance of the algorithm with respect to an array of size N. We then determine which operations are critical for each type of problem. There is an memory overhead need to be taken into consideration, before opting for an efficient sorting algorithm.\n\nFollowing are several points you must think before choosing an algorithm.\n\n1.  Number of times it compares an element in the array to another value (comparisons) or\n2.  Number of times it moves an element from or to a position in the array (swaps).\n3.  Amount of extra memory used by a sort is important.\n4.  Sometimes, when sorting an extremely large data set such as Census Data, there are simply, too many records for them to all fit in memory at once. In this case, we have to resort to external sorting algorithms that don’t assume we have random access to the data. Instead, these algorithms assume the data is stored on magnetic tapes or disks and only portions of the data will fit in memory. These algorithms use “sequential access” to the data and proceed by reading in, processing, and writing out blocks of records at a time. These partially sorted blocks need to be combined or merged in some manner to eventually sort the entire list.\n5.  One final Issue to keep in mind when Implementing a sorting algorithm is the size of the records themselves. Many sorting algorithms move and interchange records in memory several times before they are moved into their final sorted position, For large records, this can add up to lots of execution time spent simply copying data. A popular solution to this problem is called “indirect sorting”. The Idea is to sort the indices of the records, rather than the records themselves.\n\n## How do you sort?\n\nThere are several different ideas using which you can write sorting algorithms.\n\n1.  [**Insertion**](http://stacktips.com/c/insertion-sort-example-in-data-structure \"Insertion Sort Example In Data Structure\") – putting an element in the appropriate place in a sorted list yields a larger sorted list.\n2.  **Exchange** – rearrange pairs of elements which are out of order, until no such pairs remain.\n3.  **[Selection](http://stacktips.com/c/selection-sort-example-data-structure \"Selection Sort Example In Data Structure\")** – extract the largest element form the list, remove it, and repeat.\n4.  **Distribution** – separate into piles based on the first letter, then sort each pile.\n5.  **Merging** -Two sorted lists can be easily combined to form a sorted list.\n\nThere are many different methods used for sorting. Quite frequently, a combination of these above methods are used to perform a sort operation. The four common sorting methods are selection, insertion, comparison, and divi
1de and conquer.\n\n1.  **Priority queue sorting methods**: Example: Selection Sort and Heap Sort\n2.  **Divided-and-conquer method:** Example: MergeSort and Quicksort\n3.  **Insertion based sort:** Example: InsertionSort\n4.  **Other methods:Example:** [BubbleSort](http://stacktips.com/c/bubble-sort-example-data-structure \"Bubble Sort Example In Data Structure\") and ShellSort\n"])</script>
1<script>self.__next_f.push([1,"10f:T95e,"])</script>
1<script>self.__next_f.push([1,"\nSequential Search is the most natural searching method. In this method, the searching begins with searching every element of the list till the required record is found. It makes no demands on the ordering of records. It takes considerably amount of time and is slower.\n\n# Sequential Search Algorithm\n\nThis represents the algorithm to search a list of values of to find the required one.\n\n```text\nINPUT: List of size N. Target value T\nOUTPUT: Position of T in the list I\nBEGIN\n\n1. Set FOUND to false\nSet I to 0\n\n2. While (I\u003c=N) and (FOUND is false)\nIf List [I] = T\nFOUND = true\nElse\nI=I+1\nEND\n\n3. If FOUND is false\nT is not present in List.\nEND\n```\n\n### Analysis of Sequential Search\n\nWhether the sequential search is carried out on lists implemented as arrays or linked lists or on files, the criterial part in performance is the comparison loop step 2. Obviously the fewer the number of comparisons, the sooner the algorithm will terminate.\n\nThe fewest possible comparisons = 1. When the required item is the first item in the list. The maximum comparisons = N when the required item is the last item in the list. Thus if the required item is in position I in the list, I comparisons are required. Hence the average number of comparisons done by sequential search is (N+1)/2\n\n[![clip-image00285](/media/articles/304/clip-image00285.jpg)](http://stacktips.com)\n\nSequential search is easy to write and efficient for short lists. It does not require sorted data. However it is disastrous for long lists. There is no way of quickly establishing that the required item is not in the list or of finding all occurrences of a required item at one place. We can overcome these deficiencies with Binary search.\n\n### Example- Program to search for an item using linear search.\n\n```c\n#include \u003c stdio.h \u003e\n\n/* Search for key in the List */\nint seq_search(int key, int a[], int n)\n{\n    Int I;\n    for (i = 0; i \u003c n; i++)\n    {\n        If(a[i] == key) return i + 1\n    }\n    return 0;\n}\n\nvoid main()\n{\n    int I, n, key, pos, a[20];\n    printf(\"Enter the value of n\");\n    scanf(\"%d\", \u0026 n);\n    printf(\"Enter n valuesn\");\n    for (i = 0; i \u003c n; i++)\n        scanf(\"%d\", \u0026 a[i]);\n\n    printf(\"Enter the item to be searched\");\n    scanf(\"%d\", \u0026 key);\n\n    pos = seq_search(key, n, a);\n    if (pos == 0)\n        printf(\"Search unscccessful n\");\n    else\n        printf(\"key found at position = %d n\", pos);\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"110:T1406,"])</script>
1<script>self.__next_f.push([1,"\n# Introduction\n\nInformation retrieval is one of the most important applications of computers. It usually involves giving a piece of information called the key, and ask to find a record that contains other associated information. This is achieved by first going through the list to find if the given key exists or not, a process called searching. Computer systems are often used to store large amounts of data from which individual records must be retrieved according to some search criterion. The process of searching for an item in a data structure can be quit straightforward or very complex.\n\nSearching can be done on internal data structures or on external data structures. Information retrieval in the required format is the central activity in all computer applications. This involves searching. This block deals with searching techniques. Searching methods are designed to take advantage of the file organisation and optimize the search for a particular record or to establish its absence. The file organisation and searching method chosen can make a substantial difference to an application’s performance.\n\n# Objectives\n\nIn this series of tutorial, you’ll be able to understand the following\n\n1.  Brief discussion on Basics Searching Techniques.\n2.  Algorithmic Notation such as The average time, The worst-case time and, The best possible time.\n\n# Basics Searching Techniques\n\nConsider a list of n elements or can represent a file of n records, where each element is a key / number. The task is to find a particular key in the list in the shortest possible time. If you know you are going to search for an item in a set, you will need to think carefully about what type of data structure you will use for that set. At low level, the only searches that get mentioned are for sorted and unsorted arrays. However, these are not the only data types that are useful for searching.\n\n## [1. Linear search](http://stacktips.com/c/sequential-search-or-linear-search-data-structure)\n\nStart at the beginning of the list and check every element of the list. Very slow \\[order O(n) \\] but works on an unsorted list. [Read Linear Search more in detailed](http://stacktips.com/c/sequential-search-or-linear-search-data-structure).\n\n## [2. Binary Search](http://stacktips.com/c/binary-search-algorithm-data-structure)\n\nThis is used for searching in a sorted array. Test the middle element of the array. If it is too big. Repeat the process in the left half of the array, and the right half if it’s too small. In this way, the amount of space that needs to be searched is halved every time, so the time is O(log n). [Read Binary Search more in detailed](http://stacktips.com/c/binary-search-algorithm-data-structure).\n\n## 3. Hash Search\n\nSearching a hash table is easy and extremely fast, just find the hash value for the item you’re looking for then go to that index and start searching the array until you find what you are looking for or you hit a blank spot. The order is pretty close to o(1), depending on how full your hash table is.\n\n## 4. Binary Tree search\n\nSearch a binary tree is just as easy as searching a hash table, but it is usually slower (especially if the tree is badly unbalanced). Just start at the root. Then go down the left subtree if the root is too big and the right subtree if is too small. Repeat until you find what you want or the sub-tree you want isn’t there. The running time is O(log n) on average and O(n) in the worst case.\n\n# Algorithmic Notation\n\nLet’s examine how long it will take to find an item matching a key in the collections. We are interested in:\n\n1.  The average time\n2.  The worst-case time and\n3.  The best possible time.\n\nHowever, we will generally be most concerned with the worst-case time as calculations based on worst-case time can lead to guaranteed performance predictions. Conveniently, the worst-case time are generally easier to calculate than average time. If there are n items in our collection whether it is stored as an array or as linked list-then it is obvious that in the worst case, when there is no item in the collection with the desired key, then n comparisons of the key with keys of the items in the collection will have to be made. To simplify analysis and comparison of algorithms, we look for a dominated operation and count the number of times that dominant operation has to be performed. In the case of searching, the dominant operation is the comparison, since the search requires n comparisons in the worst case, we say this is O(n), (pronounced as big-Oh-n or Oh-n) algorithm.\n\n**The best case-in which the first comparison returns a match-requires a single comparison and is O(1).** The average time depends on the probability that the key will be found in the collection-this is something that we would not expected to know in the majority of cases. Thus in this case, as in most others, estimation of the average time is of little utility. If the performance of the system is vital, i.e. it’s part of a life-critical system, then we must use the worst case in our design calculations as it represents the best guaranteed performance.\n"])</script>
1<script>self.__next_f.push([1,"111:Tfd3,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we’ll show you how to use Universal Image Loader library in your android project.\n\n## What is Universal Image Loader?\n\nUniversal Image Loader is an smart and powerful library that helps in loading, caching and displaying images on Android. This means, using this library you can download remote images and display on ImageView.\n\n## Universal Image Loader Features\n\n-   Asynchronous and multi-threaded image loading. This allows you to download multiple images Asynchronously.\n-   Supports various configurations that helps to tune for your requirement. With this you can control memory, cache type, decoder, display image options, etc.\n-   Possibility of image caching in memory and/or on device’s file system (or SD card)\n-   Possibility to “listen” loading process. Allows various callback methods using which you will get to know the progress/state of your download request.\n\n[![UniversalImageLoader](/media/articles/309/UniversalImageLoader-620x405.png)](http://stacktips.com)\n\n## Integrating Universal Image Loader in Android\n\nIntegrating this library is quite easy. Here we’ll show you steps to download and integrate this library in Android application.\n\n#### 1. Download Universal Image Loader\n\n**[Download Universal Image Loader JAR](https://github.com/nostra13/Android-Universal-Image-Loader/raw/master/downloads/universal-image-loader-1.9.1-with-sources.jar)** and put the JAR in the **libs** folder of your Android project. You can also fork the library on [GitHub](https://github.com/nostra13/Android-Universal-Image-Loader)\n\n#### 2. Mainfest permissions\n\nAdd below required permission in your application Manifest file.\n\n```xml\n\u003cmanifest\u003e\n    \u003cuses-permission android:name=\"android.permission.INTERNET\" /\u003e\n    \u003c!-- Include next permission if you want to allow UIL to cache images on SD card --\u003e\n    \u003cuses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" /\u003e\n    ...\n    \u003capplication android:name=\"MyApplication\"\u003e\n        ...\n    \u003c/application\u003e\n\u003c/manifest\u003e\n```\n\n#### 3. Library setup in your Ap
1plication class\n\n```java\nimport android.app.Application;\nimport com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\n\npublic class MyApplication extends Application {\n    @Override\n    public void onCreate() {\n        super.onCreate();\n\n        // UNIVERSAL IMAGE LOADER SETUP\n        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()\n                .cacheOnDisc(true).cacheInMemory(true)\n                .imageScaleType(ImageScaleType.EXACTLY)\n                .displayer(new FadeInBitmapDisplayer(300)).build();\n\n        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(\n                getApplicationContext())\n                .defaultDisplayImageOptions(defaultOptions)\n                .memoryCache(new WeakMemoryCache())\n                .discCacheSize(100 * 1024 * 1024).build();\n\n        ImageLoader.getInstance().init(config);\n        // END - UNIVERSAL IMAGE LOADER SETUP\n    }\n}\n```\n\n#### 4. Download and display bitmap on ImageView\n\n```java\n//your image url\nString url = \"http://stacktips.com/wp-content/uploads/2014/05/UniversalImageLoader-620x405.png\";\n\nImageLoader imageLoader = ImageLoader.getInstance();\nDisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)\n                .cacheOnDisc(true).resetViewBeforeLoading(true)\n                .showImageForEmptyUri(fallback)\n                .showImageOnFail(fallback)\n                .showImageOnLoading(fallback).build();\n\n//initialize image view\nImageView imageView = (ImageView) findViewById(R.id.imageView1)\n\n//download and display image from url\nimageLoader.displayImage(url, imageView, options);\n```\n"])</script>
1<script>self.__next_f.push([1,"112:T4978,"])</script>
1<script>self.__next_f.push([1,"\nOver the course of this article, we will focus on Android SQLite database Tutorial. It also demonstrates how to create new table, insert records, and modify records with example.\n\n## 1. What is SQLite\n\nSQLite is an Open-Source embedded SQL database engine. This provides relational database management structure for storing user defined records in the form of tables. SQLite is light weight when it comes to resource usage and it doesn’t need to have any server setup like other RDBMS systems. It is an cross platform and self-contained database.\n\nAndroid is shipped with SQLite version 3.4.0.\n\n## 2. Sample TODO Application\n\nIn this tutorials we will make a simple TODO application that will store, manipulate the user created records. For the sake of simplicity we have only less number of columns in this application. You may like to extend this to make it an full-fledged application. In this example we will create a database `JAVATECHIG_TODOS.DB` and a table named `TODO` for storing all todo’s that user is creating. You can find a demo link to it on [Google play.](https://play.google.com/store/apps/details?id=com.javatechig.todo)\n\n## 3. Create New Database\n\nDatabase names must be unique within an application, not across all applications. Let us have a look at the database structure from the below image. We have three columns in `TODO` table. `_id` is with INTEGER data type and a primary key with auto increment, subject is TEXT type and `description` is also TEXT type.\n\n[![database design](/media/articles/312/database-design-620x208.png)](http://stacktips.com)\n\n## 4. Create a New Android project\n\nCreate a new android project named “TODOApp”. Here in this example we use minSdkVersion as 14, targetSdkVersion as 19 and package name is `com.javatechig.todo`\n\n## 5. Database Helper Class\n\nNow let us have a look into database helper classes. Database helper `DBhelper.java` and `SQLController.java` class helps to perform all database CURD operations.\n\n**DBhelper.java**\n\n```java\npackage com.javatechig.todo;\n\nimport android.content.Context;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\npublic class DBhelper extends SQLiteOpenHelper {\n\n    // Table Name\n    public static final String TABLE_NAME = \"TODOS\";\n\n    // Table columns\n    public static final String _ID = \"_id\";\n    public static final String TODO_SUBJECT = \"subject\";\n    public static final String TODO_DESC = \"description\";\n    // Database Information\n    static final String DB_NAME = \"JAVATECHIG_TODOS.DB\";\n\n    // database version\n    static final int DB_VERSION = 1;\n\n    // Creating table query\n    private static final String CREATE_TABLE = \"create table \" + TABLE_NAME + \"(\" + _ID\n            + \" INTEGER PRIMARY KEY AUTOINCREMENT, \" + TODO_SUBJECT + \" TEXT NOT NULL, \" + TODO_DESC + \" TEXT);\";\n\n    public DBhelper(Context context) {\n        super(context, DB_NAME, null, DB_VERSION);\n    }\n\n    @Override\n    public void onCreate(SQLiteDatabase db) {\n        db.execSQL(CREATE_TABLE);\n    }\n\n    @Override\n    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n        db.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_NAME);\n        onCreate(db);\n    }\n}\n```\n\nIn the above code we have declared various constants which are used as database name, table name and column names. DBhelper class extends `SQLiteOpenHelper` class and overrides `onCreate()` and `onUpgrade()` method.\n\n### 5.1. Create Database\n\nThe `onCreate()` method will be called on first time use of the application. Here we will construct SQLite database. This method is called only if the database file is not created before. Once the database is successfully created, it creates .DB files in your `data/data/\u003cyour app package name\u003e/databases/` folder. You can view this from DDMS from your emulator, but if you use your physical device you may not be able to browse this file unless your device is routed.\n\n[![Database location](/media/articles/312/Database-location-620x350.png)](http://stacktips.com)\n\n### 5.2. Upgrade Database\n\nThe `onUpgrade()` method is called only when the database version is changed. Database version is an integer value which is specified inside the DBhelper constructor.\n\n## 6. Create Database Controller\n\nIt is always a best practice to define an controller or separate class for all your database operations. Here in this example we are creating an new class that performs all database related operations like add, update, delete records into table.\n\nBefore performing any database operations like add, update, delete records in a table, first open the database by calling `getWritableDatabase()` method. Make sure to close database connection once it is opened.\n\n### 6.1. Add New TODO Record\n\n```java\npublic void insert(String name, String desc) {\n    ContentValues contentValue = new ContentValues();\n    contentValue.put(DBhelper.TODO_SUBJECT, name);\n    contentValue.put(DBhelper.TODO_DESC, desc);\n    database.insert(DBhelper.TABLE_NAME, null, contentValue);\n}\n```\n\n### 6.2. Fetching All Records\n\n```java\npublic Cursor fetch() {\n    String[] columns = new String[] { DBhelper._ID, DBhelper.TODO_SUBJECT, DBhelper.TODO_DESC};
1\n    Cursor cursor = database.query(DBhelper.TABLE_NAME, columns, null, null, null, null, null);\n    if (cursor != null) {\n        cursor.moveToFirst();\n    }\n    return cursor;\n}\n```\n\n### 6.3. Modify Record\n\n```java\npublic int update(long _id, String name, String desc) {\n    ContentValues contentValues = new ContentValues();\n    contentValues.put(DBhelper.TODO_SUBJECT, name);\n    contentValues.put(DBhelper.TODO_DESC, desc);\n    int i = database.update(DBhelper.TABLE_NAME, contentValues, DBhelper._ID + \" = \" + _id, null);\n    return i;\n}\n```\n\n### 6.4. Delete Record\n\nRefer SQLiteController class.\n\n### 6.5. Close Database Connection\n\nRefer SQLiteController class.\n\n## 7. Controller Complete Code\n\n**SQLController.java**\n\n```java\npackage com.javatechig.todo;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.SQLException;\nimport android.database.sqlite.SQLiteDatabase;\n\npublic class SQLController {\n\n    private DBhelper dbHelper;\n    private Context ourcontext;\n    private SQLiteDatabase database;\n\n    public SQLController(Context c) {\n        ourcontext = c;\n    }\n\n    public SQLController open() throws SQLException {\n        dbHelper = new DBhelper(ourcontext);\n        database = dbHelper.getWritableDatabase();\n        return this;\n\n    }\n\n    public void close() {\n        dbHelper.close();\n    }\n\n    public void insert(String name, String desc) {\n        ContentValues contentValue = new ContentValues();\n        contentValue.put(DBhelper.TODO_SUBJECT, name);\n        contentValue.put(DBhelper.TODO_DESC, desc);\n        database.insert(DBhelper.TABLE_NAME, null, contentValue);\n    }\n\n    public Cursor fetch() {\n        String[] columns = new String[] { DBhelper._ID, DBhelper.TODO_SUBJECT,\n                DBhelper.TODO_DESC };\n        Cursor cursor = database.query(DBhelper.TABLE_NAME, columns, null,\n                null, null, null, null);\n        if (cursor != null) {\n            cursor.moveToFirst();\n        }\n        return cursor;\n    }\n\n    public int update(long _id, String name, String desc) {\n        ContentValues contentValues = new ContentValues();\n        contentValues.put(DBhelper.TODO_SUBJECT, name);\n        contentValues.put(DBhelper.TODO_DESC, desc);\n        int i = database.update(DBhelper.TABLE_NAME, contentValues,\n                DBhelper._ID + \" = \" + _id, null);\n        return i;\n    }\n\n    public void delete(long _id) {\n        database.delete(DBhelper.TABLE_NAME, DBhelper._ID + \"=\" + _id, null);\n    }\n}\n```\n\n## 8. Application Activity Layout\n\nIn this example, we have three major layout files. One for listing all TODO items, second one is for adding all records and the third one is for update/deleting records.\n\n**fragment\\_todo\\_list.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\" \u003e\n\n    \u003cListView\n        android:id=\"@+id/list_view\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:dividerHeight=\"1dp\"\n        android:padding=\"10dp\" \u003e\n    \u003c/ListView\u003e\n\n    \u003cTextView\n        android:id=\"@+id/empty\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerInParent=\"true\"\n        android:text=\"@string/empty_list_text\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n**activity\\_add\\_record.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    android:padding=\"20dp\" \u003e\n\n    \u003cEditText\n        android:id=\"@+id/subject_edittext\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:ems=\"10\"\n        android:hint=\"@string/enter_title\" \u003e\n\n        \u003crequestFocus /\u003e\n    \u003c/EditText\u003e\n\n    \u003cEditText\n        android:id=\"@+id/description_edittext\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:ems=\"10\"\n        android:hint=\"@string/enter_desc\"\n        android:inputType=\"textMultiLine\"\n        android:minLines=\"5\" \u003e\n    \u003c/EditText\u003e\n\n    \u003cButton\n        android:id=\"@+id/
1add_record\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center\"\n        android:text=\"@string/add_record\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\n**activity\\_modify\\_record.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    android:padding=\"10dp\" \u003e\n\n    \u003cEditText\n        android:id=\"@+id/subject_edittext\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginBottom=\"10dp\"\n        android:ems=\"10\"\n        android:hint=\"@string/enter_title\" /\u003e\n\n       \u003cEditText\n        android:id=\"@+id/description_edittext\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:ems=\"10\"\n        android:hint=\"@string/enter_desc\"\n        android:inputType=\"textMultiLine\"\n        android:minLines=\"5\" \u003e\n    \u003c/EditText\u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:weightSum=\"2\"\n        android:gravity=\"center_horizontal\"\n        android:orientation=\"horizontal\" \u003e\n\n        \u003cButton\n            android:id=\"@+id/btn_update\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"@string/btn_update\" /\u003e\n\n        \u003cButton\n            android:id=\"@+id/btn_delete\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"@string/btn_delete\" /\u003e\n    \u003c/LinearLayout\u003e\n\u003c/LinearLayout\u003e\n```\n\n## 9. Application Activity Classes\n\nNow let us see how are the activity classes look like. We have three activity classes that does three different works. One for listing all TODO items, second adds TODO item and other helps in update/delete records.\n\n-   ContentValues is a name value pair, used to insert or update values into database tables. ContentValus object will be passed to SQLiteDatabase object `insert()` and `update()` method.\n-   Cursor is a temporary buffer area which holds results from SQLiteDatabase query.\n\n**TodoListActivity.java**\n\n```java\npackage com.javatechig.todo;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.v4.widget.SimpleCursorAdapter;\nimport android.support.v7.app.ActionBarActivity;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.ListView;\nimport android.widget.TextView;\n\npublic class TodoListActivity extends ActionBarActivity {\n    private SQLController dbcon;\n    private ListView listView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.fragment_emp_list);\n\n        dbcon = new SQLController(this);\n        dbcon.open();\n        listView = (ListView) findViewById(R.id.list_view);\n        listView.setEmptyView(findViewById(R.id.empty));\n        // Attach The Data From DataBase Into ListView Using Crusor Adapter\n        Cursor cursor = dbcon.fetch();\n        String[] from = new String[] { DBhelper._ID, DBhelper.TODO_SUBJECT,\n                DBhelper.TODO_DESC };\n        int[] to = new int[] { R.id.id, R.id.title, R.id.desc };\n\n        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,\n                R.layout.activity_view_record, cursor, from, to);\n\n        adapter.notifyDataSetChanged();\n        listView.setAdapter(adapter);\n\n        // OnCLickListiner For List Items\n        listView.setOnItemClickListener(new OnItemClickListener() {\n            @Override\n            public void onItemClick(AdapterVie
1w\u003c?\u003e parent, View view,\n                    int position, long viewId) {\n                TextView id_tv = (TextView) view.findViewById(R.id.id);\n                TextView title_tv = (TextView) view.findViewById(R.id.title);\n                TextView desc_tv = (TextView) view.findViewById(R.id.desc);\n\n                String id = id_tv.getText().toString();\n                String title = title_tv.getText().toString();\n                String desc = desc_tv.getText().toString();\n\n                Intent modify_intent = new Intent(getApplicationContext(),\n                        ModifyTodoActivity.class);\n                modify_intent.putExtra(\"title\", title);\n                modify_intent.putExtra(\"desc\", desc);\n                modify_intent.putExtra(\"id\", id);\n                startActivity(modify_intent);\n            }\n        });\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        getMenuInflater().inflate(R.menu.main, menu);\n        return true;\n    }\n\n    @Override\n    public boolean onOptionsItemSelected(MenuItem item) {\n        int id = item.getItemId();\n        if (id == R.id.add_record) {\n            Intent add_mem = new Intent(this, AddTodoActivity.class);\n            startActivity(add_mem);\n            return true;\n        }\n        return super.onOptionsItemSelected(item);\n    }\n}\n```\n\n**AddTodoActivity.java**\n\n```java\npackage com.javatechig.todo;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.EditText;\n\npublic class AddTodoActivity extends Activity implements OnClickListener {\n    private Button addTodoBtn;\n    private SQLController dbController;\n    private EditText subjectEditText;\n    private EditText descEditText;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setTitle(\"Add Record\");\n\n        setContentView(R.layout.activity_add_record);\n        subjectEditText = (EditText) findViewById(R.id.subject_edittext);\n        descEditText = (EditText) findViewById(R.id.description_edittext);\n        addTodoBtn = (Button) findViewById(R.id.add_record);\n        dbController = new SQLController(this);\n        dbController.open();\n        addTodoBtn.setOnClickListener(this);\n    }\n\n    @Override\n    public void onClick(View v) {\n        switch (v.getId()) {\n        case R.id.add_record:\n            final String name = subjectEditText.getText().toString();\n            final String desc = descEditText.getText().toString();\n            dbController.insert(name, desc);\n\n            Intent main = new Intent(AddTodoActivity.this,\n                    TodoListActivity.class)\n                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n            startActivity(main);\n            break;\n        default:\n            break;\n        }\n    }\n}\n```\n\n**ModifyTodoActivity.java**\n\n```java\npackage com.javatechig.todo;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.EditText;\n\npublic class ModifyTodoActivity extends Activity implements OnClickListener {\n    private EditText titleText;\n    private Button updateBtn, deleteBtn;\n    private long _id;\n    private SQLController dbController;\n    private EditText descText;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setTitle(\"Modify Record\");\n        setContentView(R.layout.activity_modify_record);\n\n        dbController = new SQLController(this);\n        dbController.open();\n        titleText = (EditText) findViewById(R.id.subject_edittext);\n        descText = (EditText) findViewById(R.id.description_edittext);\n        updateBtn = (Button) findViewById(R.id.btn_update);\n        deleteBtn = (Button) findViewById(R.id.btn_delete);\n\n        Intent intent = getIntent();\n        String id = intent.getStringExtra(\"id\");\n        String name = intent.getStringExtra(\"title\");\n        String desc = intent.getStringExtra(\"desc\");\n        _id = Long.parseLong(id);\n        titleText.setText(name);\n        descText.setText(desc);\n\n        updateBtn.setOnClickListener(this);\n        deleteBtn.setOnClickListener(this);\n    }\n\n    @Override\n    public void onClick(View v) {\n        switch (v.getId()) {\n        case R.id.btn_update:\n            String title = titleText.getText().toString();\n            String desc = descText.getText().toString();\n            dbController.update(_id, title, desc);\n            this.returnHome();\n            break;\n        case R.id.btn_delete:\n            dbController.delete(_id);\n            this.returnHome();\n            break;\n        }\n    }\n\n    public void returnHome() {\n        Intent home_intent = new Intent(getApplicationContext(),\n                TodoListActivity.class)\n                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n        startActivity(home_intent);\n    }\n}\n```\n\n## 10. Download Example Code\n\n[Download source](https://github.com/javatechig/Advance-Android-Tutorials/tree/master/TODO%20Android%20App)\n"])</script>
1<script>self.__next_f.push([1,"113:T126a,"])</script>
1<script>self.__next_f.push([1,"\nThis example explains “How to create Action Bar Tabs in Xamarin.Android”.\n\nThis example uses Fragment in combination with the action bar for tab navigation. We can add a new tab to the action bar by calling newTab() method.\n\nThe following code shows an activity with two tabs “Audio” and “Video”. It uses dummy fragments as content. The Action Bar includes support for adding tabbed interfaces in Android 4.0.\n\n## Activity Layout class (Main.xml)\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:orientation=\"vertical\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\u003e\n    \u003cFrameLayout\n        android:id=\"@+id/fragmentContainer\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"0dip\"\n        android:layout_weight=\"1\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\n## Your Activity class\n\n```cs\nusing System;\n\nusing Android.App;\nusing Android.Content;\nusing Android.Runtime;\nusing Android.Views;\nusing Android.Widget;\nusing Android.OS;\n\nnamespace ActionBarTabsExample\n{\n    [Activity (Label = \"ActionBar Tabs Example\", MainLauncher = true)]\n    public class Activity1 : Activity\n    {\n        protected override void OnCreate (Bundle bundle)\n        {\n            base.OnCreate (bundle);\n\n            // Set our view from the \"main\" layout resource\n            SetContentView (Resource.Layout.Main);\n\n        //enable navigation mode to support tab layout\n            this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;\n\n        //adding audio tab\n        AddTab (\"Audio\", Resource.Drawable.Icon,  new AudioFragment());\n\n        //adding video tab\n            AddTab (\"Video\", Resource.Drawable.Icon,  new VideoFragment());\n        }\n\n        /*\n         * This method is used to create and add dynamic tab view\n         * @Param,\n         *  tabText: title to be displayed in tab\n         *  iconResourceId: image/resource id\n         *  fragment: fragment reference\n         *\n        */\n        void AddTab (string tabText, int iconResourceId, Fragment fragment)\n        {\n            var tab = this.ActionBar.NewTab ();\n            tab.SetText (tabText);\n            tab.SetIcon (iconResourceId);\n\n            // must set event handler for replacing tabs tab\n            tab.TabSelected += delegate(object sender, ActionBar.TabEventArgs e) {\n                e.FragmentTransaction.Replace(Resource.Id.fragmentContainer, fragment);\n            };\n\n            this.ActionBar.AddTab (tab);\n        }\n\n    }\n}\n```\n\n## Your fragment layout\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cTextView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:id=\"@+id/textView\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:gravity=\"center\"\n    android:textStyle=\"bold\"\n    android:textSize=\"16dp\"\n    android:background=\"#ffe3e1e1\"\n    android:textColor=\"#ff393939\" /\u003e\n```\n\n## AudioFragment class\n\n```cs\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Android.App;\nusing Android.Content;\nusing Android.OS;\nusing Android.Runtime;\nusing Android.Views;\nusing Android.Widget;\n\nnamespace ActionBarTabsExample\n{\n    class AudioFragment: Fragment\n    {\n        public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)\n        {\n            base.OnCreateView (inflater, container, savedInstanceState);\n\n            var view = inflater.Inflate (Resource.Layout.Tab, container, false);\n            var sampleTextView = view.FindViewById\u003cTextView\u003e (Resource.Id.textView);\n            sampleTextView.Text = \"This is Audio Fragment Sample\";\n            return view;\n        }\n    }\n}\n```\n\n## VideoFragment class\n\n```cs\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Android.App;\nusing Android.Content;\nusing Android.OS;\nusing Android.Runtime;\nusing Android.Util;\nusing Android.Views;\nusing Android.Widget;\n\nnamespace ActionBarTabsExample\n{\n    class VideoFragment: Fragment\n    {\n        public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)\n        {\n            base.OnCreateView (inflater, container, savedInstanceState);\n\n            var view = inflater.Inflate (Resource.Layout.Tab, container, false);\n            var sampleTextView = view.FindViewById\u003cTextView\u003e (Resource.Id.textView);\n            sampleTextView.Text = \"This is Video Fragment Sample\";\n\n            return view;\n        }\n}\n}
1\n```\n\n## Output\n\n[![Action Bar Tabs example in Xamarin](/media/articles/313/Action-Bar-Tabs-example-in-Xamarin.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"114:T9b5,"])</script>
1<script>self.__next_f.push([1,"\nThis example explains how to implement “share action in your action bar using ShareActionProvider class”. `ActionProvider` is made available since Android 4.0 (API Level 14). An ActionProvider, once attached to a menu item in the action bar, handles both the appearance and behavior of that item. In the case of ShareActionProvider, you provide a share intent and it does the rest.\n\n## Specifying the action Provider Class\n\nTo use the ShareActionProvider, set the `android:actionProviderClass` attribute on a menu item in the XML for the Action Bar’s menu.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cmenu xmlns:android=\"http://schemas.android.com/apk/res/android\"\u003e\n  \u003citem android:id=\"@+id/shareMenu\"\n      android:showAsAction=\"always\"\n      android:title=\"Share\"\n      android:actionProviderClass=\"android.widget.ShareActionProvider\" /\u003e\n\u003c/menu\u003e\n```\n\n## Your activity class\n\n```csharp\nusing System;\n\nusing Android.App;\nusing Android.Content;\nusing Android.Runtime;\nusing Android.Views;\nusing Android.Widget;\nusing Android.OS;\n\nnamespace ShareActionProviderExample\n{\n    [Activity (Label = \"ShareActionProviderExample\", MainLauncher = true)]\n    public class MainActivity : Activity\n    {\n        protected override void OnCreate (Bundle bundle)\n        {\n            base.OnCreate (bundle);\n\n            TextView tv = new TextView (this);\n            tv.Text = \"This is an ShareActionProvider Example\";\n            tv.SetPadding (20, 20, 20, 20);\n\n            // Set our view from the \"main\" layout resource\n            SetContentView (tv);\n        }\n\n        public override bool OnCreateOptionsMenu (IMenu menu) {\n\n            MenuInflater.Inflate (Resource.Menu.MainMenu, menu);\n\n            var shareMenuItem = menu.FindItem (Resource.Id.shareMenu);\n            var shareActionProvider =\n                (ShareActionProvider)shareMenuItem.ActionProvider;\n            shareActionProvider.SetShareIntent (CreateIntent ());\n\n            return true;\n        }\n\n        Intent CreateIntent () {\n            var sendPictureIntent = new Intent (Intent.ActionSend);\n            sendPictureIntent.SetType (\"image/*\");\n            var uri = Android.Net.Uri.FromFile (GetFileStreamPath (\"image.png\"));\n            sendPictureIntent.PutExtra (Intent.ExtraStream, uri);\n            return sendPictureIntent;\n        }\n    }\n}\n```\n\n## Output\n\n[![ShareActionProvider Example in Xamarin](/media/articles/314/ShareActionProvider-Example-in-Xamarin-620x435.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"115:T9c6,"])</script>
1<script>self.__next_f.push([1,"\nThis example explains how to apply Shadow Effect on Android TextView. You can apply Shadow Effect on Android TextView in two ways. Either we do it pragmatically or we can change in the xml layout.\n\n## Shadow Effect on Android TextView using XML Layout\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:orientation=\"vertical\"\n    android:padding=\"20dp\" \u003e\n\n    \u003cTextView\n        android:id=\"@+id/textview\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center_horizontal\"\n        android:shadowColor=\"#000\"\n        android:shadowDx=\"0\"\n        android:shadowDy=\"0\"\n        android:shadowRadius=\"50\"\n        android:text=\"Text Shadow Example1\"\n        android:textColor=\"#FBFBFB\"\n        android:textSize=\"28dp\"\n        android:textStyle=\"bold\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/textview2\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center_horizontal\"\n        android:text=\"Text Shadow Example2\"\n        android:textColor=\"#FBFBFB\"\n        android:textSize=\"28dp\"\n        android:textStyle=\"bold\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\nIn the above XML layout code, the textview1 is given with Shadow effect in the layout. below are the configuration items are\n\n-   **android:shadowDx** – specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right\n-   **android:shadowDy** – it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.\n-   **android:shadowRadius** – specifies how much the shadow should be blurred at the edges. Provide a small value if shadow needs to be prominent.\n-   **android:shadowColor** – specifies the shadow color\n\n## Shadow Effect on Android TextView pragmatically\n\nUse below code snippet to get the shadow effect on the second TextView pragmatically.\n\n```java\nTextView textv = (TextView) findViewById(R.id.textview2);\ntextv.setShadowLayer(30, 0, 0, Color.RED);\n```\n\n## Output\n\n[![Shadow Effect on Android TextView](/media/articles/315/Shadow-Effect-on-Android-TextView-300x533.png)](http://stacktips.com)\n\n### Download Source Code\n\nDownload complete source code from [**Github**](https://github.com/javatechig/Android-User-Interface-Tutorials/tree/master/AndroidTextShadow)\n"])</script>
1<script>self.__next_f.push([1,"116:T669,"])</script>
1<script>self.__next_f.push([1,"\nFind some of the useful git commands for creating and managing a new branch in git.\n\n## 1. Create a New Branch in Git\n\nYou may need to create a branch anytime during development for keeping your clean to your master branch. Usually, we create a new branch by copying the master or current branch code. Branches can be merged to master or other branches.\n\nRemember to keep your master clean before creating a new branch. Commit and sync your uncommitted changes, if any in your local repository. Open your Git Shell and follow the below git commands to create a new branch on your local machine:\n\n```bash\n$ git branch \u003cname_of_your_new_branch\u003e\n```\n\nOnce your branch is created you will push the branch on GitHub remote by using the below commands\n\n```bash\n$ git push origin \u003cname_of_your_new_branch\u003e\n```\n\n## 2. Switch to your new branch\n\n```bash\n$ git checkout \u003cname_of_your_new_branch\u003e\n```\n\n## 3. List all branches created\n\n```bash\n$ git branch\n```\n\n## 4. Adding files/folders to the branch\n\nNow you may add some new files or folders to this branch. Either you may create a new file using your vim editor or you may paste the files and folders using your file explorer. When you want to commit something in your branch, be sure to be in your branch. Before committing you must all new files/folders using the below command.\n\n```bash\n$ git add-A\n```\n\n```bash\n$ git push origin \u003cnew branchName\u003e\n```\n\n## 5. Delete a git branch\n\nThe first git command deletes the branch on your local file system and the second command deletes branch in Github\n\n```bash\n$ git branch -d \u003cname_of_your_new_branch\u003e\n$ git push origin :\u003cname_of_your_new_branch\u003e\n```\n"])</script>
1<script>self.__next_f.push([1,"117:T92a,"])</script>
1<script>self.__next_f.push([1,"\nIf-else statement in java is used for conditional checks for decision making. You can have multiple hierarchies of if-else statements. Once any of the if or else-if condition satisfies it executes the block of statements corresponding to it. An else statement is optional. If none of if or else-if statements satisfies then else statement gets executed. Once the statements inside if-else block is executed it continue program normally with rest of the statement/block.\n\n[![if-then and if-then-else Statements](/media/articles/319/if-then-and-if-then-else-Statements.png)](http://stacktips.com)\n\nFor example, if you want check a number N1 is greater than or less to another number N2, then you will have to use if-else block. Below example will demonstrates the usages of if else statements.\n\n```java\nimport java.util.Scanner;\n\npublic class JavaTest {\n\n    public static void main(String[] args) {\n\n        int N1 = 10;\n        System.out.println(\"Enter Value for N2:\");\n        Scanner scanner = new Scanner(System.in);\n        int N2 = scanner.nextInt();\n\n        if (N1 \u003e N2) {\n            System.out.println(\"N1 is greater\");\n        } else if (N1 == N2) {\n            System.out.println(\"N1 and N2 are equal\");\n        } else {\n            System.out.println(\"N2 is greater\");\n        }\n    }\n}\n```\n\nWell, let’s give a closure look at the above code. Here In this example we are defining two integer variables N1 and N2. N1 is predefined with value 10 and for N2 we are asking users input. Scanner is used to accept input from user. More about scanner we’ll cover in later sections of tutorials.\n\n### Test Case1- For user entered value for N2 = 8\n\nThe fist if condition is checking whether, the value of N1 is greater than value of N2. As 10 is greater than 8, it satisfies the condition and executes the associated block of code. Here in this case it prints “N1 is greater”\n\n### Test Case2- For user entered value for N2 = 10\n\nIt will fail the first if condition check and it will check for the else if block. The else-if block condition satisfies and it executes the associated block of code. Here in this case it prints “N1 is equals to N2”\n\n### Test Case2- For user entered value for N2 = 20\n\nBoth if and else-if will fail for the value of N2 as 20. Then it executes the else statement and it will print “N2 is greater”\n"])</script>
1<script>self.__next_f.push([1,"118:Tab1,"])</script>
1<script>self.__next_f.push([1,"\nSwitch case is another alternative for if-else statements. Switch case statement compares value in the object in the expression with the expressions associated with each case. A switch works only with primitive types like byte, short, char, and int and enumerated data types. But since Java SDK7, it also supports String type.\n\n[![Switch-Case statement in Java](/media/articles/321/Switch-Case-statement-in-Java.png)](http://stacktips.com)\n\nThe following code example demonstrates switch case with example. An integer value day is passed as an parameter and the code will display the day of week.\n\n```java\npublic class StringSwitch {\n\n    public static void main(String[] args) {\n        int day = 2;\n        String dayOFWeek = \"\";\n        switch (day) {\n        case 1:\n            dayOFWeek = \"MON\";\n            break;\n        case 2:\n            dayOFWeek = \"TUE\";\n            break;\n        case 3:\n            dayOFWeek = \"WED\";\n            break;\n        case 4:\n            dayOFWeek = \"THU\";\n            break;\n        case 5:\n            dayOFWeek = \"FRI\";\n            break;\n        case 6:\n            dayOFWeek = \"SAT\";\n            break;\n        case 7:\n            dayOFWeek = \"SUN\";\n        default:\n        }\n        System.out.println(dayOFWeek);\n    }\n}\n```\n\n-   The older version of java supports switch case statement only with primitive types. It doesn’t supports String comparisons using switch case.\n-   But since JDK 7 release, you can use a String object in the expression of a switch statement.\n-   The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive.\n-   Java compiler generates generally more efficient byte code from switch statements that use String objects than from chained if-then-else statements.\n\nThe following code example demonstrates switch case with using String comparison example. Note that, you Java to compile with Java 7 and above.\n\n```java\npublic class StringSwitch {\n    public static void main(String[] args) {\n        String key = \"TWO\";\n        switch (key) {\n        case \"ONE\":\n            key = \"One Selected!\";\n            break;\n        case \"TWO\":\n            key = \"Two Selected!\";\n            break;\n        case \"THREE\":\n            key = \"Three Selected!\";\n            break;\n        case \"FOUR\":\n            key = \"Four Selected!\";\n            break;\n        case \"FIVE\":\n            key = \"Five Selected!\";\n            break;\n        case \"SIX\":\n            key = \"Six Selected!\";\n            break;\n        default:\n\n        }\n        System.out.println(key);\n\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"119:T182a,"])</script>
1<script>self.__next_f.push([1,"\nJack and Jill says this tutorial is retired. And we agree! This tutorial was published back in May 2014, since then lot has been changed; YouTubePlayerAPI is updated and Eclipse for Android development is history. Checkout our new [YouTube Android Player API Example](/articles/youtube-android-player-api-example) here.\n\nIn this tutorial we’ll see how to use YouTube Player API in android. YouTube player API provides an embedded view that supports with various playback controls.\n\n## 1. Downloading YouTube Player API\n\nBefore you start writing some code, you’ll have to first download the YouTube Android Player API. Once downloaded import the jar into your project lib folder and add the jar to your build path.\n\n**Download [YouTube Player API here](https://developers.google.com/youtube/android/player/downloads/)**\n\n[![YouTube Android Player API](/media/articles/323/YouTube-Android-Player-API-620x380.png)](http://stacktips.com)\n\n## 2. Register your app in Google developer console\n\n-   Before you start using the Youtube player API for android, you have to register your application with Google developer console and get and API key, The API key is a unique value for your application. Do not disclose this to others.\n-   Visit [**Google APIs Console**](https://console.developers.google.com) and login with your Google account and create a new project\n-   Once your project is created, got to API’s and enable **YouTube data API V3**\n-   And then Select **API Access** in your API Console. You’ll find API key. This API key will be used to access YouTube Android Player APIs.\n\n[![YouTube Android Player API2](/media/articles/323/YouTube-Android-Player-API2-620x301.png)](http://stacktips.com)\n\n## 3. Create a new Android Application project\n\nNow you are ready to create Android project to play YouTube videos using YouTube player API. You may use IDE of your choice, here I am using Eclipse.\n\nYou need `INTERNET` permission to play video over internet. Add below permission in your application `AndroidManifest.xml` file.\n\n```xml\n\u003cuses-permission android:name=\"android.permission.INTERNET\" /\u003e\n```\n\n## 4. Define your activity layout\n\nIn this example, we will create an simple layout that uses YouTubePlayerView inside an LinearLayout.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\" \u003e\n\n    \u003ccom.google.android.youtube.player.YouTubePlayerView\n        android:id=\"@+id/youtube_player\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:background=\"#fff\"\n        android:padding=\"5dp\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n## 5. Initialize YouTubePlayerView in your Activity\n\nInitializing YouTube player view by calling initialize methood. Once the initialize is successful, you will get the `onInitializationSuccess()` callback with `YouTubePlayer` instance. You can add additional listeners to handle the playback control events.\n\n```java\npackage com.javatechig.youtubeapp;\n\nimport android.os.Bundle;\nimport android.widget.Toast;\nimport com.google.android.youtube.player.YouTubeBaseActivity;\nimport com.google.android.youtube.player.YouTubeInitializationResult;\nimport com.google.android.youtube.player.YouTubePlayer;\nimport com.google.android.youtube.player.YouTubePlayer.ErrorReason;\nimport com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;\nimport com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;\nimport com.google.android.youtube.player.YouTubePlayer.Provider;\nimport com.google.android.youtube.player.YouTubePlayerView;\nimport com.javatechig.youtubeandroid.R;\n\npublic class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {\n    public static final String API_KEY = \"YOUR API KEY\";\n\n    //http://youtu.be/\u003cVIDEO_ID\u003e\n    public static final Str
1ing VIDEO_ID = \"dKLftgvYsVU\";\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        /** attaching layout xml **/\n        setContentView(R.layout.activity_main);\n\n        /** Initializing YouTube player view **/\n        YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);\n        youTubePlayerView.initialize(API_KEY, this);\n    }\n\n    @Override\n    public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {\n        Toast.makeText(this, \"Failured to Initialize!\", Toast.LENGTH_LONG).show();\n    }\n\n    @Override\n    public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {\n        /** add listeners to YouTubePlayer instance **/\n        player.setPlayerStateChangeListener(playerStateChangeListener);\n        player.setPlaybackEventListener(playbackEventListener);\n\n        /** Start buffering **/\n        if (!wasRestored) {\n            player.cueVideo(VIDEO_ID);\n        }\n    }\n\n    private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {\n\n        @Override\n        public void onBuffering(boolean arg0) {\n        }\n\n        @Override\n        public void onPaused() {\n        }\n\n        @Override\n        public void onPlaying() {\n        }\n\n        @Override\n        public void onSeekTo(int arg0) {\n        }\n\n        @Override\n        public void onStopped() {\n        }\n\n    };\n\n    private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {\n\n        @Override\n        public void onAdStarted() {\n        }\n\n        @Override\n        public void onError(ErrorReason arg0) {\n        }\n\n        @Override\n        public void onLoaded(String arg0) {\n        }\n\n        @Override\n        public void onLoading() {\n        }\n\n        @Override\n        public void onVideoEnded() {\n        }\n\n        @Override\n        public void onVideoStarted() {\n        }\n    };\n}\n```\n\n## 6. Output  \n[![YouTube Android Player API Example - Javatechig](/media/articles/323/YouTube-Android-Player-API-Example-Javatechig-620x390.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"11a:T914,"])</script>
1<script>self.__next_f.push([1,"\nThis example shows how to remove duplicate from ArrayList using Comparator. The easiest way to remove duplicate is by passing the List to an Set. We will use Comparator to remove duplicate elements. Once you have the Set you can again pass it back to ArrayList.\n\n```java\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.Set;\nimport java.util.TreeSet;\n\npublic class RemoveDuplicate {\n\n    public static void main(String[] args) {\n\n        final ArrayList students = new ArrayList();\n        students.add(new Student(\"Student1\", \"1000\"));\n        students.add(new Student(\"Student2\", \"1001\"));\n        students.add(new Student(\"Student3\", \"1002\"));\n        students.add(new Student(\"Student4\", \"1003\"));\n        students.add(new Student(\"Student5\", \"1001\"));\n        students.add(new Student(\"Student6\", \"1004\"));\n\n        /** Printing original list **/\n        System.out.println(students);\n\n        Set set = new TreeSet(new Comparator() {\n            @Override\n            public int compare(Student o1, Student o2) {\n                if(o1.getId().equalsIgnoreCase(o2.getId())){\n                    return 0;\n                }\n                return 1;\n            }\n        });\n        set.addAll(students);\n\n        System.out.println(\"\\n***** After removing duplicates *******\\n\");\n\n        final ArrayList newList = new ArrayList(set);\n\n        /** Printing original list **/\n        System.out.println(newList);\n    }\n\n}\n\nclass Student {\n    private String name;\n    private String id;\n\n    public Student(String name, String id) {\n        this.name = name;\n        this.id = id;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public String getId() {\n        return id;\n    }\n\n    public void setId(String id) {\n        this.id = id;\n    }\n\n    @Override\n    public String toString() {\n        return \"\\n\" +\"Name=\" + name + \"   Id=\" + id ;\n    }\n}\n```\n\n### Output\n\n```text\n[\nName=Student1   Id=1000,\nName=Student2   Id=1001,\nName=Student3   Id=1002,\nName=Student4   Id=1003,\nName=Student5   Id=1001,\nName=Student6   Id=1004]\n\n***** After removing duplicates *******\n\n[\nName=Student1   Id=1000,\nName=Student2   Id=1001,\nName=Student3   Id=1002,\nName=Student4   Id=1003,\nName=Student6   Id=1004]\n```\n"])</script>
1<script>self.__next_f.push([1,"11b:Tc03,"])</script>
1<script>self.__next_f.push([1,"\n## Java keywords\n\nThere are over 50 reserved keywords in Java programming language. Keywords are the language construct has predefined meaning in the Java. As they are reserved, we cannot use keywords as names for variables, methods, classes, or as any other identifier.\n\nFollowing are some of the java keywords are listed below\n\n| abstract | continue | for | new | switch |\n| --- | --- | --- | --- | --- |\n| assert*** | default | goto* | package | synchronized |\n| boolean | do | if | private | this |\n| break | double | implements | protected | throw |\n| byte | else | import | public | throws |\n| case | enum**** | instanceof | return | transient |\n| catch | extends | int | short | try |\n| char | final | interface | static | void |\n| class | finally | long | strictfp** | volatile |\n| const* | float | native | super | while |\n\n## Java Comments\n\nWhile writing code, you must write set of comments for your own understanding or for others to understand your code. Such blocks are called comments. Comments can appear anywhere in the source code where whitespaces are allowed. Java Comments are not gets compiled or makes any sense to JVM. Java supports various type of comments such single line or multi line comments.\n\nA singleline comment is represented by slash-shash (//). Example of single line comment\n\n```java\n// This is a single line comment\n```\n\nMultiline comments are represented as follows\n\n```java\n/**\n* This is a multiline comment\n**/\n```\n\n## Java Data Types\n\nThere are eight Java data types – byte, short, int, long, float, double, char and boolean. We will discuss more in details on the upcoming chapters.\n\n## Java Development Kit\n\nThe Java Developer’s Kit is distributed by Sun Microsystems. The JDK contains documentation, examples, installation instructions, class libraries and packages, and tools.\n\n## Java Literals\n\nLiterals are any number, text, or other information that represents a value. Literals are the values assigned to variables.\n\n```java\nint num = 100;\n```\n\nHere 100 is a integer literal.\n\n## Class, Objects and Methods in Java\n\nJava Class is nothing but a template for object you are going to create or it’s a blue print by using this we create an object. Whatever we can see in this world all the things are a object. And all the objects are categorized in a special group. That group is termed as a class. Methods are how we communicate with objects. When we invoke or call a method we are asking the object to carry out a task\n\n## Interface in Java\n\nAn interface is a collection of methods that have no implementation – they are just created, but have no functionality. An interface is a bit like a class, except you can only declare methods and variables in the interface. You cannot actually implement the methods.\n\n## Arrays\n\nAn array is a set of variables that are referenced using a single variable name combined with an index number. Each item of an array is called an element. All the elements in an array must be of the same type. Thus the array itself has a type that specifies what kind of elements it can contain.\n"])</script>
1<script>self.__next_f.push([1,"11c:T1339,"])</script>
1<script>self.__next_f.push([1,"\nJava is a high-level English like an object-oriented programming language with tons of `APIS` (application programming interface) for developing applications. Java is a platform independent language with support for performing complex computation, graphics, server and mobile application development.\n\nJava language syntax looks pretty much like C and C++, however, there are some differences such as the absence of pointers, allows writing object-oriented code. Learning Java is easy for a developer with a basic C programming experience.\n\nJava is one of the vastly used languages as it supports **“write once run anywhere”** architecture. A java program written in Macintosh can be executed on Windows or Linux without any modification or without recompiling it again. To understand how Java achieves platform independence, we must understand the way the java program is compiled and executed.\n\n### Writing First Java Program\n\nA simple java program can be written in any text editor such as Notepad, WordPad, notepad++ or edit plus. While writing your Java program make sure it must have one public class and one public static void method`main()` which allow it to run a java program when invoked in Java Virtual Machine.\n\nFor now without worrying much about how to go with it, just copy and paste the following code in your favorites text editor. We will learn about the building blocks in details on the following sections. After pasting the following code, save your file with name HelloWorld.java extension. Now we are ready for next step to compiling and run Java program.\n\n```java\n/* Hello World Java Program */\npublic class HelloWorld {\n\n  public static void main(String[] args) {\n    System.out.println(“Hello World!”);\n  }\n}\n```\n\n### Compiling Java Code\n\nCompiling Java code requires a compiler that comes along with Java Development Kit also called as JDK. This tutorial assumes that you have already installed Java JDK on your development computer, if not you can download and install from Oracle’s site.\n\nIf you are not sure, if java is installed properly, you can check by entering the command`javac –help` in your command line. If installed properly, you will see the output as depicted in the screenshot below.\n\n[![Compiling Java code](/media/articles/328/Compiling-Java-code-940x514.png)](http://stacktips.com)\n\nOnce you are ready with your Java development environment, you can compile your java code by invoking the command`javac` from command line. Enter the following command to compile HelloWorld.java\n\n```java\n\u003e javac HelloWorld.java\n```\n\nThe above code will compile your java source file and produce a new file named.`HelloWorld.class` Open HelloWorld.class file in a text editor; notice that it contains some unreadable bytecode. This Class file is actually java’s way to achieve platform independence. This class file contains JVM specific bytecode instead of machine code, unlike the C or C++ that makes it possible to run java program in any platform.\n\n### Running Java Application\n\nWe know that after compilation java compiler creates a`.class` file that contains JVM specific bytecodes and to execute those bytecodes we need a piece of software called Java Virtual Machine or JVM. JVM is also known as Java Runtime or JRE. Bytecodes of java programs executed inside Java Virtual Machine which is platform dependence, you here it correctly JVM are indeed platformed dependent and it has the different binary for the different platform which you can download from Sun’s site. JVM also comes with JDK or you can download it separately.\n\nUse the following command to compile the above code\n\n```java\n\u003e java HelloWorld\n```\n\nThe output of the above java program is  \nHello World!\n\n### Importance of JVM?\n\nIt’s important to know that the JVM ((Java Virtual Machine) doesn’t have any information high-level java code. It knows the only binary format of the bytecode and ensures that the class file generated by java compiler is as per Java Byte Code specification thus eliminating dangers of running a malicious and manipulated java bytecodes.\n\nSince every Java program runs within the boundaries defined by Java Virtual machine or JVM it provides inherent Security. The code run inside the JVM cannot go beyond the security constraints defined by the Java Virtual Machine. This is why java application is considered as secure applications over the internet and Java applets are the most widely used programming platform for the internet. Apart from Security Java Virtual machine also provides memory management via Garbage collection that enables java programmer or Java developer to focus more on business logic rather than worrying about system aspects like allocating and reclaiming memory.\n\nIn conclusion with the use of the class file, bytecode and Java virtual machine, Java achieves its platform independence and makes development easy to run across different platform.\n"])</script>
1<script>self.__next_f.push([1,"11d:T7fb,"])</script>
1<script>self.__next_f.push([1,"\nThis example shows how to remove duplicate from ArrayList. The easiest way to remove duplicate is by passing the List to an Set. As set doesn’t support duplicates it will omit the duplicate values. Once you have the Set you can again pass it back to ArrayList.\n\n### Duplicate Values From Java ArrayList using HashSet\n\n```java\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class RemoveDuplicate {\n    public static void main(String[] args) {\n        List sourceList = new ArrayList();\n\n        sourceList.add(\"object1\");\n        sourceList.add(\"object2\");\n        sourceList.add(\"object2\");\n        sourceList.add(\"object3\");\n        sourceList.add(\"object4\");\n        sourceList.add(\"object2\");\n\n        List newList = new ArrayList(new HashSet(\n                sourceList));\n        Iterator it = newList.iterator();\n        while (it.hasNext()) {\n            System.out.println(it.next());\n        }\n\n    }\n}\n```\n\n### Output\n\n```text\nobject3\nobject4\nobject1\nobject2\n```\n\nIn this above example we have removed duplicates from the ArrayList but we will loose the sequencing index. If you want to preserve the order of data use LinkedHashSet rather HashSet. Find an example below\n\n### Duplicate Values From Java ArrayList using LinkedHashSet\n\n```java\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashSet;\nimport java.util.List;\n\npublic class RemoveDuplicate {\n    public static void main(String[] args) {\n        List sourceList = new ArrayList();\n\n        sourceList.add(\"object1\");\n        sourceList.add(\"object2\");\n        sourceList.add(\"object2\");\n        sourceList.add(\"object3\");\n        sourceList.add(\"object4\");\n        sourceList.add(\"object2\");\n\n        List newList = new ArrayList(new LinkedHashSet(\n                sourceList));\n        Iterator it = newList.iterator();\n        while (it.hasNext()) {\n            System.out.println(it.next());\n        }\n\n    }\n}\n```\n\n### Output\n\n```text\nobject1\nobject2\nobject3\nobject4\n```\n"])</script>
1<script>self.__next_f.push([1,"11e:T1b7d,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial we’ll see the core collection interface available in java and their behavior. Examples in each section will show you the implementation and usage of various collection interfaces.\n\n### Introduction to Java collection API\n\nJava Collections API is a set of interface and implementations included in the java standard library. A collection is a container that holds multiple objects into single unit. Different collection has their own purpose and behaviors. All collection interfaces and classes are available under java.util package.  \nCollection interfaces are the abstract behavior of each collection.\n\n[](http://stacktips.com)\n\n## Collection Interface\n\nCollection interface is the root of collection hierarchy and it represents general purpose behavior for the entire interface in this hierarchy. It doesn’t have a concrete implementation.\n\n### Set Interface\n\n-   A set is a collection that doesn’t allow duplicate entries. A set has the same methods as the collection interface. It can contain at least one 1 null element.\n-   The set implementations are HashSet, LinkedHashSet and TreeSet.\n-   Element in HashSet, LinkedHashSet are not sorted but TreeSet is sorted.\n\n**Example: SetExample.java**\n\n```java\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\n\npublic class SetExample {\n  public static void main(String args[]) {\n     int count[] = {34, 22,10,60,30,22};\n     Set\u003cInteger\u003e set = new HashSet\u003cInteger\u003e();\n     try{\n        for(int i = 0; i\u003c5; i++){\n           set.add(count[i]);\n        }\n        System.out.println(\"Initial Set=\" + set);\n\n        set.remove(30);\n        System.out.println(\"Values after delete=\" + set);\n\n        System.out.println(\"Retrieving Values\");\n        Iterator\u003cInteger\u003e iterator = set.iterator();\n        while(iterator.hasNext()){\n            System.out.println(iterator.next());\n        }\n\n     }\n     catch(Exception e){}\n  }\n}\n```\n\n#### Output\n\n```text\nInitial Set=[34, 22, 10, 30, 60]\nValues after delete=[34, 22, 10, 60]\nRetrieving Values\n34\n22\n10\n60\n```\n\n### HashSet\n\n-   HashSet is an abstract implementation of Set interface. It creates a collection that uses a hash table for storing the elements.\n-   A HashTable uses hashing mechanism to store the objects. Hashing means, a key is used to determine a unique value, called its hash code. Every hash code represents a data associated with key.\n\nFor example, please refer the previous example block\n\n### LinkedHashSet\n\n-   LinkedHashSet maintains a linked list of the entries in the set.\n-   The elements are stored in the order in which they were inserted.\n-   While retrieving the LinkedHashSet elements using an Iterator, the elements will be returned in the order in which they were inserted.\n\n**Example: LinkedHashSetExample.java**\n\n```java\nimport java.util.Iterator;\nimport java.util.LinkedHashSet;\n\npublic class LinkedHashSetExample {\n    public static void main(String args[]) {\n        int count[] = { 34, 22, 10, 60, 30, 22, 25 };\n        LinkedHashSet\u003cInteger\u003e set = new LinkedHashSet\u003cInteger\u003e();\n\n        try {\n            for (int i = 0; i \u003c 7; i++) {\n                set.add(count[i]);\n            }\n            System.out.println(\"Initial Set=\" + set);\n\n            set.remove(30);\n            System.out.println(\"Values after delete=\" + set);\n\n            System.out.println(\"Retrieving Values\");\n            Iterator\u003cInteger\u003e iterator = set.iterator();\n            while (iterator.hasNext()) {\n                System.out.println(iterator.next());\n            }\n\n        } catch (Exception e) {\n        }\n    }\n}\n```\n\n#### Output\n\n```text\nInitial Set=[34, 22, 10, 60, 30, 25]\nValues after delete=[34, 22, 10, 60, 25]\nRetrieving Values\n34\n22\n10\n60\n25\n```\n\n### TreeSet\n\nTreeSet is a Set implementation that uses tree concept for storing object. It stores the elements in sorted order. Accessing TreeSet is quite faster than other set implementations.\n\n#### [TreeSet Example](http://stacktips.com/java/java-treeset-example \"Java TreeSet Example\")\n\n#### Example: TreeSetExample.java\n\n```java\nimport java.util.Iterator;\nimport java.util.Set;\nimport java.util.TreeSet;\n\npublic class TreeSetExample {\n\n    public static void main(String args[]) {\n        int count[] = { 14, 43, 10, 55, 30, 22,40};\n        Set\u003cInteger\u003e set = new TreeSet\u003cInteger\u003e();\n        try {\n            for (int i = 0; i \u003c 6;
1 i++) {\n                set.add(count[i]);\n            }\n            System.out.println(\"Intial Set=\" + set);\n\n            set.remove(30);\n            System.out.println(\"Values after delete=\" + set);\n\n            System.out.println(\"Retrieving Values\");\n            Iterator\u003cInteger\u003e iterator = set.iterator();\n            while (iterator.hasNext()) {\n                System.out.println(iterator.next());\n            }\n\n        } catch (Exception e) {\n        }\n    }\n}\n```\n\n#### Output\n\n```text\nIntial Set=[10, 14, 22, 30, 43, 55]\nValues after delete=[10, 14, 22, 43, 55]\nRetrieving Values\n10\n14\n22\n43\n55\n```\n\n### List Interface\n\n-   A List is an ordered collection of elements\n-   It may contain duplicate\n-   The indexing of the elements is similar to Array. The first index of List is zero.\n-   The elements can be manipulated based on their indexed positions\n-   Common List implementations are ArrayList and LinkedList\n\n### [ArrayList](http://stacktips.com/java/how-to-sort-an-arraylist-in-java \"How to sort an ArrayList in java\")\n\nThe ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.\n\n#### [Loop ArrayList In Java](http://stacktips.com/java/how-to-loop-arraylist-in-java \"How To Loop ArrayList In Java\")\n\n#### [Sort an ArrayList in java](http://stacktips.com/java/how-to-sort-an-arraylist-in-java \"How to sort an ArrayList in java\")\n\n### LinkedList\n\nThe LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list data structure.\n\n```java\nimport java.util.LinkedList;\n\npublic class LinkedListExample {\n    public static void main(String args[]) {\n        // create a linked list\n        LinkedList\u003cString\u003e list = new LinkedList\u003cString\u003e();\n        list.add(\"F\");\n        list.add(\"E\");\n        list.add(\"D\");\n        list.add(\"E\");\n        list.add(\"C\");\n        list.addLast(\"G\");\n        list.addFirst(\"B\");\n        list.add(1, \"E1\");\n        System.out.println(\"Values of LinkedList=\" + list);\n\n        // remove first and last elements\n        list.removeFirst();\n        list.removeLast();\n        System.out.println(\"After deleting first and last= \" + list);\n\n        // remove elements from the linked list\n        list.remove(\"C\");\n        list.remove(4);\n        System.out.println(\"After Delete\" + list);\n    }\n}\n```\n\n**Output**\n\n```text\nValues of LinkedList=[B, E1, F, E, D, E, C, G]\nAfter deleting first and last= [E1, F, E, D, E, C]\nAfter Delete[E1, F, E, D]\n```\n"])</script>
1<script>self.__next_f.push([1,"11f:Tb5b,"])</script>
1<script>self.__next_f.push([1,"\n## What is a Exception?\n\nException is an event during program execution that prevents the program from continuing normally. Exception is an error condition that changes the normal flow of control in a program. It is a signal that some unexpected condition has occurred in the program. Java classifies exceptions as Checked, Unchecked and Errors\n\n### Un-Checked Exception\n\nUnchecked exceptions are usually caused by incorrect program code or logic such as Invalid parameters passed to a method. Unchecked exceptions are subclass of RuntimeException class. The application is not required to handle this exceptions as these should be recovered by correcting the program code. Example of unchecked exceptions are NumberFormatException, IllegalArgumentException.\n\n### Checked Exception\n\nChecked Exception in Java is all those Exception which requires being catches and handled during compile time. If Compiler doesn’t see try or catch block handling a Checked Exception, it throws Compilation error. All exceptions except RuntimeException class is under checked exceptions category.\n\n## Errors\n\nErrors represent critical errors, once occurs the system is not expected to recover from. Errors can be generated from mistake in program logic or design. Example OutOfMemoryError, StackOverFlowError, etc.\n\n## Exception Class Hierarchy\n\n[![exception-hierarchy-in-java](/media/articles/332/exception-hierarchy-in-java.png)](http://stacktips.com)\n\n## Handling Exception\n\nJava exception handling is built around throw-catch paradigm. To throw means an exception has occurred and catch means the exception is handled. If the exception is not caught then it will be propagated to the call stack until it is handled by the program. The statement or code that is proven to generate checked exception should be handled by program.\n\n-   Exception handling is done using try-catch block. Try block contains the code that might throw an exception. A try block can contain one or more lines of code. For each exception type a individual catch block will be specified. Instead of writing multiple catch block for different exceptions, we can write the generic exception handler in catch block using super class “Exception” type of object.\n-   In the finally block you write the code that will be run whether or not an error has occurred. However this is optional. For example, if you get and exception while executing an database query, finally will be used to close the database connection.\n-   If the exception is not handled, it can be propagated to the call stack. In a method if we are not handling exception using try/catch block we can declare the method using “throws” keyword.\n-   A statement that might generate a checked exception that is declared by the method is considered “handled” and doesn’t need any try-catch block.\n-   You may explicitly throw an checked exception using “throw” keyword.\n"])</script>
1<script>self.__next_f.push([1,"120:T9f9,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we will examine how to multiple activities communicate each other.\n\nAndroid application is composed of multiple activities and they often communicate with each other by passing data. For example, lets say your application contains two activity Activity1 and Activity2. Activity1 is marked as launcher activity, which means it will be invoked automatically when user taps on the application icon from applications list. Note that, there can be at most one launcher activity throughout application. When user clicks on a button in Activity1, it will invoke Activity2.\n\n# Starting activity in Xamarin.Android\n\nXamarin Android provides easy to use startActivity method in activity context. The following code snippet will start Activity2 without passing any data\n\n```csharp\n StartActivity(typeof(Activity2));\n```\n\n# Starting activity by passing arguments\n\nThe above code block starts Activity2 without passing any data. However Xamarin android allows you to pass data from one activity to another using Intent bundle. All you have to do is to pass the instance of Intent to `startActivity()` method.\n\nThe Intent describes the activity to start and carries the data bundle to be sent to target activity. Intent can carry data types as key-value pairs called extras. The `putExtra()` method takes the key name in the first parameter and the value in the second parameter. Passing data between activities is limited to primitive data types. For object type you must use Parceable or Serilizable. For more information on the data types and intent, you can refer to official android documentation from below links.\n\nhttp://developer.android.com/reference/android/content/Intent.html\n\nhttp://developer.android.com/reference/android/os/Bundle.html\n\n```csharp\nIntent intent = new Intent(this, typeof(MainActivity2));\nintent.PutExtra(\"name\", \"Nilanchala\");\nintent.PutExtra(\"empid\", 1001);\nStartActivity(intent);\n```\n\nRetrieving data bundles received\n\nWe can receive the above passed data in “Activity2” using the below code snippet\n\n```csharp\nstring name = Intent.GetStringExtra(\"name\");\nint roll = Intent.GetIntegerExtra(\"empid\");\n```\n\nNote that you must use the same keys such as **“name”** and **“empid”** while retrieving the values from Activity2.\n\n# Receiving result back from Activity\n\nIf you want to receive a result from the activity when it finishes, call `startActivityForResult()` instead of `startActivity()`. Your activity receives the result as a separate Intent object in your activity’s `onActivityResult()` callback.\n"])</script>
1<script>self.__next_f.push([1,"121:T1332,"])</script>
1<script>self.__next_f.push([1,"\n## 1. Introduction\n\nThis is a tutorial explains how constructor works in Java. Constructor is an block of code which is executed before Object creation. Unlike methods constructors are getting called automatically.\n\n## 2. Properties of Constructors\n\n1.  Constructors are getting called automatically before you create an object\n2.  You class name and the constructor name should be same otherwise compiler treats that as an different method.\n3.  Constructor also can not have any return type by default it is void. However, we can still have an return statement that will return the control back from constructor.\n4.  Since Constructor is executed before object creation, the object initialization code is normally hosted inside constructor.\n5.  Like you override an method, you can also overload an constructor in Java.\n\n## 3. Constructor and Static\n\nStatic block is executed before constructor, because static members gets initialized during the class is getting loaded into memory but the constructors are executed only when you create instance of any object using new keyword.\n\n## 4. Declaring Constructor in Java\n\nIn the below code snippet, we have declared two constructors in ConstructorDemo class. One without argument and other taking a String argument. A java class can have as many as overridden constructors.\n\n```java\npublic class ConstructorDemo {\n    public ConstructorDemo() {\n        System.out.println(\"Constructor with no argument\");\n    }\n\n    public ConstructorDemo(String name) {\n        System.out.println(\"Constructor with argument\");\n    }\n\n    public static void main(String args[]) {\n\n        ConstructorDemo demo1 = new ConstructorDemo();\n        ConstructorDemo demo2 = new ConstructorDemo(\"Constructor Demo\");\n    }\n}\n```\n\n**Output**  \nConstructor with no argument  \nConstructor with argument\n\n## 5. Default Constructor in Java\n\nUsually we define constructor in almost every Class we declare in Java. If no explicit constructor is specified by Programmer, Java Compiler inserts a no argument constructor inside class. This is also called default Constructor in Java. If you define your own constructor, could be parameter or without any parameter, then compiler will not add default constructor. It is always a good practice to define a constructor.\n\n## 6. Calling Constructor and Chaining\n\nConstructors cannot be called explicitly like methods in java. But a constructor can call another constructor of same class or its immediate super class. Calling one constructor from another constructor in Java is called Constructor chaining. You can keyword “this” for calling constructor of same class and keyword “super” for calling constructor of super class. Call to constructor must be on the first line of any constructor or else you will get compilation error.\n\n### 6.1. Calling Class Constructor\n\n```java\npublic class ConstructorDemo {\n    public ConstructorDemo() {\n        System.out.println(\"Constructor with no argument\");\n    }\n\n    public ConstructorDemo(String name) {\n        this();\n        System.out.println(\"Constructor with argument\");\n    }\n\n    public static void main(String args[]) {\n        ConstructorDemo demo = new ConstructorDemo(\"Constructor Demo\");\n    }\n}\n```\n\n**Output**  \nConstructor with no argument  \nConstructor with argument  \nIn this above example, we are calling one constructor from another constructor of same class using this keyword. If you observe the output above, it is first calling the no argument constructor and then calls he constructor with argument.\n\n### 6.2. Calling Super Class Constructor\n\n```java\npublic class ConstructorDemoSuper {\n\n    public ConstructorDemoSuper() {\n        System.out.println(\"Super Class Constructor with no argument\");\n    }\n\n    public ConstructorDemoSuper(String name) {\n        System.out.println(\"Super Class Constructor with argument\");\n    }\n}\n\npublic class ConstructorDemo extends ConstructorDemoSuper {\n    public ConstructorDemo() {\n        super();\n        System.out.println(\"Constructor with no argument\");\n    }\n\n    public ConstructorDemo(String name) {\n        super(name);\n        System.out.println(\"Constructor with argument\");\n    }\n\n    public static void main(String args[]) {\n        ConstructorDemo demo1 = new ConstructorDemo(\"Constructor Demo\");\n        ConstructorDemo demo2 = new ConstructorDemo(\"Constructor Demo\");\n    }\n}\n```\n\n**Output**  \nSuper Class Constructor with argument  \nConstructor with argument  \nSuper Class Constructor with argument  \nConstructor with argument\n\n## 7. Constructor Access Modifiers\n\nJava has four basic modifiers, public, projected, private or default. You can use any of these access modifiers to constructor. You can prevent a to get initialize by other class by defining its constructor as private. Using Private constructor, only the same class can create instance of it. This is an typical example of most common singleton design pattern.\n"])</script>
1<script>self.__next_f.push([1,"122:T1750,"])</script>
1<script>self.__next_f.push([1,"\nCountDownLatch is one of the most useful Java concept that helps tracking multiple threads execution. This is useful when you want one or more threads to wait until a set of operations being performed in other threads completes.\n\nCountDownLatch helps in achieving maximum parallelism between multiple threads. Lets take a case here; sometimes you want to start multiple threads at the same time in parallel to main thread and once all the threads complete, you have to perform some actions on your main thread. This can be done easily if we create a CountDownLatch.\n\n## How it works?\n\nA CountDownLatch is initialized with a given N count. The await methods block the current thread execution until the count reaches zero. Once a task/thread completes the countDown() method will be called which results N– for every call. Once N size reaches zero, the thread which was awaiting returns immediately. CountDownLatch doesn't allow to change the count at runtime. i.e. once initialized it cannot be increased or reset.\n\nCreate `CountDownLatch` and initialize with the count N. Other worker threads must have reference of latch object, because they will need to notify the CountDownLatch object that they have completed their task.\n\nThis notification is done by countDown() method. Each time we call countDown() method, it decreases count of N. When all N threads have called this method, count reaches to zero and main thread is allowed to resume its execution.\n\n### CountDownLatch Example\n\nIn this example, we will download multiple images using worker thread. Once all the download complete, I expect my main thread to resume its execution. This example is a more simplified version just for your easy understanding.\n\nFirst lets solve this problem without using CountDownLatch\n\n**CountDownLatchTest.java**\n\n```java\nimport java.util.concurrent.CountDownLatch;\n\npublic class CountDownLatchTest {\n    private static int N = 6;\n\n    public static void main(String[] args) {\n        try {\n            for (int i = 0; i \u003c N; i++) {\n                new Thread(new MyWorker()).start();\n            }\n\n            System.out.println(\"*** Main Thread in Action ***\");\n        } catch (InterruptedException e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n\n**MyWorker.java**\n\n```java\nimport java.io.BufferedInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.util.concurrent.CountDownLatch;\n\npublic class MyWorker implements Runnable {\n\n    public MyWorker() {\n    }\n\n    @Override\n    public void run() {\n        try {\n            URL url = new URL(\n                    \"http://3rdbillion.net/wp-content/uploads/2013/11/35e7e6728456fed40f4f1b27d5d41c8513.jpg\");\n            InputStream in = new BufferedInputStream(url.openStream());\n            ByteArrayOutputStream out = new ByteArrayOutputStream();\n            byte[] buf = new byte[1024];\n            int n = 0;\n            while (-1 != (n = in.read(buf))) {\n                out.write(buf, 0, n);\n            }\n            out.close();\n            in.close();\n            byte[] response = out.toByteArray();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n        System.out.println(\"*** Worker Thread ****\");\n\n    }\n}\n```\n\nIn the above code snippet we have used multiple threads to download an image. (In this example, the downloaded image is only for demonstration, not being used for anything). Execute the above program, you will notice that it will results the output something similar as below\n\n**Output**\n\n```text\n*** Main Thread in Action ***\n*** Worker Thread ****\n*** Worker Thread ****\n*** Worker Thread ****\n*** Worker Thread ****\n*** Worker Thread ****\n*** Worker Thread ****\n```\n\n### Using CountDownLatch Example\n\n**CountDownLatchTest.java**\n\n```java\nimport java.util.concurrent.CountDownLatch;\n\npublic class CountDownLatchTest {\n\n    private static CountDownLatch _latch;\n    private static int N = 6;\n\n    public static void main(String[] args) {\n        _latch = new CountDownLatch(N);\n\n        try {\n            for (int i = 0; i \u003c N;
1 i++) {\n                new Thread(new MyWorker(_latch)).start();\n            }\n\n            _latch.await();\n\n            System.out.println(\"*** Main Thread in Action ***\");\n\n        } catch (InterruptedException e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n\n**MyWorker.java**\n\n```java\nimport java.io.BufferedInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.util.concurrent.CountDownLatch;\n\npublic class MyWorker implements Runnable {\n    private CountDownLatch _latch = null;\n\n    public MyWorker(CountDownLatch _latch) {\n        this._latch = _latch;\n    }\n\n    @Override\n    public void run() {\n        try {\n\n            URL url = new URL(\n                    \"http://3rdbillion.net/wp-content/uploads/2013/11/35e7e6728456fed40f4f1b27d5d41c8513.jpg\");\n            InputStream in = new BufferedInputStream(url.openStream());\n            ByteArrayOutputStream out = new ByteArrayOutputStream();\n            byte[] buf = new byte[1024];\n            int n = 0;\n            while (-1 != (n = in.read(buf))) {\n                out.write(buf, 0, n);\n            }\n\n            out.close();\n            in.close();\n\n            byte[] response = out.toByteArray();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        System.out.println(\"*** Worker Thread ****\");\n\n        _latch.countDown();\n    }\n}\n```\n\n**Output**\n\n```text\n*** Worker Thread ****\n*** Worker Thread ****\n*** Worker Thread ****\n*** Worker Thread ****\n*** Worker Thread ****\n*** Worker Thread ****\n*** Main Thread in Action ***\n```\n\nNotice the output above, the main thread was awaiting until all other worker threads completes their execution.  \nIf you like reading this post, please don’t forget to hit like or share with your friends!\n"])</script>
1<script>self.__next_f.push([1,"123:Tc3f,"])</script>
1<script>self.__next_f.push([1,"\nIn example explains how to create Popup menu in android. Popup menu is used to display the global actions. Popup menu is an overflow menu like Spinner actions. PopupMenu is available from API level 11 (Android 3.0).\n\n**activity\\_main.xml**\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:background=\"#fcfcfc\" \u003e\n\n    \u003cButton\n        android:id=\"@+id/btn_click\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"10dp\"\n        android:background=\"#176CEC\"\n        android:text=\"SHOW POPUP\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:textColor=\"#fff\"\n        android:textStyle=\"bold\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n**popup\\_menu.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cmenu xmlns:android=\"http://schemas.android.com/apk/res/android\" \u003e\n\n    \u003citem\n        android:id=\"@+id/item_movies\"\n        android:showAsAction=\"ifRoom|withText\"\n        android:title=\"Movies\"\n        android:visible=\"true\"/\u003e\n    \u003citem\n        android:id=\"@+id/item_music\"\n        android:showAsAction=\"ifRoom|withText\"\n        android:title=\"Music\"\n        android:visible=\"true\"/\u003e\n    \u003citem\n        android:id=\"@+id/item_comedy\"\n        android:showAsAction=\"ifRoom|withText\"\n        android:title=\"Comedy\"\n        android:visible=\"true\"/\u003e\n\n\u003c/menu\u003e\n```\n\n**PopMenuActivity.java**\n\n```java\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.PopupMenu;\nimport android.widget.PopupMenu.OnMenuItemClickListener;\nimport android.widget.Toast;\n\npublic class PopMenuActivity extends Activity implements OnMenuItemClickListener {\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        findViewById(R.id.btn_click).setOnClickListener(new OnClickListener() {\n            @Override\n            public void onClick(View view) {\n                PopupMenu popupMenu = new PopupMenu(PopMenuActivity.this, view);\n                popupMenu.setOnMenuItemClickListener(PopMenuActivity.this);\n                popupMenu.inflate(R.menu.popup_menu);\n                popupMenu.show();\n            }\n        });\n    }\n\n    public boolean onMenuItemClick(MenuItem item) {\n        switch (item.getItemId()) {\n        case R.id.item_comedy:\n            Toast.makeText(this, \"Comedy Clicked\", Toast.LENGTH_SHORT).show();\n            return true;\n        case R.id.item_movies:\n            Toast.makeText(this, \"Movies Clicked\", Toast.LENGTH_SHORT).show();\n            return true;\n        case R.id.item_music:\n            Toast.makeText(this, \"Music Clicked\", Toast.LENGTH_SHORT).show();\n            return true;\n        }\n    }\n}\n```\n\n**Output**  \n[![Popup Example in Android](/media/articles/340/Popup-Example-in-Android-620x451.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"124:T3090,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we will see how to use Dropbox API to share file to Dropbox in from your native Android application.\n\n[![Share file to Dropbox in Android Example](/media/articles/341/Share-file-to-Dropbox-in-Android-Example-e1435937309632.png)](http://stacktips.com)\n\n# 1. Create App on Dropbox\n\nFor integrating Dropbox services to your Android application, you need to use the Dropbox SDK. The SDK allows you to authenticate and share file on Dropbox. Before we begin, we need to download official [Dropbox API](https://www.dropbox.com/developers/core/sdks/android \"https://www.dropbox.com/developers/core/sdks/android\") from the link. Once download is complete, extract the file on your computer drive. Notice that the downloaded Zip file will have sample and library.\n\nNow, let us go ahead and create a new app on Dropbox developer console. Visit [Dropbox developer console](https://www.dropbox.com/developers/apps \"https://www.dropbox.com/developers/apps\") and create a new application. Once the application is setup, you will get an **App key** and **App Secret** that is required for integration.\n\n# 2. Using Dropbox SDK\n\nNow do the following changes to your application manifest file. Put the following code before \u003c/application\u003e tag. Make sure you are using your own AppID obtained from Facebook developer console.\n\n```xml\n\u003cactivity\n            android:name=\"com.dropbox.client2.android.AuthActivity\"\n            android:configChanges=\"orientation|keyboard\"\n            android:launchMode=\"singleTask\" \u003e\n            \u003cintent-filter\u003e\n                \u003c!-- Change this to be db- followed by your app key --\u003e\n                \u003cdata android:scheme=\"db-yatqpqyb9lsh0tu\" /\u003e\n\n                \u003caction android:name=\"android.intent.action.VIEW\" /\u003e\n                \u003ccategory android:name=\"android.intent.category.BROWSABLE\" /\u003e\n                \u003ccategory android:name=\"android.intent.category.DEFAULT\" /\u003e\n            \u003c/intent-filter\u003e\n        \u003c/activity\u003e\n```\n\n\u003e **Note:** Make sure that you have to declare android.permission.INTERNET permission in your application manifest file.\n\n# 3. Declare Activity Layout\n\nNow define layout for your activity class. In this example, We have three sample buttons one for login/logout , upload and view files.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:layout_marginTop=\"20dp\"\n    android:gravity=\"center_horizontal\"\n    android:orientation=\"vertical\" \u003e\n\n    \u003cButton\n        android:id=\"@+id/dropbox_login\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"10dp\"\n        android:background=\"#176CEC\"\n        android:text=\"Login to Dropbox\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:textColor=\"#fff\"\n        android:textStyle=\"bold\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/upload_file\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"10dp\"\n        android:background=\"#176CEC\"\n        android:text=\"Upload File to Dropbox\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:textColor=\"#fff\"\n        android:textStyle=\"bold\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/list_files\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"10dp\"\n        android:background=\"#176CEC\"\n        android:text=\"List All Files\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:textColor=\"#fff\"\n        android:textStyle=\"bold\" /\u003e\n\n    \u003cScrollView\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"match_parent\"\n        android:layout_margin=\"10dp\" \u003e\n\n        \u003cLinearLayout\n            android:id=\"@+id/container_files\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:orientation=\"vertical\" \u003e\n        \u003c/LinearLayout\u003e\n    \u003c/ScrollView\u003e\n\u003c/LinearLayout\u003e\n```\n\n# 4. Activity Java Code\n\n```java\npackage com.javatechig.dropboxsample;\n\nimport java.util.ArrayList;\nimport android.app.Activity;\nimport android.content.SharedPreferences;\nimport android.content.SharedPreferences.Editor;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport com.dropbox.client2.DropboxAPI;\nimport com.dropbox.client2.android.AndroidAuthSession;\nimport com.dropbox.client2.session.AccessTokenPair;\nimport com.dropbox.client2.session.AppKeyPair;\nimport com.dropbox.client2.session.Session.AccessType;\nimport com.dropbox.client2.session.TokenPair;\n\npublic class DropboxActivity extends Activity implements OnClickListener {\n    private DropboxAPI\u003cAndroidAuthSession\u003e dropbox;\n    private final static String FILE_DIR = \"/DropboxSample/\";\n    private final static String DROPBOX_NAME = \"dropbox_prefs\";\n    private final static String ACCESS_KEY = \"yatqpqyb9lsh0tu\";\n    private final static String ACCESS_SECRET = \"9siqdkoo44y3jlr\";\n    private boolean isLoggedIn;\n    private Button logIn;\n    private Button uploadFile;\n    private Button listFiles;\n    private LinearLayout container;\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_dropbox);\n\n        logIn = (Button) findViewById(R.id.dropbox_login);\n        logIn.setOnClickListener(this);\n        uploadFile = (Button) findViewById(R.id.upload_file);\n        uploadFile.setOnClickListener(this);\n        listFiles = (Button) findViewById(R.id.list_files);\n        listFiles.setOnClickListener(this);\n        container = (LinearLayout) findViewById(R.id.container_files);\n\n        loggedIn(false);\n        AndroidAuthSession session;\n        AppKeyPair pair = new AppKeyPair(ACCESS_KEY, ACCESS_SECRET);\n\n        SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);\n        String key = prefs.getString(ACCESS_KEY, null);\n        String secret = prefs.getString(ACCESS_SECRET, null);\n\n        if (key != null \u0026\u0026 secret != null) {\n            AccessTokenPair token = new AccessTokenPair(key, secret);\n            session = new AndroidAuthSession(pair, AccessType.APP_FOLDER, token);\n        } else {\n            session = new AndroidAuthSession(pair, AccessType.APP_FOLDER);\n        }\n        dropbox = new DropboxAPI\u003cAndroidAuthSession\u003e(session);\n    }\n\n    @Override\n    protected void onResume() {\n        super.onResume();\n\n        AndroidAuthSession session = dropbox.getSession();\n        if (session.authenticationSuccessful()) {\n            try {\n                session.finishAuthentication();\n                TokenPair tokens = session.getAccessTokenPair();\n                SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);\n                Editor editor = prefs.edit();\n                editor.putString(ACCESS_KEY, tokens.key);\n                editor.putString(ACCESS_SECRET, tokens.secret);\n                editor.commit();\n                loggedIn(true);\n            } catch (IllegalStateException e) {\n                Toast.makeText(this, \"Error during Dropbox authentication\",\n                        Toast.LENGTH_SHORT).show();\n            }\n        }\n    }\n\n    public void loggedIn(boolean isLogged) {\n        isLoggedIn = isLogged;\n        uploadFile.setEnabled(isLogged);\n        listFiles.setEnabled(isLogged);\n        logIn.setText(isLogged ? \"Log out\" : \"Log in\");\n    }\n\n    private final Handler handler = new Handler() {\n        public void handleMessage(Message msg) {\n            ArrayList\u003cString\u003e result = msg.getData().getStringArrayList(\"data\");\n            for (String fileName : result) {\n                Log.i(\"ListFiles\", fileName);\n                TextView tv = new TextView(DropboxActivity.this);\n                tv.setText(fileName);\n                container.addView(tv);\n            }\n        }\n    };\n\n    @Override\n    public void onClick(View v) {\n        switch (v.getId()) {\n        case R.id.dropbox_login:\n            if (isLoggedIn) {\n                dropbox.getSession().unlink();\n                loggedIn(false);\n            } else {\n                dropbox.getSession().startAuthentication(DropboxActivity.this);\n            }\n\n            break;\n        case R.id.list_files:\n            ListDropboxFiles list = new ListDropboxFiles(dropbox, FILE_DIR,\n                    handler);\n            list.execute();\n            break;\n        case R.id.upload_file:\n            UploadFileToDropbox upload = new UploadFileToDropbox(this, dropbox,\n                    FILE_DIR);\n            upload.execute();\n            break;\n        default:\n            break;\n        }\n    }\n}\n```\n\n# 5. Upload File to Dropbox\n\n```java\npackage com.javatechig.dropboxsample;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport android.content.Context;\nimport android.os.AsyncTask;\nimport android.widget.Toast;\nimport com.dropbox.client2.DropboxAPI;\nimport com.dropbox.client2.exception.DropboxException;\n\npublic class UploadFileToDropbox extends AsyncTask\u003cVoid, Void, Boolean\u003e {\n\n    private DropboxAPI\u003c?\u003e dropbox;\n    private String path;\n    private Context context;\n\n    public UploadFileToDropbox(Context context, DropboxAPI\u003c?\u003e dropbox,\n            String path) {\n        this.context = context.getApplicationContext();\n        this.dropbox = dropbox;\n        this.path = path;\n    }
1\n\n    @Override\n    protected Boolean doInBackground(Void... params) {\n        final File tempDir = context.getCacheDir();\n        File tempFile;\n        FileWriter fr;\n        try {\n            tempFile = File.createTempFile(\"file\", \".txt\", tempDir);\n            fr = new FileWriter(tempFile);\n            fr.write(\"Sample text file created for demo purpose. You may use some other file format for your app \");\n            fr.close();\n\n            FileInputStream fileInputStream = new FileInputStream(tempFile);\n            dropbox.putFile(path + \"textfile.txt\", fileInputStream,\n                    tempFile.length(), null, null);\n            tempFile.delete();\n            return true;\n        } catch (IOException e) {\n            e.printStackTrace();\n        } catch (DropboxException e) {\n            e.printStackTrace();\n        }\n\n        return false;\n    }\n\n    @Override\n    protected void onPostExecute(Boolean result) {\n        if (result) {\n            Toast.makeText(context, \"File Uploaded Sucesfully!\",\n                    Toast.LENGTH_LONG).show();\n        } else {\n            Toast.makeText(context, \"Failed to upload file\", Toast.LENGTH_LONG)\n                    .show();\n        }\n    }\n}\n```\n\n# 6. List Dropbox Files\n\n```java\npackage com.javatechig.dropboxsample;\n\nimport java.util.ArrayList;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Message;\nimport com.dropbox.client2.DropboxAPI;\nimport com.dropbox.client2.DropboxAPI.Entry;\nimport com.dropbox.client2.exception.DropboxException;\n\npublic class ListDropboxFiles extends AsyncTask\u003cVoid, Void, ArrayList\u003cString\u003e\u003e {\n\n    private DropboxAPI\u003c?\u003e dropbox;\n    private String path;\n    private Handler handler;\n\n    public ListDropboxFiles(DropboxAPI\u003c?\u003e dropbox, String path, Handler handler) {\n        this.dropbox = dropbox;\n        this.path = path;\n        this.handler = handler;\n    }\n\n    @Override\n    protected ArrayList\u003cString\u003e doInBackground(Void... params) {\n        ArrayList\u003cString\u003e files = new ArrayList\u003cString\u003e();\n        try {\n            Entry directory = dropbox.metadata(path, 1000, null, true, null);\n            for (Entry entry : directory.contents) {\n                files.add(entry.fileName());\n            }\n        } catch (DropboxException e) {\n            e.printStackTrace();\n        }\n\n        return files;\n    }\n\n    @Override\n    protected void onPostExecute(ArrayList\u003cString\u003e result) {\n        Message msgObj = handler.obtainMessage();\n        Bundle b = new Bundle();\n        b.putStringArrayList(\"data\", result);\n        msgObj.setData(b);\n        handler.sendMessage(msgObj);\n\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"125:Tba9,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we will see how to drag and ImageView in android on touch drag event.\n\n**Creating View layout**\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:id=\"@+id/root\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:padding=\"@dimen/activity_vertical_margin\" \u003e\n\n    \u003cImageView\n        android:id=\"@+id/imageView\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentTop=\"true\"\n        android:layout_centerHorizontal=\"true\"\n        android:layout_marginTop=\"124dp\"\n        android:src=\"@drawable/ic_launcher\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n**Activity Java code**\n\n```java\npackage com.javatechig;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.RelativeLayout;\n\npublic class MainActivity extends Activity implements View.OnTouchListener {\n\n    private ImageView mImageView;\n    private ViewGroup mRrootLayout;\n    private int _xDelta;\n    private int _yDelta;\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        mRrootLayout = (ViewGroup) findViewById(R.id.root);\n        mImageView = (ImageView) mRrootLayout.findViewById(R.id.imageView);\n\n        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(150, 150);\n        mImageView.setLayoutParams(layoutParams);\n        mImageView.setOnTouchListener(this);\n    }\n\n    public boolean onTouch(View view, MotionEvent event) {\n        final int X = (int) event.getRawX();\n        final int Y = (int) event.getRawY();\n        switch (event.getAction() \u0026 MotionEvent.ACTION_MASK) {\n        case MotionEvent.ACTION_DOWN:\n            RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();\n            _xDelta = X - lParams.leftMargin;\n            _yDelta = Y - lParams.topMargin;\n            break;\n        case MotionEvent.ACTION_UP:\n            break;\n        case MotionEvent.ACTION_POINTER_DOWN:\n            break;\n        case MotionEvent.ACTION_POINTER_UP:\n            break;\n        case MotionEvent.ACTION_MOVE:\n            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view\n                    .getLayoutParams();\n            layoutParams.leftMargin = X - _xDelta;\n            layoutParams.topMargin = Y - _yDelta;\n            layoutParams.rightMargin = -250;\n            layoutParams.bottomMargin = -250;\n            view.setLayoutParams(layoutParams);\n            break;\n        }\n        mRrootLayout.invalidate();\n        return true;\n    }\n}\n```\n\n**Output**\n\n[![Drag a View in Android](/media/articles/342/Drag-a-View-in-Android.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"126:T1446,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we will show how to create a ListView with section header. This involves following steps\n\n1.  Create two custom layout for your List header and List row\n2.  Create your custom adapter for ListView\n3.  Instantiate ListView in your activity\n\n### Create Custom layout for List header and List row\n\n**snippet\\_item1.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:gravity=\"center_vertical\" \u003e\n\n    \u003cTextView\n        android:id=\"@+id/text\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:background=\"#FFF\"\n        android:gravity=\"center_vertical\"\n        android:padding=\"5dp\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:textColor=\"#FF000000\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n**snippet\\_item2.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:background=\"#2F2F2F\"\n    android:gravity=\"center_vertical\" \u003e\n\n    \u003cTextView\n        android:id=\"@+id/textSeparator\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:gravity=\"center\"\n        android:padding=\"8dp\"\n        android:text=\"\"\n        android:textAllCaps=\"true\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:textColor=\"#FFF\"\n        android:textStyle=\"bold\"\n        android:visibility=\"visible\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n### Create your custom adapter for ListView\n\nYou must override getViewTypeCount() method. This method returns the number of types of Views that will be created by getView method.\n\n```java\npackage com.javatechig;\n\nimport java.util.ArrayList;\nimport java.util.TreeSet;\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.BaseAdapter;\nimport android.widget.TextView;\n\nclass CustomAdapter extends BaseAdapter {\n\n    private static final int TYPE_ITEM = 0;\n    private static final int TYPE_SEPARATOR = 1;\n\n    private ArrayList\u003cString\u003e mData = new ArrayList\u003cString\u003e();\n    private TreeSet\u003cInteger\u003e sectionHeader = new TreeSet\u003cInteger\u003e();\n\n    private LayoutInflater mInflater;\n\n    public CustomAdapter(Context context) {\n        mInflater = (LayoutInflater) context\n                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n    }\n\n    public void addItem(final String item) {\n        mData.add(item);\n        notifyDataSetChanged();\n    }\n\n    public void addSectionHeaderItem(final String item) {\n        mData.add(item);\n        sectionHeader.add(mData.size() - 1);\n        notifyDataSetChanged();\n    }\n\n    @Override\n    public int getItemViewType(int position) {\n        return sectionHeader.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;\n    }\n\n    @Override\n    public int getViewTypeCount() {\n        return 2;\n    }\n\n    @Override\n    public int getCount() {\n        return mData.size();\n    }\n\n    @Override\n    public String getItem(int position) {\n        return mData.get(position);\n    }\n\n    @Override\n    public long getItemId(int position) {\n        return position;\n    }\n\n    public View getView(int position, View convertView, ViewGroup parent) {\n        ViewHolder holder = null;\n        int rowType = getItemViewType(position);\n\n        if (convertView == null) {\n            holder = new ViewHolder();\n            switch (rowType) {\n            case TYPE_ITEM:\n                convertView = mInflater.inflate(R.layout.snippet_item1, null);\n                holder.textView = (TextView) convertView.findViewById(R.id.text);\n                break;\n            case TYPE_SEPARATOR:\n                convertView = mInflater.inflate(R.layout.snippet_item2, null);\n                holder.textView = (TextView) convertView.findViewById(R.id.textSeparator);\n                break;\n            }\n            convertView.setTag(holder);\n        } else {\n            holder = (ViewHolder) convertView.getTag();\n        }\n        holder.textView.setText(mData.get(position));\n\n        return convertView;\n    }\n\n    public static class ViewHolder {\n        public TextView textView;\n    }\n\n}\n```\n\n### Instantiate ListView in your activity\n\n```java\npackage com.javatechig;\n\nimport android.app.ListActivity;\nimport android.os.Bundle;\n\npublic class SectionListView extends ListActivity {\n\n    private CustomAdapter mAdapter;\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        mAdapter = new CustomAdapter(this);\n        for (int i = 1; i \u003c 30;
1 i++) {\n            mAdapter.addItem(\"Row Item #\" + i);\n            if (i % 4 == 0) {\n                mAdapter.addSectionHeaderItem(\"Section #\" + i);\n            }\n        }\n        setListAdapter(mAdapter);\n    }\n\n}\n```\n\n### Output\n\n[![ListView with section header in android](/media/articles/343/ListView-with-section-header-in-android.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"127:Tb26,"])</script>
1<script>self.__next_f.push([1,"\nIn the following example, we will see how to use TreeSet Collection in java. This example includes,\n\n-   How to create an TreeSet\n-   How to display element of Treeset\n-   Adding data to TreeSet\n-   Deleting data from TreeSet\n\n### Things to know about TreeSet\n\n1.  TreeSet is similar to TreeMap that stores its elements in a tree and maintain order of its elements based on their values. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.\n2.  To get the size of TreeSet collection size() method is used.\n3.  The size of the TreeSet can be determine by calling size() method.\n4.  remove() method can be used to remove an item/object\n5.  clear() method removes all object and makes the TreeSet empty\n6.  first() and last() method is used to get the first and last element in TreeSet\n\n## TreeSet Example\n\n```java\nimport java.util.Iterator;\nimport java.util.TreeSet;\n\npublic class TreeSetExample {\n\n    public static void main(String[] args) {\n        // adding Integer to treeset\n        TreeSet\u003cInteger\u003e treeSet = new TreeSet\u003cInteger\u003e();\n        treeSet.add(20);\n        treeSet.add(30);\n        treeSet.add(40);\n        treeSet.add(50);\n        treeSet.add(22);\n\n        // Check empty or not\n        if (treeSet.isEmpty()) {\n            System.out.print(\"TreeSet is empty.\");\n        } else {\n            System.out.println(\"TreeSet size: \" + treeSet.size());\n        }\n\n        // Looping and Displaying the Tree set data using Iterator\n        Iterator\u003cInteger\u003e iterator = treeSet.iterator();\n        while (iterator.hasNext()) {\n            System.out.print(iterator.next() + \"\\t\");\n        }\n\n        // Retrieve first data from tree set\n        System.out.println(\"\\nFirst Element: \" + treeSet.first());\n\n        // Retrieve last data from tree set\n        System.out.println(\"Last Element: \" + treeSet.last());\n\n        // remove element by value\n        boolean flag = treeSet.remove(40);\n        if (flag) {\n            System.out.println(\"40 is removed!\");\n        } else {\n            System.out.println(\"40 doesn't exist!\");\n        }\n\n        System.out.println(\"New size after delete: \" + treeSet.size());\n\n        // Looping and Displaying the Tree set data using Iterator\n        iterator = treeSet.iterator();\n        while (iterator.hasNext()) {\n            System.out.print(iterator.next() + \"\\t\");\n        }\n\n        // Remove all data\n        treeSet.clear();\n        if (treeSet.isEmpty()) {\n            System.out.print(\"\\nTree Set is empty.\");\n        } else {\n            System.out.println(\"\\nTree Set size: \" + treeSet.size());\n        }\n    }\n}\n```\n\n### Output\n\n```text\nTreeSet size: 5\n20    22    30    40    50\nFirst Element: 20\nLast Element: 50\n40 is removed!\nNew size after delete: 4\n20    22    30    50\nTree Set is empty.\n```\n"])</script>
1<script>self.__next_f.push([1,"128:Tda4,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we will create an example to customize `ActionBar` with a custom layout in Android. Before we begin, I assume you already have created an Android application.\n\n\\[box style=”2″\\]\n\nToolbar is a new standard replacement for ActionBar, introduced in Android Lollipop. It supports whole bunch of customization as you wish along with no or less modification to ActionBar logic.  \n\\[/box\\] I recommend using ToolBar. [Checkout our Android Lollipop ToolBar Example](http://stacktips.com/android/android-lollipop-toolbar-example \"Android Lollipop Toolbar Example\").\n\nNow let us create a custom layout xml file for your ActionBar.\n\n#### custom\\_actionbar.xml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"50dp\"\n    android:background=\"@drawable/black_pattern\" \u003e\n\n    \u003cTextView\n        android:id=\"@+id/title_text\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerInParent=\"true\"\n        android:textAllCaps=\"true\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:textColor=\"#fff\"\n        android:textStyle=\"bold\" /\u003e\n\n    \u003cImageView\n        android:id=\"@+id/imageView1\"\n        android:layout_width=\"35dp\"\n        android:layout_height=\"35dp\"\n        android:layout_alignParentLeft=\"true\"\n        android:layout_centerVertical=\"true\"\n        android:layout_marginLeft=\"8dp\"\n        android:src=\"@drawable/ic_launcher\" /\u003e\n\n    \u003cImageButton\n        android:id=\"@+id/imageButton\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentRight=\"true\"\n        android:layout_centerVertical=\"true\"\n        android:layout_marginRight=\"8dp\"\n        android:background=\"@null\"\n        android:src=\"@android:drawable/ic_menu_rotate\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n### Activity Class (MainActivity.java)\n\nThe above declared layout will be used as custom layout for Activity `ActionBar`. You can inflate custom view to ActionBar `setCustomView()` method. Let us have a look at the code snippet below.\n\n```java\npublic class MainActivity extends Activity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        ActionBar mActionBar = getActionBar();\n        mActionBar.setDisplayShowHomeEnabled(false);\n        mActionBar.setDisplayShowTitleEnabled(false);\n        LayoutInflater mInflater = LayoutInflater.from(this);\n\n        View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);\n        TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text);\n        mTitleTextView.setText(\"My Own Title\");\n\n        ImageButton imageButton = (ImageButton) mCustomView\n                .findViewById(R.id.imageButton);\n        imageButton.setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View view) {\n                Toast.makeText(getApplicationContext(), \"Refresh Clicked!\",\n                        Toast.LENGTH_LONG).show();\n            }\n        });\n\n        mActionBar.setCustomView(mCustomView);\n        mActionBar.setDisplayShowCustomEnabled(true);\n    }\n\n}\n```\n\n### Output\n\n[![ActionBar Custom View Example in Android](/media/articles/345/custom-actionbar.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"129:T10eb,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial show you how to use EditText user interface widget in android and write validation for the inputs. In this example we will create an simple Signup form as attached in the screenshot below.\n\nEditText widget in android allows us to enter data in UI like html web forms. It is an extends TextView and additional attributes that allows user to input values. It provides wide variety of input controls that enable select, cut, copy, paste of text into EditText.\n\n### Android Layout XML file\n\nLet us create an layout xml file with two EditText field one for entering email-id and other for password.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:background=\"#F0F0F0\"\n    android:orientation=\"vertical\" \u003e\n\n    \u003cTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:padding=\"10dp\"\n        android:text=\"@string/lbl_register\"\n        android:textAllCaps=\"true\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:textColor=\"#176CEC\"\n        android:textStyle=\"bold\" /\u003e\n\n    \u003cEditText\n        android:id=\"@+id/editText_email\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:background=\"#fff\"\n        android:ems=\"10\"\n        android:hint=\"@string/lbl_email_hint\"\n        android:inputType=\"textEmailAddress\"\n        android:padding=\"12dp\" /\u003e\n\n    \u003cEditText\n        android:id=\"@+id/editText_password\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginTop=\"1dp\"\n        android:background=\"#fff\"\n        android:ems=\"10\"\n        android:hint=\"@string/lbl_password_hint\"\n        android:inputType=\"textPassword\"\n        android:padding=\"12dp\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/btn_signup\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"20dp\"\n        android:background=\"#176CEC\"\n        android:text=\"@string/lbl_btn_signup\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:textColor=\"#fff\"\n        android:textStyle=\"bold\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n### Android Layout XML file.\n\n```java\npackage com.javatechig;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.EditText;\n\npublic class MainActivity extends Activity {\n    private EditText emailEditText;\n    private EditText passEditText;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        emailEditText = (EditText) findViewById(R.id.editText_email);\n        passEditText = (EditText) findViewById(R.id.editText_password);\n\n        findViewById(R.id.btn_signup).setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View arg0) {\n\n                final String email = emailE
1ditText.getText().toString();\n                if (!isValidEmail(email)) {\n                    emailEditText.setError(\"Invalid Email\");\n                }\n\n                final String pass = passEditText.getText().toString();\n                if (!isValidPassword(pass)) {\n                    passEditText.setError(\"Invalid Password\");\n                }\n\n            }\n        });\n    }\n\n    // validating email id\n    private boolean isValidEmail(String email) {\n        String EMAIL_PATTERN = \"^[_A-Za-z0-9-\\+]+(.[_A-Za-z0-9-]+)*@\"\n                + \"[A-Za-z0-9-]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$\";\n\n        Pattern pattern = Pattern.compile(EMAIL_PATTERN);\n        Matcher matcher = pattern.matcher(email);\n        return matcher.matches();\n    }\n\n    // validating password with retype password\n    private boolean isValidPassword(String pass) {\n        if (pass != null \u0026\u0026 pass.length() \u003e 6) {\n            return true;\n        }\n        return false;\n    }\n}\n```\n\n### Output\n\n[![Validate EditText in Android ](/media/articles/346/Untitled.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"12a:T5f3,"])</script>
1<script>self.__next_f.push([1,"\nIn this post we will see how to convert unix date to human readable format, how to use SimpleDateFormat class for date conversion.\n\n-   `System.currentTimeMillis()` will give date/time as a single numeric value, expressed as the number of milliseconds after the UNIX epoch. Unix epoch is always an long value. You can convert this time to get your time as per your local time zone.\n-   You can use util.Date class object to get the date. Using this you can extract the year, month and day value numerically.\n-   `Calendar.getInstance()` gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. You can overload the time zone and locale to get specific time zone time.\n-   `SimpleDateFormat` class is used for parsing and formatting date as text string. We just have to specify the pattern for parsing.\n\n# How to get current date\n\n```java\nDateFormat dateFormat = new SimpleDateFormat(\"EEE, d MMM yyyy HH:mm:ss\");\n//getting current date using util.Date class\nDate date = new Date();\nSystem.out.println(\"Current Date:\" + dateFormat.format(date));\n\n//or use calendar instance\n//Calendar cal = Calendar.getInstance();\n//return dateFormat.format(cal.getTime());\n```\n\n# Convert UNIX date to String\n\n```java\nlong unixdate = 1389705117;\nDateFormat formatter = new SimpleDateFormat(\"EEE, d MMM yyyy HH:mm:ss\");\nCalendar calendar = Calendar.getInstance();\ncalendar.setTimeInMillis(unixdate * 1000);\nSystem.out.println(\"Formatted Date:\" + formatter.format(calendar.getTime()));\n```\n"])</script>
1<script>self.__next_f.push([1,"12b:T1355,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains the basic building blocks of Xamarin.Android application.\n\n# 1. Activity\n\nUnlike other platform applications, Android application doesn’t have a single entry point “Main” method. Android application is composed of loosely coupled screens called activity. Android supports multi screen applications. Since each Activity is essentially decoupled from the others, there needs to be a way to launch them and optionally pass data to them. On Android this is accomplished using Intents. Intents are classes that describe a message: both what the desired action of the message is and a data payload to send along with it.\n\n![components of a basic Android application](/media/articles/348/components-of-a-basic-Android-application.png)\n\nAs mentioned, Activities are classes that provide an interface. An Activity is given a window in which to add User Interface to. Therefore, creating multi-screen applications involves creating multiple Activities and transitioning between them.\n\nThe Activity class inherits from the abstract Context class. Context is the closest Android gets to a reference to the current application and provides a mechanism for accessing the Android system. A Context is needed to perform many operations in Android such as:\n\n-   Start, stop android services\n-   Accessing shared preferences\n-   Creating views and custom views\n-   While accessing resources\n\nAn Android application needs a Context to know what permissions the application has, how to create controls, accessing preferences, etc. Therefore, each Activity and Service inherits from Context, which has all the information the application needs. Every time a new Activity is created, it’s passed a Context from the Activity that created it.\n\n### Activity Lifecycle\n\nActivity has a life-cycle method that helps you to identify and perform operations depending on the livfecycle states. Activities can be paused or destroyed by the system at any time. The lifecycle provides a way for Activities to handle the various lifecycle methods that Android will call and gives them an opportunity to save or rehydrate state, so screens can continue to operate normally.\n\n[![activity lifecycle](/media/articles/348/activity-lifecycle-300x376.jpg)](http://stacktips.com)\n\n# 2. Intent\n\nIntent is a messaging object you can use to request an action from another app component. Although intents facilitate communication between activities or activity with service. An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.\n\nAdditionally, Intents can be used to tell the OS to launch external Activities as well. For example, an application can have the intention to dial a phone number when the user taps a button. The way an application announces this intention is via an Intent for a phone dialing action. However, the actual dialing of the number is handled by an Activity in the Phone Dialer Application.\n\n# 3. AndroidManifest.xml\n\nEvery Android application needs to include a file called AndroidManifest.xml. This file contains information about the application such as:\n\n-   Application name, icon, version, version code, etc.\n-   Registration of Activities, Intents and services\n-   Listing all permissions needed for your application\n-   OS Version Compatibility – The minimum and max Android API level the application supports.\n\n# 4. Services\n\nServices are application components that run in the background to perform long-running operations with no direct access to user interface. A typical long running tasks can be periodic downloading of data from internet, persisting multiple records into database, perform file I/O, fetching phone contacts list, etc. Such long running tasks can be implemented using Service, to provide smooth user experience by letting user interact with other activities while long running jobs being processed in background.\n\n# 5. Content providers\n\nContent providers manage access to a central repository of data such as contacts. A content provider is a part of an application, which usually provides a user interface to manage its data. A standard interface is also provided, which allows other applications to access its repository.\n\n# 6. Broadcast receivers\n\nBroadcast receivers are components that perform some type of processing in response to system-wide broadcasts. Broadcasts are generally initiated by the system for events such as low battery, taking a picture, or turning on Bluetooth. Applications may also choose to send broadcasts; a content provider might send a broadcast when data, such as a contact, has been updated. While broadcast receivers do not have a user interface, they may indirectly cause updates to a status.\n"])</script>
1<script>self.__next_f.push([1,"12c:T116d,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains step by step approach to create and deploy a Xamarin.Android application. For the sake of simplicity our first ever Xamarin.Android application, will have very basic user interface.\n\n## 1. Creating a Xamarin.Android Application\n\nThis example assumes you already have Xamarin.Android installed in your development system. If you are a windows user you can use Visual Studio 2010 Professional or MonoDev IDE for development.\n\nLet us create a new Xamarin.Android solution. Xamarin.Android includes several project templates, including:\n\n1.  Android Library Project – A reusable .NET library project for Android.\n2.  Android Application – A basic starter project with a single activity.\n3.  Android OpenGL Application – An OpenGL starter project.\n\nWe will use “Android Application template” for this example. Let’s create an application by doing the following:\n\n[![Xamrin Android Application](/media/articles/349/Xamrin-Android-Application-620x379.png)](http://stacktips.com)\n\n## 2. Understanding Application Components\n\nIn the above section, we have just created a simple Xamarin.Android project. It automatically generates a project structure with different files and folders. The “HelloWorld” project includes three folders named Assets, Properties, and Resources.\n\n-   Assets – Contains any type of file the application needs included in its package. Files included here are accessible at runtime via the Assets class.\n-   Properties – Contains 
1normal .NET assembly metadata.\n-   Resources – Contains application resources such as strings and images, as well as declarative XML user interface definitions. These resources are accessible through the generated Resource class.\n\n[![Xamrin Android Application Example](/media/articles/349/Xamrin-Android-Application-Example-300x308.png)](http://stacktips.com)  \nThe project template also created a class called HelloWorld in the file MainActivity.cs. An Activity is a class that models a destination where a user can perform some action while using an app, typically via a user interface.\n\n## 3. Creating HelloWorld program\n\nIn this example we will create a simple screen with a TextView and a Button. Clicking the button will show a toast message to user.\n\n#### Main.axml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:orientation=\"vertical\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:background=\"#ffe7e5e5\"\u003e\n    \u003cTextView\n        android:text=\"HelloWorld Example in Xamrin\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:id=\"@+id/textView1\"\n        android:gravity=\"center_horizontal\"\n        android:layout_margin=\"10dp\"\n        android:textColor=\"#ff130c0c\" /\u003e\n    \u003cButton\n        android:id=\"@+id/myButton\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"@string/hello\"\n        android:capitalize=\"characters\"\n        android:layout_margin=\"10dp\"\n        android:background=\"#ff0f37f5\"\n        android:textColor=\"#ffffffff\"\n        android:textSize=\"18dp\"\n        android:textStyle=\"bold\"\n        android:typeface=\"sans\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\n#### MainActivity.cs\n\n```cs\nusing System;\nusing Android.App;\nusing Android.Content;\nusing Android.Runtime;\nusing Android.Views;\nusing Android.Widget;\nusing Android.OS;\n\nnamespace HelloWorld\n{\n    [Activity (Label = \"HelloWorld!\", MainLauncher = true)]\n    public class MainActivity : Activity\n    {\n        protected override void OnCreate (Bundle bundle)\n        {\n            base.OnCreate (bundle);\n\n            // Set your view layout layout resource file\n            SetContentView (Resource.Layout.Main);\n\n            // Initilize button from the layout resource\n            Button button = FindViewById\u003cButton\u003e (Resource.Id.myButton);\n\n            // and attach an event to it\n            button.Click += delegate {\n                //display toast message\n                Toast.MakeText (Application, \"Button Clicked!\", ToastLength.Short).Show ();\n            };\n        }\n    }\n}\n```\n\n## 4. Output\n\nHere is a screenshot that shows the application running in Samsung S4.\n\n[![HelloWorld program in Xamarin](/media/articles/349/framed_Screenshot_2014-02-21-08-33-10.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"12d:T1304,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial we show you how to create input dialog in android with code sample.\n\nA dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed. The Dialog class is the base class for dialogs.\n\nCreating a input dialog in android involves below steps\n\n1.  Create layout for input dialog\n2.  Inflating layout and initialize AlertDialog\n\n## Creating Input Dialog Layout\n\nHere in this example we are creating an simple layout with an TextView and EditText. You may like to add your own layout with different UI widgets you need with your custom styles.\n\n### Activity layout (activity\\_main.xml)\n\nHere we are creating an sample layout for activity. This has just an button, clicking on the button we will show the input dialog.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    android:padding=\"@dimen/activity_vertical_margin\" \u003e\n\n    \u003cButton\n        android:id=\"@+id/button\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Show Input Dialog\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/result\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n### Input dialog layout (input\\_dialog.xml)\n\nInput dialog layout is composed of a TextView to hint user what to enter, and a EditText to enter values.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:orientation=\"vertical\"\n    android:padding=\"10dp\"\u003e\n\n    \u003cTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:textAppearance=\"?android:attr/textAppearanceMedium\"\n        android:text=\"Enter Name\"\n        android:id=\"@+id/textView\" /\u003e\n\n    \u003cEditText\n        android:id=\"@+id/edittext\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:hint=\"Enter text here..\"\n        android:padding=\"10dp\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\n### Activity Class\n\nHere in this class we are instating the activity\\_main.xml layout. A click event is given for the Button, when clicked it shows the input dialog.\n\n```java\npackage com.javatechig;\n\nimport android.app.Activity;\nimport android.app.AlertDialog;\nimport android.content.DialogInterface;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends Activity {\n\n    private Button button;\n    private TextView resultText;\n\n    public void onCreate(Bundle savedInstanceState) {\n\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        // components from main.xml\n        button = (Button) findViewById(R.id.button);\n        resultText = (TextView) findViewById(R.id.result);\n\n        button.setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View view) {\n                showInputDialog();\n            }\n        });\n    }\n\n    protected void showInputDialog() {\n\n        // get prompts.xml view\n        LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);\n        View promptView = layoutInflater.inflate(R.layout.input_dialog, null);\n        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);\n        alertDialogBuilder.setView(promptView);\n\n        final EditText editText = (EditText) promptView.findViewById(R.id.edittext);\n        // setup a dialog window\n        alertDialogBuilder.setCancelable(false)\n                .setPositiveButton(\"OK\", new DialogInterface.OnClickListener() {\n                    public void onClick(DialogInterface dialog, int id) {\n                        resultText.setText(\"Hello, \" + editText.getText());\n                    }\n                })\n                .setNegativeButton(\"Cancel\",\n                        new DialogInterface.OnClickListener() {\n                            public void onClick(DialogInterface dialog, int id) {\n                                dialog.cancel();\n                            }\n                        });\n\n        // create an alert dialog\n        AlertDialog alert = alertDialogBuilder.create();\n        alert.show();\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"12e:Tfa6,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we show you how to use check box in android with example.\n\nCheckbox is a two-states button that can be either checked or unchecked. When the radio button is unchecked, the user can click it to check it or vice-versa. Unlike [RadioButton](http://stacktips.com/android/android-radio-button-example \"Android Radio Button Example\"), android check box works like toggle between two states.\n\n# Android CheckBox Example\n\nLet us create a example that displays three checkbox and responds to user click event. When user selects or un-select the button, it displays a toast with its state. Create a new layout file named activity\\_main.xml under layout resource folder and add the following code snippets. The code will generate the layout as shown in the screenshot below.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    android:padding=\"@dimen/activity_vertical_margin\"\u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView1\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"@string/hint\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n    \u003cCheckBox\n        android:id=\"@+id/music\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"@string/music\" /\u003e\n\n    \u003cCheckBox\n        android:id=\"@+id/game\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:checked=\"true\"\n        android:text=\"@string/game\" /\u003e\n\n    \u003cCheckBox\n        android:id=\"@+id/blogging\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"@string/blogging\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n[![Android CheckBox Example](/media/articles/351/Android-CheckBox-Example.png)](http://stacktips.com)\n\nIn the above layout class, we are using below strings\n\n```xml\n\u003cresources\u003e\n    \u003cstring name=\"app_name\"\u003eMy Application\u003c/string\u003e\n    \u003cstring name=\"blogging\"\u003eWrite Blog\u003c/string\u003e\n    \u003cstring name=\"music\"\u003eListen Music\u003c/string\u003e\n    \u003cstring name=\"game\"\u003ePlay Games\u003c/string\u003e\n    \u003cstring name=\"submit\"\u003eSubmit\u003c/string\u003e\n    \u003cstring name=\"hint\"\u003eWhat do you like do in your free time?\u003c/string\u003e\n\u003c/string\u003e\n\u003c/resources\u003e\n```\n\n# Using CheckBox from Activity\n\n```java\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.CheckBox;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity {\n    private CheckBox blogging, game, music;\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        blogging = (CheckBox) findViewById(R.id.blogging);\n        game = (CheckBox) findViewById(R.id.game);\n        music = (CheckBox) findViewById(R.id.music);\n        music.setOnClickListener(checkboxClickListener);\n        game.setOnClickListener(checkboxClickListener);\n        blogging.setOnClickListener(checkboxClickListener);\n\n        /* Set blogging by default */\n        blogging.setChecked(true);\n\n    }\n\n    View.OnClickListener checkboxClickListener = new View.OnClickListener() {\n        @Override\n        public void onClick(View view) {\n            boolean checked = ((CheckBox) view).isChecked();\n            if (checked) {\n                String text = null;\n                switch (view.getId()){\n                    case R.id.game:\n                        text = \"Play Game\";\n                        break;\n                    case R.id.music:\n                        text = \"Listen Music\";\n                        break;\n                    case R.id.blogging:\n                        text=\"Write blog\";\n                        break;\n                }\n                Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();\n            }\n        }\n    };\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"12f:Tf95,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial we show you how to create custom dialog in android with code sample.\n\nA dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed. The Dialog class is the base class for dialogs.\n\nCreating a custom dialog in android involves below steps\n\n1.  Crating a custom layout for dialog\n2.  Attaching layout to dialog instance\n3.  Show/Hide dialog\n\n# Crating a custom layout for dialog\n\nHere in this example we are creating an simple layout with an ImgeView, TextView and a Button. You may like to add your own layout with different UI widgets you need with your custom styles.\n\n**custom\\_dialog\\_layout.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\" \u003e\n\n    \u003cImageView\n        android:id=\"@+id/image\"\n        android:layout_width=\"50dp\"\n        android:layout_height=\"50dp\"\n        android:contentDescription=\"@drawable/ic_launcher\"\n        android:src=\"@drawable/ic_launcher\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/button\"\n        android:layout_width=\"100dp\"\n        android:layout_height=\"wrap_content\"\n        android:layout_below=\"@+id/image\"\n        android:layout_centerHorizontal=\"true\"\n        android:text=\"Dismiss\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"fill_parent\"\n        android:layout_above=\"@+id/button\"\n        android:layout_toRightOf=\"@+id/image\"\n        android:gravity=\"center_vertical\"\n        android:textAppearance=\"?android:attr/textAppearanceMedium\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n# Attaching layout to dialog instance\n\nNow, let us go back to our activity and create an instance of Dialog. We can attach our custom layout to dialog by using setContentView() method call.\n\n```java\npackage com.javatechig;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.TextView;\n\npublic class MainActivity extends Activity {\n    private Button button;\n\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        button = (Button) findViewById(R.id.button);\n        button.setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View view) {\n                final Dialog dialog = new Dialog(MainActivity.this);\n\n                //setting custom layout to dialog\n                dialog.setContentView(R.layout.cusotm_dialog_layout);\n                dialog.setTitle(\"Custom Dialog\");\n\n                //adding text dynamically\n                TextView txt = (TextView) dialog.findViewById(R.id.textView);\n                txt.setText(\"Put your dialog text here.\");\n\n                ImageView image = (ImageView)dialog.findViewById(R.id.image);\n                image.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_dialog_info));\n\n                //adding button click event\n                Button dismissButton = (Button) dialog.findViewById(R.id.button);\n                dismissButton.setOnClickListener(new OnClickListener() {\n                    @Override\n                    public void onClick(View v) {\n                        dialog.dismiss();\n                    }\n                });\n                dialog.show();\n            }\n        });\n    }\n}\n```\n\n# Show/Hide dialog\n\nWhen you want to show your dialog, just call show() method and to hide you have to call dismiss() method.\n\n# Output\n\n[
1![Custom Dialog in Android](/media/articles/352/Custom-Dialog-in-Android-300x437.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"130:Tdff,"])</script>
1<script>self.__next_f.push([1,"\nAndroid is enriched with some of the best User interface design widgets. That allows you to build robust and good looking ui based application. ImageView is one of the UI widget that is used to display images in your Application.\n\nImageView is comes with different configuration options to support different scaleTypes. scaleType options are used for scaling the bounds of an image to the bounds of this view. Below are the listed `scaleType` configuration properties supported.\n\n-   CENTER\n-   CENTER\\_CROP\n-   CENTER\\_INSIDE\n-   FIT\\_CENTER\n-   FIT\\_END\n-   FIT\\_START\n-   FIT\\_XY\n-   MATRIX\n\n## Android ImageView Example\n\nLet us add a new activity layout file named activity\\_main.xml to your project res/layout folder. In this example, we will be creating three different ImageView for demonstration purpose.\n\nNote that the ImageView uses the images from drawable folder.\n\n```xml\n\u003cScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:background=\"#31352e\" \u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:orientation=\"vertical\" \u003e\n\n        \u003cImageView\n            android:id=\"@+id/imageView1\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"150dp\"\n            android:layout_margin=\"5dp\"\n            android:src=\"@drawable/image1\" /\u003e\n\n        \u003cImageView\n            android:id=\"@+id/imageView2\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"150dp\"\n            android:layout_margin=\"5dp\"\n            android:background=\"#fff\"\n            android:padding=\"3dp\"\n            android:scaleType=\"fitXY\"\n            android:src=\"@drawable/image2\" /\u003e\n\n        \u003cImageView\n            android:id=\"@+id/imageView3\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"200dp\"\n            android:layout_margin=\"5dp\"\n            android:background=\"#fff\"\n            android:paddingBottom=\"50dp\"\n            android:paddingLeft=\"3dp\"\n            android:paddingRight=\"3dp\"\n            android:paddingTop=\"3dp\"\n            android:scaleType=\"fitXY\"\n            android:src=\"@drawable/image2\" /\u003e\n    \u003c/LinearLayout\u003e\n\n\u003c/ScrollView\u003e\n```\n\n## Using ImageView from Activity\n\nLet us look at the Activity java class. In this example, the second ImageView (i.e. imageView2) is loaded dynamically with an image from drawable folder using `setImageResource()` method. You can also listen to click event of the ImageView using `setOnClickListener().`\n\n```java\npackage com.javatechig.imageview;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.ImageView;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        // setting image resource from drawable\n        ImageView imageView = (ImageView) findViewById(R.id.imageView2);\n        imageView.setImageResource(R.drawable.image1);\n\n        imageView.setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View arg0) {\n                Toast.makeText(getApplicationContext(), \"Clicked Second Image\",\n                        Toast.LENGTH_SHORT).show();\n            }\n        });\n\n    }\n\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"131:T1bfd,"])</script>
1<script>self.__next_f.push([1,"\n# 1. Why Analytics in Mobile app ?\n\nAnalytics is one of the major parts in applications that drive revenue. Mobile App Analytics help you set and track the goal conversions you want most: purchases, clicks, or simply time spent on your app. It is required to make business inclined towards user’s interest. For example, if you developing an application for Mobile Shopper app, it is important to track the below things.\n\n1.  Number of users/active users from across the world\n2.  Most viewed products, categories, brands, etc.\n3.  Number of users placing request, etc.\n\nThe above information is required in order to improve the product and make the service is better.\n\n# 2. Introduction to Google Analytics\n\nThe Google Analytics Platform lets you measure user interactions with your business across various devices and environments. The platform provides all the computing resources to collect, store, process, and report on these user-interactions.\n\n# 3. Supported Features\n\nBelow are the currently supported features. Read more\n\n**[http://www.google.co.in/analytics/mobile/](http://www.google.co.in/analytics/mobile/)**\n\n1.  Google Play Integration\n2.  Crash and Exception Reporting\n3.  Custom Reports\n4.  Event Tracking\n5.  Flow Visualization\n6.  Real-Time Reporting\n\n# 4. How to use Google Analytics in android\n\nThis section of tutorial we will see detailed steps to install Google Analytics for your android application. Before begin with Analytics integration we need the following items\n\n1.  Android developer SDK and required configurations. I assume you have it already, if not you can follow Android official documentation **[http://developer.android.com/sdk/index.html](http://developer.android.com/sdk/index.html)**\n2.  Google Analytics SDK for Android v3, with `libGoogleAnalyticsServices.jar` file. Copy this file in your project’s /libs directory.\n3.  Codebase of an Android app that you like to implement the Google Analytics\n4.  Create a Google Analytics account (Requires Gmail), and then create a new app property and view in the Analytics console.\n\n# 5. Using Google Analytics Detailed Steps\n\nBefore starting with section, I assume you already have Codebase of an Android app that you like to implement the Google Analytics. But to simplify my example, I am creating an simple Android App and integrating with Google Analytics.\n\n## 5.1. Creating Google Analytics Account and App Property\n\n1.  Login to your Google Analytics Account. Then press “Admin” button on the right side of your screen.\n2.  Create a new Account, if you don’t have one and then create a new property. While creating a new property choose Mobile App.\n3.  After property is created, you will get the `tracking Id`. This tracking id will be used as configuration in android app.\n\n## 5.2. Add analytics.xml configuration file\n\nAdd `analytics.xml` configuration file in your application values folder\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cresources\u003e\n\n    \u003c!-- Replace placeholder ID with your tracking ID --\u003e\n    \u003cstring name=\"ga_trackingId\"\u003eUA-xxxxxxxxxx\u003c/string\u003e\n\n    \u003c!-- Enable automatic activity tracking --\u003e\n    \u003cbool name=\"ga_autoActivityTracking\"\u003etrue\u003c/bool\u003e\n\n    \u003c!-- Enable automatic exception tracking --\u003e\n    \u003cbool name=\"ga_reportUncaughtExceptions\"\u003etrue\u003c/bool\u003e\n\n\u003c/resources\u003e\n```\n\n## 5.3. Android Activity Layout (activity\\_main.xml)\n\nFor this example, I have created an sample Activity with two buttons for tracking event and exceptions.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    android:padding=\"@dimen/activity_vertical_margin\"\n    tools:context=\".MainActivity\" \u003e\n\n    \u003cTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"@string/info\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/trackEvent\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Track Event\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/trackCrash\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Track Crash\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n## 5.4. Android Activity (MainActivity.java)\n\nNow, you need to write the tracking code in your activity class. For that simply add the `activiyStart()` and `activityStop()` methods to the `onStart()` and `onStop()` methods of each of your Activities as in the following example. This two method enables basic activity tracking.\n\n```java\npackage com.javatechig.ganalytics;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport com.google.analytics.tracking.android.EasyTracker;\nimport com.google.analytics.tracking.android.MapBuilder;\nimport com.google.analytics.tracking.android.StandardExceptionParser;\n\npublic class MainActivity extends Activity {\n\n    private EasyTracker easyTracker = null;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        easyTracker = EasyTracker.getInstance(MainActivity.this);\n\n        findViewById(R.id.trackEvent).setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View view) {\n                easyTracker.send(MapBuilder.createEvent(\"your_action\",\n                        \"envet_name\", \"button_name/id\", null).build());\n            }\n        });\n\n        findViewById(R.id.trackCrash).setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View view) {\n\n                try {\n                    int a[] = new int[2];\n                    int num = a[4];\n                } catch (ArrayIndexOutOfBoundsException e) {\n                    easyTracker.send(MapBuilder.createException(\n                                    new StandardExceptionParser(MainActivity.this, null)\n                                            .getDescription(Thread.currentThread().getName(), e), false).build());\n                }\n\n            }\n        });\n    }\n\n    @Override\n    public void onStart() {\n        super.onStart();\n        EasyTracker.getInstance(this).activityStart(this);\n    }\n\n    @Override\n    public void onStop() {\n        super.onStop();\n        EasyTracker.getInstance(this).activityStop(this);\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        getMenuInflater().inflate(R.menu.main, menu);\n        return true;\n    }\n\n}\n```\n\nIn this above activity code sample, we are tracking event an crashes on two button clicks. Just for demonstation purpose I am creating sample exception and tracking it.\n\n# 6. Google Analytics Output\n\n[
1![Google Analytics Report](/media/articles/356/Google-Analytics-Report-940x623.png)](http://stacktips.com)\n\n# 7. Download Complete Example\n\n[Download source](https://github.com/javatechig/javatechig-android-advanced/tree/master/GoogleAnalyticsDemo)\n"])</script>
1<script>self.__next_f.push([1,"132:T14fb,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we will see how to use Handler in android. This example downloads image from server and using Handler it is communicating back with UI thread.\n\nA Handler allows you communicate back with the UI thread from other background thread. This is useful in android as android doesn’t allow other threads to communicate directly with UI thread. Handler can send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When a new Handler is created, it is bound to the thread/message queue of the thread that is creating it.\n\nThe example explained in this tutorial is using below configurations\n\n-   JDK 1.6\n-   Eclipse 4.2 Juno\n-   Android SKD 4.0\n-   And tested over HTC OneX (Android 4.2)\n\n#### Android Activity Layout (activity\\_main.xml)\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    tools:context=\".MainActivity\" \u003e\n\n    \u003cButton\n        android:id=\"@+id/button1\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"15dp\"\n        android:text=\"Download Image\" /\u003e\n\n    \u003cImageView\n        android:id=\"@+id/imageView\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\n        android:scaleType=\"centerInside\"\n        android:src=\"@drawable/ic_launcher\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n#### Android Activity (MainActivity.java)\n\n```java\npackage com.javatechig.handlerexample;\nimport java.io.InputStream;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.HttpStatus;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport com.javatechige.handlerexample.R;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.ImageView;\npublic class MainActivity extends Activity {\n    private ProgressDialog progressDialog;\n    private ImageView imageView;\n    private String url = \"http://www.9ori.com/store/media/images/8ab579a656.jpg\";\n    private Bitmap bitmap = null;\n\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        imageView = (ImageView) findViewById(R.id.imageView);\n\n        Button start = (Button) findViewById(R.id.button1);\n        start.setOnClickListener(new OnClickListener() {\n            @Override\n            public void onClick(View arg0) {\n                progressDialog = ProgressDialog.show(MainActivity.this, \"\", \"Loading..\");\n                new Thread() {\n                    public void run() {\n                        bitmap = downloadBitmap(url);\n                        messageHandler.sendEmptyMessage(0);\n                    }\n                }.start();\n            }\n        });\n    }\n\n    private Handler messageHandler = new Handler() {\n        public void handleMessage(Message msg) {\n            super.handleMessage(msg);\n            imageView.setImageBitmap(bitmap);\n                progressDialog.dismiss();\n        }\n    };\n\n    private Bitmap downloadBitmap(String url) {\n        // Initialize the default HTTP client object\n        final DefaultHttpClient client = new DefaultHttpClient();\n\n        //forming a HttpGet request\n        final HttpGet getRequest = new HttpGet(url);\n        try {\n            HttpResponse response = client.execute(getRequest);\n            //check 200 OK for success\n            final int statusCode = response.getStatusLine().getStatusCode();\n            if (statusCode != HttpStatus.SC_OK) {\n                Log.w(\"ImageDownloader\", \"Error \" + statusCode + \" while retrieving bitmap from \" + url);\n                return null;\n            }\n\n            final HttpEntity entity = response.getEntity();\n            if (entity != null) {\n                InputStream inputStream = null;\n                try {\n                    // getting contents from the stream\n                    inputStream = entity.getContent();\n                    // decoding stream data back into image Bitmap\n                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);\n                    return bitmap;\n                } finally {\n                    if (inputStream != null) {\n                        inputStream.close();\n                    }\n                    entity.consumeContent();\n                }\n            }\n        } catch (Exception e) {\n            getRequest.abort();\n            Log.e(getString(R.string.app_name), \"Error \"+ e.toString());\n        }\n        return null;\n    }\n}
1\n```\n\n#### Output\n\n[![Android Handler Example](/media/articles/357/Android-Handler-Example.gif)](http://stacktips.com)\n\n#### Download Complete Source\n\nDownload complete source code from [GitHub](https://github.com/javatechig/javatechig-android-advanced/tree/master/HandlerExample)\n"])</script>
1<script>self.__next_f.push([1,"133:T678,"])</script>
1<script>self.__next_f.push([1,"\nThis example explains how to get device unique id in android. The device unique id is needed when we want user registration for a specific device. This way we can achieve security. Most of the banking applications today are using such approach.\n\n#### Android Activity Layout (activity\\_main.xml)\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    tools:context=\".MainActivity\" \u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView1\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerInParent=\"true\"\n        android:textColor=\"#cc0000\"\n        android:textSize=\"32sp\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n#### Android Activity (MainActivity.java)\n\n```java\npackage com.javatechig.getdeviceid;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.provider.Settings.Secure;\nimport android.widget.TextView;\n\npublic class MainActivity extends Activity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        //getting unique id for device\n        String id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);\n\n        //displaying id in textview\n        TextView tv = (TextView) findViewById(R.id.textView1);\n        tv.setText(id);\n\n    }\n\n}\n```\n\n#### Output\n\n#### [![Get Device ID Example in Android](/media/articles/358/Get-Device-ID-Example-in-Android-300x438.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"134:Tdda,"])</script>
1<script>self.__next_f.push([1,"\nHere in this example we will see how to list all files present in SDCard of your android device. In the below example it searches for all of the SDCard folders and lists all of the images available. You may extend this example to list other file formats.\n\n**Steps**\n\n1.  First let us create a new Android project and name it as you like. This example uses minSdkVersion=8 and targetSdkVersion=”18″ and tested over HTC Onex (Android 4.2) device.\n2.  Make sure, you have SDCard with some files to list.\n\n#### Android Activity Layout (activity\\_main.xml)\n\n```xml\n\u003cScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:id=\"@+id/scrollView\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\" \u003e\n\n    \u003cLinearLayout\n        android:id=\"@+id/view\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:orientation=\"vertical\"\n        android:padding=\"8dp\" \u003e\n    \u003c/LinearLayout\u003e\n\n\u003c/ScrollView\u003e\n```\n\nFrom the above code snippet, you can observe that I have taken a ScrollView and a LinearLayout as its child. This LinearLayout will hold all of the TextViews that shows filenames.\n\n#### Android Activity (MainActivity.java)\n\n```java\npackage com.javatechig.listallfiles;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport com.example.listallfiles.R;\nimport android.app.Activity;\nimport android.graphics.Color;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\npublic class MainActivity extends Activity {\n\n    private File root;\n    private ArrayList\u003cFile\u003e fileList = new ArrayList\u003cFile\u003e();\n    private LinearLayout view;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        view = (LinearLayout) findViewById(R.id.view);\n\n        //getting SDcard root path\n        root = new File(Environment.getExternalStorageDirectory()\n                .getAbsolutePath());\n        getfile(root);\n\n        for (int i = 0; i \u003c fileList.size(); i++) {\n            TextView textView = new TextView(this);\n            textView.setText(fileList.get(i).getName());\n            textView.setPadding(5, 5, 5, 5);\n\n            System.out.println(fileList.get(i).getName());\n\n            if (fileList.get(i).isDirectory()) {\n                textView.setTextColor(Color.parseColor(\"#FF0000\"));\n            }\n            view.addView(textView);\n        }\n\n    }\n\n    public ArrayList\u003cFile\u003e getfile(File dir) {\n        File listFile[] = dir.listFiles();\n        if (listFile != null \u0026\u0026 listFile.length \u003e 0) {\n            for (int i = 0; i \u003c listFile.length; i++) {\n\n                if (listFile[i].isDirectory()) {\n                    fileList.add(listFile[i]);\n                    getfile(listFile[i]);\n\n                } else {\n                    if (listFile[i].getName().endsWith(\".png\")\n                            || listFile[i].getName().endsWith(\".jpg\")\n                            || listFile[i].getName().endsWith(\".jpeg\")\n                            || listFile[i].getName().endsWith(\".gif\"))\n\n                    {\n                        fileList.add(listFile[i]);\n                    }\n                }\n\n            }\n        }\n        return fileList;\n    }\n\n}\n```\n\n#### Output\n\n[![Example Listing All Files In Android](/media/articles/359/Example-Listing-All-Files-In-Android.gif)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"135:T2902,"])</script>
1<script>self.__next_f.push([1,"\n## 1. Introduction\n\nAndroid navigation drawer is a one of the most common used design pattern that displays the app’s main navigation links on the left side of the screen. It is not visible by default, and shown when swiped from left to right or by clicking the navigation menu icon from ActionBar.\n\nThe following example explains, how to implement a navigation drawer using Android Support Library `DrawerLayout` API.\n\n## 2. When to Use Navigation Drawer\n\nNavigation drawer is an overlay panel, that is replaced with the legacy application dashboard screen or menu. Now we don’t need to create a dedicated activity for showing all application options. You can simply it further by just using navigation drawer.\n\nBefore you decide to use a navigation drawer in your app, you should understand the use cases and design principles defined in the Navigation Drawer design guide. It is not an general replacement for top-level menu navigation.\n\nFollow official [Android on design guidelines](http://developer.android.com/design/patterns/navigation-drawer.html) follow for more information.\n\n## 3. Navigation Drawer Example\n\nThe following section of this tutorial, describes step by step approach to Implement a navigation drawer using the DrawerLayout APIs available in the Android Support Library. Some of the steps includes\n\n-   Create drawer layout\n-   Initialize navigation drawer layout\n-   Handle navigation drawer click\n-   Update content based on selection\n\n[![Navigation Drawer Android Example](/media/articles/360/Navigation-Drawer-Android-Example.png)](http://stacktips.com)\n\n## 4. Creating a Drawer Layout\n\nFor creating a navigation drawer, first we need to declare the drawer layout in your main activity where you want to show the navigation drawer. Add `android.support.v4.widget.DrawerLayout` as root view of activity layout.\n\nA DrawerLayout can have the layout for list to be shown inside navigation drawer and layout for main content view. In this example, the DrawerLayout contains two child views; one FrameLayout for main content, and a ListView for the navigation drawer. The FrameLayout is used to hold the child view’s populated by a Fragment at runtime.\n\n```xml\n\u003candroid.support.v4.widget.DrawerLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:id=\"@+id/drawer_layout\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\" \u003e\n\n    \u003c!-- The main content view --\u003e\n    \u003cFrameLayout\n        android:id=\"@+id/content_frame\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\" /\u003e\n\n    \u003c!-- The navigation drawer list--\u003e\n    \u003cListView\n        android:id=\"@+id/drawer_list\"\n        android:layout_width=\"240dp\"\n        android:layout_height=\"match_parent\"\n        android:layout_gravity=\"start\"\n        android:background=\"#111\"\n        android:choiceMode=\"singleChoice\"\n        android:divider=\"@android:color/transparent\"\n        android:dividerHeight=\"0dp\" /\u003e\n\u003c/android.support.v4.widget.DrawerLayout\u003e\n```\n\n#### Key Notes:\n\n-   The main content view is used as first child in the DrawerLayout. The XML order implies z-ordering and the drawer must be on top of the content.\n-   The main content view is set to match the parent view’s width and height, because it represents the entire UI when the navigation drawer is hidden.\n-   The width of drawer view is specified in dp (density independent pixels) units and the height matches the parent view. The drawer width should be no more than 320dp so the user can always see a portion of the main content.\n\n## 5. Initialize the Drawer List\n\nNow, first initialize the navigation drawer’s list of items. As here the navigation drawer consists a ListView, so the list can be populated by an Adapter.\n\n```java\nitems = getResources().getStringArray(R.array.menus);\n\n/* Getting reference to the DrawerLayout */\nmDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);\nmDrawerList = (ListView) findViewById(R.id.drawer_list);\n\n/* Creating an ArrayAdapter to add items to mDrawerList */\nArrayAdapter adapter = new ArrayAdapter(this,\n        R.layout.drawer_list_item, items);\n\n/* Setting the adapter to mDrawerList */\nmDrawerList.setAdapter(adapter);\n```\n\n## 6. Handle Navigation Click Events\n\nWhen the user selects an item in the drawer’s list, the system calls onItemClick() on the OnItemClickListener given to setOnItemClickListener(). In this example, selecting each item in the list inserts a different Fragment into the main content view FrameLayout.\n\n```java\n// Setting item click listener to mDrawerList\nmDrawerList.setOnItemClickListener(new OnItemClickListener() {\n    @Override\n    public void onItemClick(AdapterVie
1w\u003c?\u003e parent, View view, int position, long id) {\n        selectedPosition = position;\n        //Replace fragment content\n        updateFragment();\n        mDrawerLayout.closeDrawer(mDrawerList);\n     }\n});\n```\n\nNotice that in the above example we are using updateFragment() method that takes responsibility to update the content based on navigation drawer menu click. For the sake of simplicity, example loads the same WebView with different url. Add the following method to your activity.\n\n```java\npublic void updateFragment() {\n    FragmentManager fragmentManager = getFragmentManager();\n    WebViewFragment rFragment = new WebViewFragment();\n\n    // Passing selected item information to fragment\n    Bundle data = new Bundle();\n    data.putString(\"title\", items[selectedPosition]);\n    data.putString(\"url\", getUrl());\n    rFragment.setArguments(data);\n\n    //Replace fragment\n    FragmentTransaction ft = fragmentManager.beginTransaction();\n    ft.replace(R.id.content_frame, rFragment);\n    ft.commit();\n}\n```\n\n## 7. Handle Drawer Open and Close Events\n\nWe can also listen to the drawer open and close event. To listen for drawer open and close events, we can extend the ActionBarDrawerToggle class. The ActionBarDrawerToggle implements DrawerLayout.DrawerListener.\n\n```java\n/* Getting reference to the ActionBarDrawerToggle */\nmDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {\n    /* Called when drawer is closed */\n    public void onDrawerClosed(View view) {\n         //Put your code here\n    }\n\n  /* Called when a drawer is opened */\n  public void onDrawerOpened(View drawerView) {\n     //Put your code here\n  }\n};\n/* Setting DrawerToggle on DrawerLayout */\nmDrawerLayout.setDrawerListener(mDrawerToggle);\n```\n\n## 8. Download Complete Source\n\nDownload Source Code on [Github](https://github.com/javatechig/AndroidNavigationDrawer \"Download Navigation Drawer Example\")\n\n**MainActivity.java**\n\n```java\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.FragmentManager;\nimport android.app.FragmentTransaction;\nimport android.os.Bundle;\nimport android.support.v4.app.ActionBarDrawerToggle;\nimport android.support.v4.widget.DrawerLayout;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\n\npublic class MainActivity extends Activity {\n    private DrawerLayout mDrawerLayout;\n    private ListView mDrawerList;\n    private ActionBarDrawerToggle mDrawerToggle;\n    private String mTitle = \"Navigation Drawer\";\n    private String[] items;\n    private int selectedPosition;\n\n    @SuppressLint(\"NewApi\")\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        getActionBar().setTitle(mTitle);\n\n        items = getResources().getStringArray(R.array.menus);\n        // Getting reference to the DrawerLayout\n        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);\n        mDrawerList = (ListView) findViewById(R.id.drawer_list);\n\n        /* Creating an ArrayAdapter to add items to mDrawerList */\n        ArrayAdapter\u003cString\u003e adapter = new ArrayAdapter\u003cString\u003e(this, R.layout.drawer_list_item, items);\n        mDrawerList.setAdapter(adapter);\n        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,\n                R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {\n\n            /* Called when drawer is closed */\n            public void onDrawerClosed(View view) {\n                //Put your code here\n            }\n\n            /* Called when a drawer is opened */\n            public void onDrawerOpened(View drawerView) {\n                //Put your code here\n            }\n        };\n        mDrawerLayout.setDrawerListener(mDrawerToggle);\n\n        // Enabling Home button\n        getActionBar().setHomeButtonEnabled(true);\n        getActionBar().setDisplayHomeAsUpEnabled(true);\n\n        // Setting item click listener for the listview mDrawerList\n        mDrawerList.setOnItemClickListener(new OnItemClickListener() {\n            @Override\n            public void onItemClick(AdapterVie
1w\u003c?\u003e parent, View view, int position, long id) {\n                selectedPosition = position;\n\n                /* Replace fragment content */\n                updateFragment();\n\n               /* Closing the drawer */\n                mDrawerLayout.closeDrawer(mDrawerList);\n            }\n        });\n\n        /* Setting default fragment */\n        selectedPosition = 0;\n        updateFragment();\n    }\n\n    public void updateFragment() {\n        /* Getting reference to the FragmentManager */\n        FragmentManager fragmentManager = getFragmentManager();\n\n        /* Creating fragment instance */\n        WebViewFragment rFragment = new WebViewFragment();\n\n        /* Passing selected item information to fragment */\n        Bundle data = new Bundle();\n        data.putString(\"title\", items[selectedPosition]);\n        data.putString(\"url\", getUrl());\n        rFragment.setArguments(data);\n\n        /* Replace fragment */\n        FragmentTransaction ft = fragmentManager.beginTransaction();\n        ft.replace(R.id.content_frame, rFragment);\n        ft.commit();\n    }\n\n    protected String getUrl() {\n        StringBuffer url = new StringBuffer(\"http://stacktips.com\");\n        if (selectedPosition \u003e 0) {\n            url.append(\"/topics/\" + items[selectedPosition].toLowerCase());\n        }\n        return url.toString();\n    }\n\n    @Override\n    protected void onPostCreate(Bundle savedInstanceState) {\n        super.onPostCreate(savedInstanceState);\n        mDrawerToggle.syncState();\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"136:T1530,"])</script>
1<script>self.__next_f.push([1,"\nGone are the days when developers or programmers were solving all the programming issues on their own without using any tool. In today’s highly competitive software application development world, spending hours of time just to code everything right may not be a feasible solution for the developers, and that’s where the significance of IDE (Integrated Development Environment) comes into the picture, specifically when you’re developing applications using Groovy and Grails.\n\nIntegrated development environment (IDE) brings a whole host of features like auto complete, re-factoring source control and more for the developers. However, when it comes to Groovy and Grails, it becomes crucial for the developers to choose the right kind of IDE to improve the productivity on the go.\n\nWhile Groovy is written for the JVM and uses features and syntax of Java, Grails is built upon Hibernate and Spring. Most of the developers are using Eclipse for developing any kind of Java applications, but when it comes to the Grails, developers have to consider various plugins and IDEs to easily and effectively develop applications based on Groovy and Grails. So, which are the best IDEs that developers can use to build applications based on Groovy and Grails? Let’s find it out!\n\n## NetBeans\n\n[![netbeans-ide](/media/articles/372/Netbeans-IDE.png)](http://stacktips.com)NetBeans is a free and open source IDE which can be used for Groovy/Grails development. NetBeans 6.5 or above versions support Groovy/ Grails development. NetBeans comes with a Groovy editor with various integrated tools and offers features like code completion, providing name of dynamic methods for grails domain and controller class. It is light and offers great functional features.\n\nNetBeans is a free IDE tool, which brings tons of benefits for the developers. However, like any other tool or technology, it also has some drawbacks: it is too slow and many developers using it have experienced slow code completion.\n\nIf you have a tight budget and can’t afford a paid IDE, this is a best choice. Moreover, it has been integrated with multiple Grails actions. You can easily control the deployment status of your Grails application from the Service window, you can also run Grails generator, Grails commands and create Groovy Server Pages (GSPs) on the go.\n\n## Spring Tool Suite (STS)\n\n[![sts](/media/articles/372/STS.png)](http://stacktips.com)STS for Grails is an eclipse based IDE, which is free and offers out-of-the-box features; all this makes it highly popular among the developer community. Many developers are switching to STS from NetBeans because of better code completion support provided by it. STS is faster and improves developer’s productivity significantly.\n\nAlthough STS for Grails is not as feature rich as NetBeans, we can expect an improvement on this front as Grails is owned by Spring. If you’re looking for a strong alternative of NetBeans, then STS is without any doubt a great option for you!\n\n## IntelliJ\n\n[![intellijidea-spring](/media/articles/372/IntelliJIDEA-Spring.png)](http://stacktips.com)IntelliJ IDE is one of the most popular IDE tools for Grails Development. This amazing IDE comes in two forms: one is free IDEA Community Edition and other one is commercialized IDE known as IntelliJ IDEA Ultimate. There are many advantages of IntelliJ, which simplifies the development of your Groovy and Grails applications.\n\nIntelliJ offers many out-of-the-box features like code completion, on the fly code analysis, Groovy to Java converter, built-in Groovy Shell, integrations with different frameworks other than Grails, like Hibernate, Play and so on. Overall, it offers excellent support for Groovy and Grails. Moreover, it indexes files much faster than any other IDEs.\n\n## Groovy/Grails Tool Suite™ for Eclipse\n\n[![eclipse](/media/articles/372/eclipse.png)](http://stacktips.com)The Groovy/Grails Tool Suite is a complete Eclipse-based development environment optimized for developing, debugging and executing Groovy and Grails applications. A new perspective, new views and wizards ensure an intuitive and familiar Eclipse experience when working with the Groovy language and Grails framework. It provides support for the latest versions of Groovy and Grails, and comes on top of the latest Eclipse releases.\n\nIncluded with the Groovy/Grails Tool Suite is the developer edition of Pivotal tc Server, the drop-in replacement for Apache Tomcat. With its Spring Insight console, tc Server Developer Edition provides a graphical real-time view of application performance metrics that lets developers identify and diagnose problems from their desktops.\n\nThe Groovy/Grails Tool Suite supports application targeting to local, virtual and cloud-based servers. It is freely available for development and internal business operations use with no time limits, fully open-source and licensed under the terms of the Eclipse Public License.\n\n## Final Verdict\n\nThe above discussed IDEs can easily help you simplify your Groovy and [Grails application development](http://www.cygnet-infotech.com/java/grails-development). However, if you don’t have any price constraint, then IntelliJ is the best option. On the other hand, if you wish to go for a FREE IDE, then you may two options. If you choose NetBeans, you may get plenty of features, but you may have to compromise on speed that has been offered by STS for Grails.\n"])</script>
1<script>self.__next_f.push([1,"137:T674,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial will explain how to start an application while the Android device bootup. For this, we need to listen to the **BOOT\\_COMPLETED** action and react to it. The **BOOT\\_COMPLETED **is a Broadcast Action that is broadcast once after the system has finished booting. You can listen to this action by creating a `BroadcastReceiver` that then starts your launch Activity when it receives an intent with the BOOT\\_COMPLETED action.****\n\nHere's a step-by-step guide:\n\n## Add permission to your manifest\n\n```xml\n\u003cuses-permission android:name=\"android.permission.RECEIVE_BOOT_COMPLETED\" /\u003e\n```\n\n## Create a Custom `BroadcastReceiver`\n\nSecondly, create a custom `BroadcastReceiver` in your project to receive boot up event.\n\n```java\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\n\npublic class BootReceiver extends BroadcastReceiver{\n\n    @Override\n    public void onReceive(Context context, Intent intent) {\n        Intent i = new Intent(context, MainActivity.class);\n                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n                context.startActivity(i);\n    }\n}\n```\n\n## Adding `BroadCastReceiver` to the Android Manifest\n\n```xml\n\u003creceiver android:name=\".BootReceiver\" android:enabled=\"true\"\n    android:permission=\"android.permission.RECEIVE_BOOT_COMPLETED\"\u003e\n    \u003cintent-filter\u003e\n        \u003caction android:name=\"android.intent.action.BOOT_COMPLETED\" /\u003e\n        \u003ccategory android:name=\"android.intent.category.DEFAULT\" /\u003e\n    \u003c/intent-filter\u003e\n\u003c/receiver\u003e\n```\n\nInstall the application, and then restart the device. You can see the application will start after the device restarts.\n"])</script>
1<script>self.__next_f.push([1,"138:T11a5,"])</script>
1<script>self.__next_f.push([1,"\nThe `TextSwitcher` and `ImageSwitcher` in Android allows you to create an smooth transition animation in when switching between Android views. TextSwitcher and ImageSwitcher is available from version Android v1.6+. TextSwitcher replaces a TextView and ImageSwitcher replaces an ImageView.\n\nTextView and TextSwitcher work in a similar way. TextSwitcher is what we need if we want to add an animation to avoid the hard swap. A TextSwitcher is useful to animate a label onscreen. Whenever it’s called, TextSwitcher animates the current text out and animates the new text in.\n\nTextSwitcher uses the factory to create new views. Whenever we use setText(), it first removes the old view using an animation set with the `setOutAnimation()` method, and then places the new one using the animation set by the `setInAnimation()` method. You can use setInAnimation() and setOutAnimation() method to set in and out animation using for switcher. The new transition fades out the original text while the new text fades in to replace it.\n\nIn this example, we will use default stock android `fade_in` animation. This should work equally well with other custom animations.\n\n![TextSwitcher-and-ImageSwitcher-Example-in-Android](/media/articles/378/TextSwitcher-and-ImageSwitcher-Example-in-Android.gif)\n\n### Defining TextSwitcher and ImageSwitcher in layout\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\" \u003e\n\n    \u003cImageSwitcher\n        android:id=\"@+id/imageSwitcher\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\n        android:layout_alignParentLeft=\"true\" \u003e\n    \u003c/ImageSwitcher\u003e\n\n    \u003cTextSwitcher\n        android:id=\"@+id/textSwitcher\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentBottom=\"true\"\n        android:layout_centerHorizontal=\"true\"\n        android:background=\"#99000000\"\n        android:padding=\"10dp\" /\u003e\n\n    \u003cButton\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentRight=\"true\"\n        android:layout_alignParentTop=\"true\"\n        android:layout_marginTop=\"10dp\"\n        android:onClick=\"onSwitch\"\n        android:text=\"Next Image \u003e\u003e\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n## Using TextSwitcher and ImageSwitcher from code\n\n```java\npackage com.javatechig.ui;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.Gravity;\nimport android.view.View;\nimport android.widget.ImageSwitcher;\nimport android.widget.ImageView;\nimport android.widget.TextSwitcher;\nimport android.widget.TextView;\nimport android.widget.ViewSwitcher.ViewFactory;\n\npublic class MainActivity extends Activity {\n\n    private static final String[] TEXTS = { \"Image #1\", \"Image #2\", \"Image #3\" };\n    private static final int[] IMAGES = { R.drawable.mf1, R.drawable.mf2,\n            R.drawable.mf3 };\n    private int mPosition = 0;\n    private TextSwitcher mTextSwitcher;\n    private ImageSwitcher mImageSwitcher;\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.main);\n\n        mTextSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher);\n        mTextSwitcher.setFactory(new ViewFactory() {\n            @Override\n            public View makeView() {\n                TextView textView = new TextView(MainActivity.this);\n                textView.setGravity(Gravity.CENTER);\n                return textView;\n            }\n        });\n\n        mTextSwitcher.setInAnimation(this, android.R.anim.fade_in);\n        mTextSwitcher.setOutAnimation(this, android.R.anim.fade_out);\n\n        mImageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);\n        mImageSwitcher.setFactory(new ViewFactory() {\n            @Override\n            public View makeView() {\n                ImageView imageView = new ImageView(MainActivity.this);\n                return imageView;\n            }\n        });\n        mImageSwitcher.setInAnimation(this, android.R.anim.slide_in_left);\n        mImageSwitcher.setOutAnimation(this, android.R.anim.slide_out_right);\n\n        onSwitch(null);\n    }\n\n    public void onSwitch(View view) {\n        mTextSwitcher.setText(TEXTS[mPosition]);
1\n        mImageSwitcher.setBackgroundResource(IMAGES[mPosition]);\n        mPosition = (mPosition + 1) % TEXTS.length;\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"139:T2a80,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains how to create custom Views in Android. We will create a custom view with two TextView. One to the left and other to the right as pairs. The custom styles can be configured from xml.\n\nAndroid provides various View classes for dealing with user interfaces. View’s are responsible for representing data to user and allow interactivity. Below are few of the common View classes and Layout that is being supported in android.\n\n## Different Android Layouts\n\nA layout defines the visual structure for a user interface. It defines the way View’s can be placed on an Activity. Layouts can be declared in two ways.\n\n1.  **Declarative approach:** Android provides a straightforward XML vocabulary that corresponds to the View classes and sub classes, such as those for widgets and layouts.\n2.  Instantiate **Components using Java Code:** Your application can create and manipulate View and ViewGroup objects programmatically.\n\nFollowing are the the ViewGroup classes supported by Android;\n\n-   [Linear Layout](http://stacktips.com/articles/android-linearlayout-example)\n-   [Relative Layout](http://stacktips.com/articles/android-relativelayout-example)\n-   [Table Layout](http://stacktips.com/articles/android-table-layout-example)\n-   [Grid View](http://stacktips.com/articles/android-gridview-example-building-image-gallery-in-android/)\n-   [Frame Layout](http://stacktips.com/articles/android-framelayout-example)\n-   [List View](http://stacktips.com/articles/android-listview-tutorial)\n\nFollowing are some of the most common used Android View classes;\n\n-   [Button](http://stacktips.com/articles/android-button-example/)\n-   [Checkbox](http://stacktips.com/articles/android-checkbox-example \"Android Checkbox Example\")\n-   [EditText](http://stacktips.com/articles/edittext-validation-in-android-example \"Edittext Validation in Android Example\")\n-   [ImageView](http://stacktips.com/articles/android-imageview-example \"Android ImageView Example\")\n-   [ProgressBar](http://stacktips.com/articles/progressbar-while-loading-webview/)\n-   [RadioButton](http://stacktips.com/articles/android-radio-button-example/)\n-   [SeekBar](http://stacktips.com/articles/android-seekbar-example/)\n-   [Spinner (ComboBox)](http://stacktips.com/articles/android-spinner-example/)\n-   [ToggleButton](http://stacktips.com/articles/how-to-turn-off-turn-on-wifi-in-android-using-code/)\n-   [WebView](http://stacktips.com/articles/android-webview-example/)\n-   [Dialog](http://stacktips.com/articles/android-dialog-example/)\n\n## Why Custom Views?\n\nAll the above View classes and ViewGroup classes are good enough to create an solid android app. However, sometimes your app may have unique needs that aren’t covered by the built-in views. Such cases you will end up creating an custom View in android. The below example shows you how to create your own views that are robust and reusable.\n\n## Creating Custom Views\n\nDeclaring a custom View is much similar to declaring any other class in Java. While designing an custom class keep the following things in mind\n\n1.  It should provide some easy to use interface and should use the memory efficiently.\n2.  A Custom View should conform to Android standards\n3.  You can provide custom styleable attributes that can be configurable from Android XML layouts\n4.  Your View class should be compatible with multiple Android platforms\n\nAll the default View classes that are available in android extends View. The same way your custom View can directly extend the View class or you may extend one of the default View controls such as TextView. Now, override the constructor that takes a Context and an AttributeSet object as parameters.\n\n```java\nimport android.content.Context;\nimport android.util.AttributeSet;\nimport android.widget.LinearLayout;\n\npublic class LovelyView extends LinearLayout {\n\n    public LovelyView(Context context) {\n        super(context);\n    }\n\n    public LovelyView(Context context, AttributeSet attrs) {\n        super(context, attrs);\n    }\n\n    public LovelyView(Context context, AttributeSet attrs, int defStyle) {\n        this(context, attrs);\n    }\n}\n```\n\n### Define Custom Attributes\n\nYou can provide custom styleable attributes that can be configurable from Android XML layouts. These attributes will control its appearance and behavior of View. You can create a **`values/attr.xml`** file in your project. To enable this behavior in y
1our custom view, you can define custom attributes for your view in a resource element in **`attr.xml`** file.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cresources\u003e\n\n    \u003cdeclare-styleable name=\"LovelyView\"\u003e\n        \u003cattr name=\"leftLabel\" format=\"string\" /\u003e\n        \u003cattr name=\"rightLabel\" format=\"string\" /\u003e\n        \u003cattr name=\"leftLabelStyle\" format=\"reference\" /\u003e\n        \u003cattr name=\"rightLabelStyle\" format=\"reference\" /\u003e\n    \u003c/declare-styleable\u003e\n\n\u003c/resources\u003e\n```\n\nIn the above xml file, `LovelyView` is the name of the style. and `leftLabel`, `rightLabel`, `leftLabelStyle` and `rightLabelStyle` are the style attributes defines.\n\nOnce you define the custom attributes, you can use them in layout XML files just like built-in attributes. The only difference is that your custom attributes belong to a different namespace. Instead of belonging to the `http://schemas.android.com/apk/res/android` namespace, they belong to `http://schemas.android.com/apk/res/(your package name)`\n\nHere’s how to use the attributes defined for LovelyView\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    xmlns:custom=\"http://schemas.android.com/apk/res/com.example.customview\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:layout_margin=\"10dp\"\n    android:orientation=\"vertical\"\n    tools:context=\".MainActivity\" \u003e\n\n    \u003ccom.example.customview.LovelyView\n        android:id=\"@+id/leftTextView\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"10dp\"\n        custom:leftLabel=\"\"\n        custom:leftLabelStyle=\"@style/leftTextStyle\"\n        custom:rightLabel=\"\"\n        custom:rightLabelStyle=\"@style/rightTextStyle\" /\u003e\n\n    \u003ccom.example.customview.LovelyView\n        android:id=\"@+id/rightTextView\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        custom:leftLabel=\"Hello Mr:\"\n        custom:leftLabelStyle=\"@style/leftTextStyle\"\n        custom:rightLabel=\"Whats Up Buddy!\"\n        custom:rightLabelStyle=\"@style/rightTextStyle\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\nNotice that, In the above code snippet, we are using the fully qualified name of the custom view class. If your view class is an inner class, you must further qualify it with the name of the view’s outer class.\n\n### Apply Custom Attributes\n\nIn the above two steps, we have configured the View stylable attributes in the XML. When a view is created from an XML layout, all of the attributes in the XML tag are read from the resource bundle and passed into the view’s constructor as an AttributeSet. We can read the attributes by calling **`obtainStyledAttributes()`** method.\n\n```java\nTypedArray a = context.getTheme().obtainStyledAttributes(attrs,\n        R.styleable.LovelyView, 0, 0);\ntry {\n    // get the text and colors specified using the names in attrs.xml\n    leftLabel = a.getString(R.styleable.LovelyView_leftLabel);\n    rightLabel = a.getString(R.styleable.LovelyView_rightLabel);\n    leftStyle = a.getResourceId(R.styleable.LovelyView_leftLabelStyle, android.R.style.TextAppearance_DeviceDefault);\n    rightStyle = a.getResourceId(R.styleable.LovelyView_rightLabelStyle, android.R.style.TextAppearance_DeviceDefault);\n\n} finally {\n    a.recycle();\n}\n\nLayoutInflater.from(context).inflate(R.layout.key_value_layout, this);\n\n//left text view\nleftTextView = (TextView) this.findViewById(R.id.leftTextView);\nleftTextView.setText(leftLabel);\nleftTextView.setTextAppearance(context, leftStyle);\n\n//right text view\nrightTextView = (TextView) this.findViewById(R.id.rightTextView);\nrightTextView.setText(rightLabel);\nrightTextView.setTextAppearance(context, rightStyle);\n```\n\nBelow is the complete View class code\n\n```java\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\npublic class LovelyView extends LinearLayout {\n    private String leftLabel = \"\";\n    private String rightLabel = \"\";\n    private TextView leftTextView;\n    private TextView rightTextView;\n    private int leftStyle ;\n    private int rightStyle;\n\n    public LovelyView(Context context) {\n        super(context);\n        LayoutInflater.from(context).inflate(R.layout.key_value_layout, this);\n    }\n\n    public LovelyView(Context context, AttributeSet attrs) {\n        super(context, attrs);\n        initViews(context, attrs);\n    }\n\n    public LovelyView(Context context, AttributeSet attrs, int defStyle) {\n        this(context, attrs);\n        initViews(context, attrs);\n    }\n\n    private void initViews(Context context, AttributeSet attrs) {\n        TypedArray a = context.getTheme().obtainStyledAttributes(attrs,\n                R.styleable.LovelyView, 0, 0);\n\n        try {\n            // get the text and colors specified using the names in attrs.xml\n            leftLabel = a.getString(R.styleable.LovelyView_leftLabel);\n            rightLabel = a.getString(R.styleable.LovelyView_rightLabel);\n            leftStyle = a.getResourceId(R.styleable.LovelyView_leftLabelStyle, android.R.style.TextAppearance_DeviceDefault);\n            rightStyle = a.getResourceId(R.styleable.LovelyView_rightLabelStyle, android.R.style.TextAppearance_DeviceDefault);\n\n        } finally {\n            a.recycle();\n        }\n\n        LayoutInflater.from(context).inflate(R.layout.key_value_layout, this);\n\n        //left text view\n        leftTextView = (TextView) this.findViewById(R.id.leftTextView);\n        leftTextView.setText(leftLabel);\n        leftTextView.setTextAppearance(context, leftStyle);\n\n        //right text view\n        rightTextView = (TextView) this.findViewById(R.id.rightTextView);\n        rightTextView.setText(rightLabel);\n        rightTextView.setTextAppearance(context, rightStyle);\n    }\n\n    public String getLeftLabel() {\n        return leftLabel;\n    }\n\n    public void setLeftLabel(String leftLabel) {\n        this.left
1Label = leftLabel;\n        if(leftTextView!=null){\n            leftTextView.setText(leftLabel);\n        }\n    }\n\n    public String getRightLabel() {\n        return rightLabel;\n    }\n\n    public void setRightLabel(String rightLabel) {\n        this.rightLabel = rightLabel;\n        if(rightTextView!=null){\n            rightTextView.setText(rightLabel);\n        }\n    }\n}\n```\n\n  \n\n[](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"13a:T108d,"])</script>
1<script>self.__next_f.push([1,"\nWhen you’re creating complex layouts, you may find yourself adding a lot of ViewGroup’s and Views. But, making your view hierarchy tree taller will also result in slowness in your application and increases complexity. Creating optimized layouts is fundamental to building an application that runs fast and is responsive to the user.\n\nIn this example, we’ll see how to use the `\u003cinclude /\u003e` tag in your XML to avoid replication of code in different layouts. Before we begin, let us have a look into the screenshot below.\n\n[![Avoid replication of Views using include tag in android layout](/media/articles/380/Avoid-replication-of-Views-using-include-tag-in-android-layout.gif)](http://stacktips.com)\n\nNow, let us imagine we want to add footer (as shown in the image below) to every page of your app. It looks quite simple, we can just declare it in all the layouts files as required. But what happens if we want to do a small modification to the footer layout? We have to do the changes to all the layout files, which costs time. Android include tag is the solution here.\n\n## How it works?\n\nYou just have to declare your reusable xml layout file in a separate xml file. For our example, let us name it as footer.xml.\n\nJust use the footer.xml file using include tag for all your activity/fragment layout files.\n\n### footer.xml\n\nHere is our `footer.xml` file which we can reuse using include tag\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:background=\"#ffffff\"\n    android:padding=\"5dp\" \u003e\n\n    \u003cImageView\n        android:id=\"@+id/imageView\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentLeft=\"true\"\n        android:layout_alignParentTop=\"true\"\n        android:layout_margin=\"5dp\"\n        android:src=\"@drawable/javatechig_logo\" /\u003e\n\n    \u003cTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerHorizontal=\"true\"\n        android:layout_centerVertical=\"true\"\n        android:gravity=\"center\"\n        android:text=\"@string/footer_text\"\n        android:textColor=\"#13352E\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\nWe have just declared the layout for footer.xml, which will be reused in all activity. Let us create an layout file for our MainActivity class. Let’s look at how it can help us out. We use the `\u003cinclude /\u003e` tag in XML to add another layout from another XML file.\n\n### activity\\_main.xml\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:background=\"#f0f0f0\" \u003e\n\n    \u003cLinearLayout\n        android:id=\"@+id/linearLayout1\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"10dp\"\n        android:background=\"#ffffff\"\n        android:orientation=\"vertical\"\n        android:padding=\"5dp\" \u003e\n\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"@string/hint\"\n            android:textAppearance=\"?android:attr/textAppearanceLarge\"\n            android:textColor=\"#13352E\" /\u003e\n\n        \u003cImageView\n            android:id=\"@+id/imageView1\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_gravity=\"center_horizontal\"\n            android:src=\"@drawable/image_7\" /\u003e\n    \u003c/LinearLayout\u003e\n\n    \u003cinclude\n        android:id=\"@+id/footerVie
1w\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentBottom=\"true\"\n        layout=\"@layout/footer\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\nFrom your MainActivity.java file, you can access the views by using following code snippets\n\n```java\n// Fetching footer layout\nView footerLayout = findViewById(R.id.footerView);\n\n// Fetching the textview declared in footer.xml\nTextView footerText = (TextView) footerLayout.findViewById(R.id.footer_text);\nfooterText.setText(\"Some Text Here\");\n```\n"])</script>
1<script>self.__next_f.push([1,"13b:T10ff,"])</script>
1<script>self.__next_f.push([1,"\nThe code sample below will help you understand “How To Send Email In Android” using EmailIntent in android. In android we can use Intent.ACTION\\_SEND to call an existing email client to send an Email. If no email clients are configured then,android system displays **“No application can perform this action”** error.\n\n## Sending Email In Android example\n\nHere is my layout as shown in the screenshots below\n\n[![sending email in android](/media/articles/381/sending-email-in-android.png)](http://stacktips.com)\n\n**activity\\_main.xml**\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:id=\"@+id/linearLayout1\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:orientation=\"vertical\"\n    android:padding=\"5dp\" \u003e\n\n    \u003cTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"To:\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n    \u003cEditText\n        android:id=\"@+id/toEmail\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:hint=\"Enter email\" \u003e\n    \u003c/EditText\u003e\n\n    \u003cTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Subject:\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n    \u003cEditText\n        android:id=\"@+id/subject\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:hint=\"Enter Subject\" \u003e\n    \u003c/EditText\u003e\n\n    \u003cTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Message:\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n    \u003cEditText\n        android:id=\"@+id/emailBody\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:gravity=\"top\"\n        android:hint=\"Enter mail body\"\n        android:inputType=\"textMultiLine\"\n        android:lines=\"5\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\nIn my code example, I have used ActionBar commands for send and clear option.\n\n**main\\_menu.xml**\n\n```xml\n\u003cmenu xmlns:android=\"http://schemas.android.com/apk/res/android\" \u003e\n\n     \u003citem\n        android:id=\"@+id/menu_clear\"\n        android:icon=\"@android:drawable/ic_menu_close_clear_cancel\"\n        android:showAsAction=\"ifRoom|withText\"\n        android:title=\"Clear\"/\u003e\n\n    \u003citem\n        android:id=\"@+id/menu_send\"\n        android:icon=\"@android:drawable/ic_menu_send\"\n        android:showAsAction=\"ifRoom|withText\"\n        android:title=\"Send\"/\u003e\n\n\u003c/menu\u003e\n```\n\nNow, check out the activity code\n\n**MainActivity.java**\n\n```java\npublic class MainActivity extends Activity {\n\n    private EditText toEmail = null;\n    private EditText emailSubject = null;\n    private EditText emailBody = null;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        toEmail = (EditText) findViewById(R.id.toEmail);\n        emailSubject = (EditText) findViewById(R.id.subject);\n        emailBody = (EditText) findViewById(R.id.emailBody);\n\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        getMenuInflater().inflate(R.menu.main, menu);\n        return true;\n    }\n\n    @Override\n    public boolean onOptionsItemSelected(MenuItem item) {\n        switch (item.getItemId()) {\n        case R.id.menu_clear:\n            toEmail.setText(\"\");\n            emailBody.setText(\"\");\n            emailSubject.setText(\"\");\n            break;\n        case R.id.menu_send:\n            String to = toEmail.getText().toString();\n            String subject = emailSubject.getText().toString();\n            String message = emailBody.getText().toString();\n\n            Intent email = new Intent(Intent.ACTION_SEND);\n            email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });\n            email.putExtra(Intent.EXTRA_SUBJECT, subject);\n            email.putExtra(Intent.EXTRA_TEXT, message);\n\n            // need this to prompts email client only\n            email.setType(\"message/rfc822\");\n\n            startActivity(Intent.createChooser(email, \"Choose an Email client\"));\n\n            break;\n        }\n        return true;\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"13c:T1c05,"])</script>
1<script>self.__next_f.push([1,"\n# Introduction\n\nThis tutorial will help you understand android `SeekBar`. Here in this example, we’ll see how to create and customize SeekBar with different color and layout.\n\n`SeekBar` is one of the useful user interface element in android applications. SeekBar is an extension of `ProgressBar` that allows the selection of integer values using a natural user interface. Basically SeekBar has a thumb that you can slide to choose a value between 0 and some maximum that you set. A typical usage of Seekbar is your device brightness control and volume control.\n\nWe can add a SeekBar widget using element. `android:max` property is basically used to set a maximum integer value for selection using SeekBar. `android:progress` property is basically used to set a integer value for SeekBar progress.\n\n# Android Seekbar Example\n\n#### activity\\_seekbar.xml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:background=\"#F0F0F5\" \u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"5dp\"\n        android:background=\"@drawable/background_view_rounded_single\"\n        android:orientation=\"vertical\"\n        android:visibility=\"visible\" \u003e\n\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:padding=\"10dp\"\n            android:text=\"Seekbar\"\n            android:textColor=\"#ffffff\"\n            android:textSize=\"20sp\" /\u003e\n\n        \u003cSeekBar\n            android:id=\"@+id/seek1\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"wrap_content\"\n            android:layout_margin=\"10dp\"\n            android:progress=\"20\"\n            android:secondaryProgress=\"20\" /\u003e\n\n        \u003cTextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:padding=\"10dp\"\n            android:text=\"Custom Seekbar\"\n            android:textColor=\"#fcfcfc\"\n            android:textSize=\"20sp\" /\u003e\n\n        \u003cSeekBar\n            android:id=\"@+id/volume_bar\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"wrap_content\"\n            android:layout_margin=\"10dp\"\n            android:max=\"100\"\n            android:progress=\"0\"\n            android:progressDrawable=\"@drawable/progressbar\"\n            android:secondaryProgress=\"0\" /\u003e\n    \u003c/LinearLayout\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n#### background\\_view\\_rounded\\_single.xml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cinset android:insetLeft=\"1.0px\" android:insetRight=\"1.0px\" android:insetTop=\"0.0px\" android:insetBottom=\"1.0px\"\n  xmlns:android=\"http://schemas.android.com/apk/res/android\"\u003e\n    \u003cselector\u003e\n        \u003citem android:state_pressed=\"true\"\u003e\n            \u003cshape\u003e\n                \u003cgradient android:startColor=\"@color/rounded_container_bg\" android:endColor=\"@color/rounded_container_bg\" android:angle=\"270.0\" /\u003e\n                \u003ccorners android:radius=\"11.0dip\" /\u003e\n            \u003c/shape\u003e\n        \u003c/item\u003e\n        \u003citem\u003e\n            \u003cshape\u003e\n                \u003cstroke android:width=\"1.0px\" android:color=\"@color/rounded_container_border\" /\u003e\n                \u003cgradient android:startColor=\"@color/rounded_container_bg\" android:endColor=\"@color/rounded_container_bg\" android:angle=\"270.0\" /\u003e\n                \u003ccorners android:radius=\"10.0dip\" /\u003e\n\n            \u003c/shape\u003e\n        \u003c/item\u003e\n    \u003c/selector\u003e\n\u003c/inset\u003e\n```\n\n#### progressbar.xml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003clayer
1-list xmlns:android=\"http://schemas.android.com/apk/res/android\" \u003e\n\n    \u003citem android:id=\"@android:id/background\"\u003e\n        \u003cshape android:shape=\"rectangle\" \u003e\n            \u003ccorners android:radius=\"5dp\" /\u003e\n\n            \u003cgradient\n                android:angle=\"270\"\n                android:endColor=\"@color/light_gray_header_color\"\n                android:startColor=\"@color/light_gray_header_color\" /\u003e\n        \u003c/shape\u003e\n    \u003c/item\u003e\n    \u003citem android:id=\"@android:id/secondaryProgress\"\u003e\n        \u003cclip\u003e\n            \u003cshape android:shape=\"rectangle\" \u003e\n                \u003ccorners android:radius=\"5dp\" /\u003e\n\n                \u003cgradient\n                    android:angle=\"270\"\n                    android:endColor=\"#00996a\"\n                    android:startColor=\"#00d190\" /\u003e\n            \u003c/shape\u003e\n        \u003c/clip\u003e\n    \u003c/item\u003e\n    \u003citem android:id=\"@android:id/progress\"\u003e\n        \u003cclip\u003e\n            \u003cshape android:shape=\"rectangle\" \u003e\n                \u003ccorners android:radius=\"5dp\" /\u003e\n\n                \u003cgradient\n                    android:angle=\"270\"\n                    android:endColor=\"#00996a\"\n                    android:startColor=\"#00d190\" /\u003e\n            \u003c/shape\u003e\n        \u003c/clip\u003e\n    \u003c/item\u003e\n\n\u003c/layer-list\u003e\n```\n\n#### colors.xml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cresources\u003e\n\n    \u003ccolor name=\"default_screen_bg\"\u003e#f9f9f9\u003c/color\u003e\n    \u003ccolor name=\"rounded_container_bg\"\u003e#222222\u003c/color\u003e\n    \u003ccolor name=\"rounded_container_border\"\u003e#3b3f44\u003c/color\u003e\n    \u003ccolor name=\"light_gray_header_color\"\u003e#646663\u003c/color\u003e\n\n\u003c/resources\u003e\n```\n\nWe are good with layout design, lets move a bit into Java coding. Below is my activity code\n\n```java\npublic class SeekbarActivity extends Activity {\n\n    private SeekBar volumeControl = null;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_seekbar);\n\n        volumeControl = (SeekBar) findViewById(R.id.volume_bar);\n\n        volumeControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {\n            int progressChanged = 0;\n\n            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){\n                progressChanged = progress;\n            }\n\n            public void onStartTrackingTouch(SeekBar seekBar) {\n                // TODO Auto-generated method stub\n            }\n\n            public void onStopTrackingTouch(SeekBar seekBar) {\n                Toast.makeText(SeekbarActivity.this,\"seek bar progress:\"+progressChanged,\n                        Toast.LENGTH_SHORT).show();\n            }\n        });\n    }\n\n}\n```\n\nOur activity implements `SeekBar.OnSeekBarChangeListener`; Basically `SeekBar.OnSeekBarChangeListener` is a public static interface that is used to listen the SeekBar events. The SeekBar.OnSeekBarChangeListener interface allows us to override the below methods.\n\n1.  `onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)` – Used to notify that the progress level has changed.\n2.  `onStartTrackingTouch(SeekBar seekBar)` – Used to notify that the user has started a touch gesture.\n3.  `onStopTrackingTouch(SeekBar seekBar)` – Used to notify that the user has finished a touch gesture.\n\n# Output\n\nOutput of the above code is shown below\n\n[![Customizing Android Seekbar Example](/media/articles/383/Customizing-Android-Seekbar-300x507.png)](http://stacktips.com)\n\n# Download Source Code\n\nDownload complete example source code from GitHub.\n\n[Download source](https://github.com/javatechig/Android-Seekbar-Example)\n"])</script>
1<script>self.__next_f.push([1,"13d:Td2b,"])</script>
1<script>self.__next_f.push([1,"\nThe following code snippet will help you to pragmatically turn on and turn off wi-fi in android. This sample code is using android Switch (Available from android API level 14) to toggle between wi-fi state.\n\n[](http://stacktips.com)\n\nWe need following permissions in AndroidMainfest.xml file\n\n```xml\n  \u003cuses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\" /\u003e\n  \u003cuses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\" /\u003e\n  \u003cuses-permission android:name=\"android.permission.WAKE_LOCK\" /\u003e\n```\n\n### Creating Layout for On/Off Switch\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    tools:context=\".MainActivity\" \u003e\n\n    \u003cImageView\n        android:id=\"@+id/imageView1\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerInParent=\"true\"\n        android:src=\"@drawable/wifi\" /\u003e\n\n    \u003cSwitch\n        android:id=\"@+id/wifi_switch\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentBottom=\"true\"\n        android:layout_marginBottom=\"10dp\"\n        android:background=\"@android:color/background_dark\"\n        android:checked=\"false\"\n        android:text=\"Wi-Fi Settings\"\n        android:textColor=\"@android:color/white\"\n        android:textOff=\"OFF\"\n        android:textOn=\"ON\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n### Turn on or off wifi in Android\n\nWe are done with the layout. Now let us move on to turn on wifi pragmatically.  To do this e need to get the Wifi system service by calling `getSystemService()` method. After getting Wifi manager, we can check the state of WiFi by calling `isWiiEnabled()` method, before turning on.\n\n```java\npackage com.example.wifitest;\nimport android.net.wifi.WifiManager;\nimport android.os.Bundle;\nimport android.widget.CompoundButton;\nimport android.widget.Switch;\nimport android.widget.Toast;\nimport android.app.Activity;\nimport android.content.Context;\n\npublic class MainActivity extends Activity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        Switch toggle = (Switch) findViewById(R.id.wifi_switch);\n        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n                if (isChecked) {\n                    toggleWiFi(true);\n                    Toast.makeText(getApplicationContext(), \"Wi-Fi Enabled!\", Toast.LENGTH_LONG).show();\n                } else {\n                    toggleWiFi(false);\n                    Toast.makeText(getApplicationContext(), \"Wi-Fi Disabled!\", Toast.LENGTH_LONG).show();\n                }\n            }\n        });\n    }\n\n    public void toggleWiFi(boolean status) {\n        WifiManager wifiManager = (WifiManager) this\n                .getSystemService(Context.WIFI_SERVICE);\n        if (status == true \u0026\u0026 !wifiManager.isWifiEnabled()) {\n            wifiManager.setWifiEnabled(true);\n        } else if (status == false \u0026\u0026 wifiManager.isWifiEnabled()) {\n            wifiManager.setWifiEnabled(false);\n        }\n    }\n\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"13e:T292e,"])</script>
1<script>self.__next_f.push([1,"\nAndroid `PackageManager` class is used to retrieve information on the application packages that are currently installed on the device. You can get an instance of PackageManager class by calling `getPackageManager()`. PackageManager provides methods for querying and manipulating installed packages and related permissions, etc. In this Android example, we we get list of installed apps in Android.\n\n[![How to Get List of Installed Apps in Android](/media/articles/385/How-to-get-list-of-Installed-Apps-in-Android.gif)](http://stacktips.com)\n\n```java\nPackageManager packageManager = getPackageManager();\nList\u003cApplicationInfo\u003e list = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)\n```\n\n`packageManager.getInstalledApplications()` return a List of all application packages that are installed on the device. If we set the flag `GET_UNINSTALLED_PACKAGES` has been set, a list of all applications including those deleted with `DONT_DELETE_DATA` (partially installed apps with data directory) will be returned.\n\n# 1. Creating application layout in xml\n\n**activity\\_main.xml**\n\nAs you can see in the attached screenshot, we will be creating a ListView to show all of the installed applications in android.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:orientation=\"vertical\" \u003e\n\n    \u003cListView\n        android:id=\"@android:id/list\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n**snippet\\_list\\_row.xml**\n\nThis layout is being used by the ListView Adapter for representing application details. It shows application icon, application name and application package.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\" \u003e\n\n    \u003cImageView\n        android:id=\"@+id/app_icon\"\n        android:layout_width=\"50dp\"\n        android:layout_height=\"50dp\"\n        android:padding=\"3dp\"\n        android:scaleType=\"centerCrop\" /\u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\n        android:gravity=\"center_vertical\"\n        android:orientation=\"vertical\"\n        android:paddingLeft=\"5dp\" \u003e\n\n        \u003cTextView\n            android:id=\"@+id/app_name\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"wrap_content\"\n            android:gravity=\"center_vertical\"\n            android:textStyle=\"bold\" /\u003e\n\n        \u003cTextView\n            android:id=\"@+id/app_paackage\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"wrap_content\"\n            android:gravity=\"center_vertical\" /\u003e\n    \u003c/LinearLayout\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n# 2. Writing Java class\n\n**AllAppsActivity.java**\n\nThis is the main application class that is used to initialize and list the installed applications. As getting the list of application details from PackageManage is a long running task, we will do that in AsyncTask. Also, this class is using custom Adapter “ApplicationAdapter” for custom ListView.\n\n```java\npackage com.javatechig.listapps;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport android.app.AlertDialog;\nimport android.app.ListActivity;\nimport android.app.ProgressDialog;\nimport android.content.ActivityNotFoundException;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.pm.ApplicationInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.MenuInflater;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ListView;\nimport android.widget.Toast;\n\npublic class AllAppsActivity extends ListActivity {\n    private PackageManager packageManager = null;\n    private List\u003cApplicationInfo\u003e applist = null;\n    private ApplicationAdapter listadaptor = null;\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        packageManager = getPackageManager();\n\n        new LoadApplications().execute();\n    }\n\n    public boolean onCreateOptionsMenu(Menu menu) {\n        MenuInflater inflater = getMenuInflater();\n        inflater.inflate(R.menu.menu, menu);\n\n        return true;\n    }\n\n    public boolean onOptionsItemSelected(MenuItem item) {\n        boolean result = true;\n\n        switch (item.getItemId()) {\n        case R.id.menu_about: {\n            displayAboutDialog();\n\n            break;\n        }\n        default: {\n            result = super.onOptionsItemSelected(item);\n\n            break;\n        }\n        }\n\n        return result;\n    }\n\n    private void displayAboutDialog() {\n        final AlertDialog.Builder builder = new AlertDialog.Builder(this);\n        builder.setTitle(getString(R.string.about_title));\n        builder.setMessage(getString(R.string.about_desc));\n\n        builder.setPositiveButton(\"Know More\", new DialogInterface.OnClickListener() {\n               public void onClick(DialogInterface dialog, int id) {\n                   Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http://stacktips.com\"));\n                   startActivity(browserIntent);\n                   dialog.cancel();\n               }\n           });\n        builder.setNegativeButton(\"No Thanks!\", new DialogInterface.OnClickListener() {\n               public void onClick(DialogInterface dialog, int id) {\n                    dialog.cancel();\n               }\n        });\n\n        builder.show();\n    }\n\n    @Override\n    protected void onListItemClick(ListView l, View v, int position, long id) {\n        super.onListItemClick(l, v, position, id);\n\n        ApplicationInfo app = applist.get(position);\n        try {\n            Intent intent = packageManager\n                    .getLaunchIntentForPackage(app.packageName);\n\n            if (null != intent) {\n                startActivity(intent);\n            }\n        } catch (ActivityNotFoundException e) {\n            Toast.makeText(AllAppsActivity.this, e.getMe
1ssage(),\n                    Toast.LENGTH_LONG).show();\n        } catch (Exception e) {\n            Toast.makeText(AllAppsActivity.this, e.getMessage(),\n                    Toast.LENGTH_LONG).show();\n        }\n    }\n\n    private List\u003cApplicationInfo\u003e checkForLaunchIntent(List\u003cApplicationInfo\u003e list) {\n        ArrayList\u003cApplicationInfo\u003e applist = new ArrayList\u003cApplicationInfo\u003e();\n        for (ApplicationInfo info : list) {\n            try {\n                if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {\n                    applist.add(info);\n                }\n            } catch (Exception e) {\n                e.printStackTrace();\n            }\n        }\n\n        return applist;\n    }\n\n    private class LoadApplications extends AsyncTask\u003cVoid, Void, Void\u003e {\n        private ProgressDialog progress = null;\n\n        @Override\n        protected Void doInBackground(Void... params) {\n            applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));\n            listadaptor = new ApplicationAdapter(AllAppsActivity.this,\n                    R.layout.snippet_list_row, applist);\n\n            return null;\n        }\n\n        @Override\n        protected void onCancelled() {\n            super.onCancelled();\n        }\n\n        @Override\n        protected void onPostExecute(Void result) {\n            setListAdapter(listadaptor);\n            progress.dismiss();\n            super.onPostExecute(result);\n        }\n\n        @Override\n        protected void onPreExecute() {\n            progress = ProgressDialog.show(AllAppsActivity.this, null,\n                    \"Loading application info...\");\n            super.onPreExecute();\n        }\n\n        @Override\n        protected void onProgressUpdate(Void... values) {\n            super.onProgressUpdate(values);\n        }\n    }\n}\n```\n\n**ApplicationAdapter.java**\n\n```java\npackage com.javatechig.listapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.content.pm.ApplicationInfo;\nimport android.content.pm.PackageManager;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.ImageView;\nimport android.widget.TextView;\n\npublic class ApplicationAdapter extends ArrayAdapter\u003cApplicationInfo\u003e {\n    private List\u003cApplicationInfo\u003e appsList = null;\n    private Context context;\n    private PackageManager packageManager;\n\n    public ApplicationAdapter(Context context, int textViewResourceId,\n            List\u003cApplicationInfo\u003e appsList) {\n        super(context, textViewResourceId, appsList);\n        this.context = context;\n        this.appsList = appsList;\n        packageManager = context.getPackageManager();\n    }\n\n    @Override\n    public int getCount() {\n        return ((null != a
1ppsList) ? appsList.size() : 0);\n    }\n\n    @Override\n    public ApplicationInfo getItem(int position) {\n        return ((null != appsList) ? appsList.get(position) : null);\n    }\n\n    @Override\n    public long getItemId(int position) {\n        return position;\n    }\n\n    @Override\n    public View getView(int position, View convertView, ViewGroup parent) {\n        View view = convertView;\n        if (null == view) {\n            LayoutInflater layoutInflater = (LayoutInflater) context\n                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n            view = layoutInflater.inflate(R.layout.snippet_list_row, null);\n        }\n\n        ApplicationInfo applicationInfo = appsList.get(position);\n        if (null != applicationInfo) {\n            TextView appName = (TextView) view.findViewById(R.id.app_name);\n            TextView packageName = (TextView) view.findViewById(R.id.app_paackage);\n            ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);\n\n            appName.setText(applicationInfo.loadLabel(packageManager));\n            packageName.setText(applicationInfo.packageName);\n            iconview.setImageDrawable(applicationInfo.loadIcon(packageManager));\n        }\n        return view;\n    }\n};\n```\n\n# Download Complete Example\n\nDownload complete Eclipse project source code from [GitHub.](https://github.com/javatechig/javatechig-android-advanced/tree/master/ListInstalledApps)\n"])</script>
1<script>self.__next_f.push([1,"13f:T251b,"])</script>
1<script>self.__next_f.push([1,"\nIn Android user interface is displayed through an activity. Activity is used to represent the data to user and allows user interaction. In an android application, we can have multiple activities and that can interact with each other. This tutorial I will explain more about, how to switch between one Activity to another.\n\n[![Starting an activity for a result](/media/articles/386/Starting-an-activity-for-a-result.gif)](http://stacktips.com)\n\n# 1. Starting An Activity\n\nWe can call one activity from another by using Intents. Intent is one of the main building block which provides an abstract description of an operation to be performed. `startActivity(intent)` method belongs to your Activity class and can be used for starting a new activity.\n\n```java\n  Intent intent = new Intent(context, YourActivityClass.class);\n  startActivity(intent);\n```\n\n# 2. Starting Activity for Result\n\nStarting another activity doesn’t have to be one-way. You can also start another activity and receive a result back. To receive a result, call `startActivityForResult()` instead of startActivity(). However, the activity that responds must be designed to return a result. When it does, it sends the result as another Intent object. Your activity receives it in the `onActivityResult()` callback.\n\nNote: You can use explicit or implicit intents when you call startActivityForResult(). When starting one of your own activities to receive a result, you should use an explicit intent to ensure that you receive the expected result.\n\n```java\n Intent intent = new Intent(this, SecondActivity.class);\n startActivityForResult(intent, requestCode);\n```\n\nrequestCode is an integer argument, that identifies your request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.\n\n# 3. Passing Result Back\n\nIn secondActivity if you want to send back data:\n\n```java\n Intent returnIntent = new Intent();\n returnIntent.putExtra(\"result\",result);\n setResult(RESULT_OK, returnIntent);\n finish();\n```\n\nIf you don’t want to return data:\n\n```java\n Intent returnIntent = new Intent();\n setResult(RESULT_CANCELED, returnIntent);\n finish();\n```\n\n# 4. Receive the Result\n\nWhen Second Acivity is done with its work and returns the result back, the caller activity’s `onActivityResult()` method gets invoked.\n\nrequestCode: The request code you passed to startActivityForResult().  \n`resultCode`: A result code specified by the second activity. This is either `RESULT_OK` if the operation was successful or `RESULT_CANCELED` if the user backed out or the operation failed for some reason.  \n`resultIntent`: An Intent that carries the result data.\n\n```java\n@Override\nprotected void onActivityResult(int requestCode, int resultCode, Intent data) {\nsuper.onActivityResult(requestCode, resultCode, data);\n    if (requestCode == 1){\n        if(resultCode == RESULT_OK){\n             //here is your result\n            String result=data.getStringExtra(\"result\");\n            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();\n        }\n        if (resultCode == RESULT_CANCELED) {\n            //Write your code if there's no result\n            Toast.makeText(getApplicationContext(), \"Nothing Returned!\", Toast.LENGTH_SHORT).show();\n        }\n    }\n}\n```\n\n# 5. Example\n\nIn this example, we will develop an application with two activities, the first activity will call the second activity for result. The second activity has two buttons; One sends response as “Smile Back” and other doesn’t returns any response.\n\n**activity\\_first.xml**\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"fill_parent\"\n    android:background=\"@drawable/bg\"\n    android:orientation=\"vertical\"\n    android:padding=\"10dp\"\n    tools:context=\".FirstActivity\" \u003e\n\n\u003cTextView\n    android:id=\"@+id/textView1\"\n    android:layout_width=\"wrap_content\"\n    android:layout_height=\"wrap_content\"\n    android:layout_centerHorizontal=\"true\"\n    android:layout_marginTop=\"10dp\"\n    android:text=\"Activity 1\"\n    android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n\u003cButton\n    android:id=\"@+id/start_button\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:layout_alignParentBottom=\"true\"\n    android:layout_centerHorizontal=\"true\"\n    android:background=\"@android:color/holo_blue_dark\"\n    android:text=\"Start Activity 2\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n**activity\\_second.xml**\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"fill_parent\"\n    android:background=\"@drawable/bg\"\n    android:orientation=\"vertical\"\n    android:padding=\"10dp\"\u003e\n\n    \u003cTextView\n        android:id=\"@+id/textView1\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerHorizontal=\"true\"\n        android:layout_marginTop=\"10dp\"\n        android:text=\"Activity 2\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentBottom=\"true\"\n        android:layout_marginTop=\"50dp\"\n        android:orientation=\"horizontal\"\n        android:weightSum=\"2\" \u003e\n\n        \u003cButton\n            android:id=\"@+id/cancel_button\"\n            android:layout_width=\"0dp\"\n            android:layout_height=\"wrap_content\"\n            android:layout_gravity=\"center\"\n            android:layout_margin=\"2dp\"\n            android:layout_weight=\"1\"\n            android:background=\"@android:color/holo_blue_dark\"\n            android:text=\"Cancel\" /\u003e\n\n        \u003cButton\n            android:id=\"@+id/return_button\"\n            android:layout_width=\"0dp\"\n            android:layout_height=\"wrap_content\"\n            android:layout_gravity=\"center\"\n            android:layout_margin=\"2dp\"\n            android:layout_weight=\"1\"\n            android:background=\"@android:color/holo_blue_dark\"\n            android:text=\"Return Results\" /\u003e\n\n    \u003c/LinearLayout\u003e\n\u003c/RelativeLayout\u003e\n```\n\n**FirstActivity.java**\n\n```java\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport android.app.Activity;\nimport android.content.Intent;\n\npublic class FirstActivity extends Activity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_first);\n\n        Button start = (Button) findViewById(R.id.start_button);\n        start.setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View view) {\n                Intent intent = new Intent(FirstActivity.this, SecondActivity.class);\n                startActivityForResult(intent, 1);\n            }\n        });\n    }\n\n    @Override\n    protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n        super.onActivityResult(requestCode, resultCode, data);\n\n        if (requestCode == 1){\n            if(resultCode == RESULT_OK){\n                String result=data.getStringExtra(\"result\");\n                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();\n            }\n            if (resultCode == RESULT_CANCELED) {\n                //Write your co
1de if there's no result\n                Toast.makeText(getApplicationContext(), \"Nothing Returned!\", Toast.LENGTH_SHORT).show();\n            }\n        }\n    }\n\n}\n```\n\n**SecondActivity.java**\n\n```java\npackage com.example.activitytest;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\n\npublic class SecondActivity extends Activity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_second);\n\n        Button returnResult = (Button) findViewById(R.id.return_button);\n        returnResult.setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View view) {\n                // returing result back\n                Intent resultIntent = new Intent();\n                resultIntent.putExtra(\"result\", \"Getting Smile Back!!\");\n                setResult(RESULT_OK, resultIntent);\n                finish();\n\n                // if you don't want to return any result\n                // setResult(RESULT_CANCELED, resultIntent);\n            }\n        });\n\n        Button back = (Button) findViewById(R.id.cancel_button);\n        back.setOnClickListener(new OnClickListener() {\n            @Override\n            public void onClick(View view) {\n                // if you don't want to return any result\n                Intent resultIntent = new Intent();\n                setResult(RESULT_CANCELED, resultIntent);\n                finish();\n            }\n        });\n    }\n}\n```\n\n# 6. Download Complete Example\n\nHere you can download complete eclipse project source code from GitHub.\n\n[Download source](https://github.com/javatechig/javatechig-android-ui/tree/master/ActivityForResults)\n"])</script>
1<script>self.__next_f.push([1,"140:T3263,"])</script>
1<script>self.__next_f.push([1,"\nIn Android user interface is displayed through an activity. Activity is used to represent the data to user and allows user interaction. In an android application, we can have multiple activities and that can interact with each other. During activity interaction we might required to pass data from one activity to other. This tutorial I will explain more about, how to send data while switching between one Activity to another.\n\nFor example, if you are developing an application for RSS News feed reader, you may require having at least of two screens. While the first screen displaying the List of news feeds and other displaying the feed details. Below is the screenshot from the example.\n\n[![pass a data from one Activity to another in Android](/media/articles/387/app_screenshot.gif)](http://stacktips.com)\n\n# 1. Calling one activity from another in android\n\nWe can call one activity from another by using Intents. Intent is one of the main building block which provides an abstract description of an operation to be performed. `startActivity(intent)` method belongs to your Activity class and can be used for starting a new activity.\n\n```java\nIntent intent = new Intent(context, YourActivityClass.class);\nstartActivity(intent);\n```\n\n# 2. Passing data from one activity to other in android\n\nAn intent contains the action and optionally additional data. The data can be passed to other activity using intent p`utExtra()` method. Data is passed as extras and are key/value pairs. The key is always a String. As value you can use the primitive data types int, float, chars, etc. We can also pass `Parceable` and `Serializable` objects from one activity to other.\n\n```java\nIntent intent = new Intent(context, YourActivityClass.class);\nintent.putExtra(KEY, \u003cyour value here\u003e);\nstartActivity(intent);\n```\n\n# 3. Retrieving bundle data from android activity\n\nYou can retrieve the information using `getData()` methods on the Intent object. The Intent object can be retrieved via the `getIntent(`) method.\n\n```java\n  Intent intent = getIntent();\n  if (null != intent) {\n    String stringData= intent.getStringExtra(KEY);\n    int numberData = intent.getIntExtra(KEY, defaultValue);\n    boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);\n    char charData = intent.getCharExtra(KEY, defaultValue);\n  }\n```\n\nTo retrieve `Serializable` and `Parcelable` object using `getSerializableExtra(KEY)` and `getParcelableExtra(KEY)` method.\n\n# 4. Example and case study\n\nIn this example, we will develop one list view of objects and clicking on a list row, it will open up another actiity displaying the detail of that row. Here, we are passing the row data from one activity to other.\n\n## 4.1. Defining case study layouts\n\n**activity\\_news\\_list.xml**\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    tools:context=\".NewsListActivity\" \u003e\n\n    \u003cListView\n        android:id=\"@+id/newsList\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\" \u003e\n    \u003c/ListView\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n**snippet\\_news\\_list\\_row.xml**\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:id=\"@+id/LinearLayout1\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"80dp\"\n    android:orientation=\"vertical\"\n    android:minHeight=\"60dp\"\n     android:background=\"#99CC00\"\n    tools:context=\".NewsListActivity\" \u003e\n\n    \u003cTextView\n        android:id=\"@+id/newsHeadline\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"News Headline\"\n        android:padding=\"5dp\"\n        android:minLines=\"2\"\n        android:maxLines=\"2\"\n        android:textStyle=\"bold\"\n        android:textColor=\"#0000dc\"\n        android:textAppearance=\"?android:attr/textAppearanceMedium\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/pubDate\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginRight=\"19dp\"\n        android:text=\"Published Date\"\n        android:padding=\"3dp\"\n        android:textColor=\"#FF4444\"\n        android:textAppearance=\"?android:attr/textAppearanceSmall\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n**activity\\_news\\_details.xml**\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:id=\"@+id/LinearLayout1\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    tools:context=\".NewsListActivity\" \u003e\n\n    \u003cTextView\n        android:id=\"@+id/headlines\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:padding=\"8dp\"\n        android:text=\"Headline\"\n        android:background=\"#99CC00\"\n        android:textStyle=\"bold\"\n        android:textAppearance=\"?android:attr/textAppearanceMedium\"\n        android:textColor=\"#0000dc\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/pub_date\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:gravity=\"right\"\n        android:padding=\"3dp\"\n        android:text=\"Published Date\"\n        android:textAppearance=\"?android:attr/textAppearanceSmall\"\n        android:background=\"#33B5E5\"\n        android:textColor=\"#0000dc\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/description\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:padding=\"10dp\"\n        android:text=\"News Description\"\n        android:textAppearance=\"?android:attr/textAppearanceMedium\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n## 4.2. Defining Java Classes\n\n**NewsItem.java**\n\n```java\npackage com.javatechig;\n\npublic class NewsItem  {\n\n    private String headline;\n    private String details;\n    private String pubDate;\n\n    public String getHeadline() {\n        return headline;\n    }\n\n    public void setHeadline(String headline) {\n        this.headline = headline;\n    }\n\n    public String getDetails() {\n        return details;\n    }\n\n    public void setDetails(String details) {\n        this.details = details;\n    }\n\n    public String getPubDate() {\n        return pubDate;\n    }\n\n    public void setPubDate(String pubDate) {\n        this.pubDate = pubDate;\n    }\n\n}\n```\n\n**NewsListActivity.java**\n\nHere we render custom list view to show the news items. NewsItems are shown with alternative colors for each rows. When a list row is clicked, we pass the data to NewsDetail
1sActivity using intent extras.\n\n```java\npackage com.javatechig;\n\nimport java.util.ArrayList;\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.view.Menu;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.ListView;\n\npublic class NewsListActivity extends Activity {\n\n    private NewsListAdapter adapter;\n\n    public static final String KEY_HEADLINE=\"news_headline\";\n    public static final String KEY_DETAILS=\"news_details\";\n    public static final String KEY_PUBDATE = \"news_pub_date\";\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_news_list);\n\n        adapter = new NewsListAdapter(this, getData());\n        ListView list = (ListView) findViewById(R.id.newsList);\n        list.setAdapter(adapter);\n\n        list.setOnItemClickListener(new OnItemClickListener() {\n\n            @Override\n            public void onItemClick(AdapterView\u003c?\u003e adapterView, View view, int position, long offset) {\n                NewsItem item = (NewsItem) adapter.getItem(position);\n\n                Intent intent = new Intent(getApplicationContext(), NewsDetailsActivity.class);\n                intent.putExtra(KEY_HEADLINE, item.getHeadline());\n                intent.putExtra(KEY_PUBDATE, item.getPubDate());\n                intent.putExtra(KEY_DETAILS, item.getDetails());\n\n                startActivity(intent);\n            }\n        });\n    }\n\n    private ArrayList\u003cNewsItem\u003e getData() {\n        ArrayList\u003cNewsItem\u003e newsList = new ArrayList\u003cNewsItem\u003e();\n        String[] headlines = getResources().getStringArray(R.array.news_headlines);\n        String[] pubDate = getResources().getStringArray(R.array.news_pubdate);\n        String[] details = getResources().getStringArray(R.array.news_details);\n\n        for (int i = 0; i \u003c headlines.length; i++) {\n            NewsItem item = new NewsItem();\n            item.setHeadline(headlines[i]);\n            item.setPubDate(pubDate[i]);\n            item.setDetails(details[i]);\n            newsList.add(item);\n        }\n        return newsList;\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        getMenuInflater().inflate(R.menu.main, menu);\n        return true;\n    }\n}\n```\n\n**NewsListAdapter.java**\n\nThis adapter will be used for custom list view. Here in this we are using alternative color for each of the list row.\n\n```java\npackage com.javatechig;\n\nimport java.util.ArrayList;\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.BaseAdapter;\nimport android.widget.TextView;\n\npublic class NewsListAdapter extends BaseAdapter {\n\n    private ArrayList\u003cNewsItem\u003e listData;\n    private LayoutInflater layoutInflater;\n    private Context context;\n\n    public NewsListAdapter(Context context, ArrayList\u003cNewsItem\u003e listData) {\n        this.listData = listData;\n        this.context = context;\n        layoutInflater = LayoutInflater.from(context);\n    }\n\n    @Override\n    public int getCount() {\n        return listData.size();\n    }\n\n    @Override\n    public Object getItem(int position) {\n        return listData.get(position);\n    }\n\n    @Override\n    public long getItemId(int position) {\n        return position;\n    }\n\n    public View getView(int position, View convertView, ViewGroup parent) {\n        ViewHolder holder;\n        if (convertView == null) {\n            convertView = layoutInflater.inflate(R.layout.snippet_news_list_row, null);\n            holder = new ViewHolder();\n            holder.headline = (TextView) convertView.findViewById(R.id.newsHeadline);\n            holder.pubDate = (TextView) convertView.findViewById(R.id.pubDate);\n            convertView.setTag(holder);\n        } else {\n            holder = (ViewHolder) convertView.getTag();\n        }\n\n        holder.headline.setText(listData.get(position).getHeadline());\n        holder.pubDate.setText(listData.get(position).getPubDate());\n\n        if (position % 2 == 1) {\n            convertView.setBackgroun
1dColor(context.getResources().getColor(R.color.list_row_color1));\n        } else {\n            convertView.setBackgroundColor(context.getResources().getColor(R.color.list_row_color2));\n        }\n\n        return convertView;\n    }\n\n    static class ViewHolder {\n        TextView headline;\n        TextView pubDate;\n    }\n\n}\n```\n\n**NewsDetailsActivity.java**\n\nIn NewsDetailsActivity we are retrieving the data passed from NewsListActivity.\n\n```java\npackage com.javatechig;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.widget.TextView;\nimport static com.javatechig.NewsListActivity.KEY_HEADLINE;\nimport static com.javatechig.NewsListActivity.KEY_PUBDATE;\nimport static com.javatechig.NewsListActivity.KEY_DETAILS;\n\npublic class NewsDetailsActivity extends Activity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_news_details);\n\n        String headline = \"\";\n        String details = \"\";\n        String pubDate = \"\";\n\n        Intent intent = getIntent();\n        if (null != intent) {\n            headline = intent.getStringExtra(KEY_HEADLINE);\n            details = intent.getStringExtra(KEY_DETAILS);\n            pubDate = intent.getStringExtra(KEY_PUBDATE);\n        }\n\n        TextView headlineTxt = (TextView) findViewById(R.id.headlines);\n        headlineTxt.setText(headline);\n\n        TextView pubdateTxt = (TextView) findViewById(R.id.pub_date);\n        pubdateTxt.setText(pubDate);\n\n        TextView descriptionTxt = (TextView) findViewById(R.id.description);\n        descriptionTxt.setText(details);\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        getMenuInflater().inflate(R.menu.main, menu);\n        return true;\n    }\n}\n```\n\n# 5. Download Complete Example\n\nHere you can download complete eclipse project source code from [**GitHub**](https://github.com/javatechig/Android-UI-Tutorials/tree/master/AndroidBundleExample).\n"])</script>
1<script>self.__next_f.push([1,"141:T116a,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains how to create a HTTP adapter in IBM Worlight and easy steps to deploy on Worklight Server. This example reads feeds from stacktips.com using HTTP Adapter.\n\n## 1. What is an IBM Worklight Adapter?\n\nAdapter is a mediator between mobile applications and enterprise system. Adapters provide an easy and secure access to enterprise system. And it is efficient to provide enterprise data to mobile devices in a uniform data format. The data can be presented to mobile device using various interchange formats like XML or JSON (used mostly)\n\nIBM Worklight provides three different types of adapters\n\n1.  HTTP adapter: HTTP adapters provide access to HTTP-based enterprise services, including RESTful and SOAP-based services.\n2.  SQL adapter: SQL adapters provide access to enterprise databases.\n3.  Cast IRON adapter: Cast Iron adapters initiate orchestrations in IBM Web Sphere Cast Iron.\n\nAdapters are coded in JavaScript and it runs at server-side on the IBM Worklight mobile application platform. IBM internally uses Rhino JavaScript engine for executing the JavaScript source code.\n\n## 2. How to create HTTP adapter?\n\n### **2.1 Architecture of HTTP Adapter**\n\nAdapters are developed using JavaScript and always runs on the IBM Worklight server. When the mobile application makes request to the HTTP adapter, the HTTP adapter sends the web request to the back end web services. As a response the web service returns the response either in json or xml format, and the adapters converts the response to JSON format and sends it to the requested client application.\n\n[![](/media/articles/388/http-adapter-worklight.png)](http://stacktips.com)\n\nIn my example, I am witting an adapter to fetch feeds from stacktips.com. To fetch the feeds I have to connect to [http://stacktips.com/feed/](http://stacktips.com/feed/)\n\n### **2.2 Now let us move to create a HTTP Adapter**\n\n1. Start Eclipse, and create a new Worklight project.\n\n2. Right-click on the newly created Worklight project and then, New-\u003e Worklight Adapter. You require giving the project name, adapter name and choosing HTTP adapter type.\n\n3. Go to the adapter’s folder and then open the newly created adapter xml file. This XML contains the configuration required to connect to the REST Web service from adapter.\n\n4. Change the connection parameters like protocol, domain name and port. See my connection parameter in this example. My xml file after changes\n\n```xml\n\u003cwl:adapter xmlns:wl=\"http://www.worklight.com/integration\"\nxmlns:http=\"http://www.worklight.com/integration/http\"\nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nname=\"JavatechigFeedReader\"\u003e\n   \u003cdisplayName\u003estacktips.com\u003c/displayName\u003e\n   \u003cdescription\u003eJavatechig FeedReader\u003c/description\u003e\n   \u003cconnectivity\u003e\n          \u003cconnectionPolicy xsi:type=\"http:HTTPConnectionPolicyType\"\u003e\n              \u003cprotocol\u003ehttp\u003c/protocol\u003e\n              \u003cdomain\u003estacktips.com\u003c/domain\u003e\n              \u003cport\u003e80\u003c/port\u003e\n          \u003c/connectionPolicy\u003e\n          \u003cloadConstraints maxConcurrentConnectionsPerNode=\"2\"/\u003e\n   \u003c/connectivity\u003e\n\n\u003cprocedure name=\"getFeeds\"/\u003e\n\u003c/wl:adapter\u003e\n```\n\nI have changed domain name to “stacktips.com”\n\nThe xml file lists the procedure declaration for the adapters. It declares all the procedures that the adapter implements. The adapter implementation resides on the JavaScript impl file.\n\n5. Now let us implement the procedure.\n\n```js\nfunction getFeeds() {\n    var input = {\n        method : 'get',\n        returnedContentType : 'xml',\n        path : \"feed\",\n        transformation : {\n            type : 'xslFile',\n            xslFile : 'filtered.xsl'\n        }\n    };\n\n    return WL.Server.invokeHttp(input);\n}\n```\n\n## 3. Testing Adapter Procedures?\n\nRight click on the adapter folder -\u003e run as -\u003e Deploy as Worklight adapter. Once deployed you can see it from the admin console. Open your browser and hit [http://localhost:8080/console/](http://localhost:8080/console/)\n\nNow, RunAs-\u003e Invoke Worklight procedure. Select the procedure to test. For now you can test for getFeeds, results will appear as JSON data.\n\n[![](/media/articles/388/testing-http-adapter.png)](http://stacktips.com)\n\n## 4. How to invoke worklight Adapter Procedure?\n\nRefer my earlier post [**“Invoking Adapter procedure in IBM Worklight”**](http://stacktips.com/2013/03/22/invoking-adapter-procedure-in-ibm-worklight/)\n\n## 5. References\n\n[http://pic.dhe.ibm.com/infocenter/wrklight](http://pic.dhe.ibm.com/infocenter/wrklight)\n"])</script>
1<script>self.__next_f.push([1,"142:T16df,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial will help you to understand the Adapters in IBM Worklight and Invoking Adapter procedure in IBM Worklight from Javascript client code. Here to make my post simplified, I am continuing my previous post [How to create an SQL Adapter in IBM Worklight](http://stacktips.com/2013/03/18/how-to-create-a-sql-adapter-in-ibm-worklight/) refer the same before reading this post.\n\n## 1. What is an IBM Worklight Adapter?\n\nAdapter is a mediator between mobile applications and enterprise system. Adapters provide an easy and secure access to enterprise system. And it is efficient to provide enterprise data to mobile devices in a uniform data format. The data can be presented to mobile device using various interchange formats like XML or JSON (used mostly)\n\nIBM Worklight provides three different types of adapters\n\n1.  HTTP adapter: HTTP adapters provide access to HTTP-based enterprise services, including Restful and SOAP-based services.\n2.  SQL adapter: SQL adapters provide access to enterprise databases.\n3.  Cast IRON adapter: Cast Iron adapters initiate orchestrations in IBM Web Sphere Cast Iron.\n\nAdapters are coded in JavaScript and it runs at server-side on the IBM Worklight mobile application platform. IBM internally uses Rhino JavaScript engine for executing the JavaScript source code.\n\n## 2. How to create SQL Adapter?\n\nRefer my previous post for [creating SQL Adapter in IBM Worklight.](http://stacktips.com/2013/03/18/how-to-create-a-sql-adapter-in-ibm-worklight/)\n\n## 3. How to invoke Adapter Procedure?\n\nLet us understand a bit before going much into coding.Worklight application can communicate with adapters by making the procedure calls. Typically while making a server call from java script we end up with getting the problem of cross origin proxy browser security issues. But IBM Worklight application architecture is design avoids the same-origin constraints and can make procedure call with the adapters deployed on IBM Worklight server.\n\nThe invocation of adapter procedure involved two basic configurations\n\n1.  Preparing invocationData object\n2.  Invoking procedure from the application\n\n### **3.1. Prepare an invocationData object**\n\nInvocationData object is used to provide the invocation configuration information. The configuration parameters are being configured as a JSON object. Preparing invocationData object requires three configuration parameters i.e. adapter name, procedure name and parameters to be passed. For parameters, leave empty array if your procedure is not expecting.\n\n```javascript\nvar invocationData = {\n        adapter : 'StudentInfo', // adapter name\n        procedure : 'getStudentInfos', // procedure name\n        parameters : [] // parameters if any\n};\n```\n\nHere in this example, I am trying to invoke the SQL adapter created in my previous post.\n\n### **3.2. Invoking a procedure from the application**\n\nWe can invoke a procedure from the client application using `WL.Client.invokeProcedure` method. This method take invocationData and call back methods. The call back methods are the failure or success callbacks.\n\n```javascript\nWL.Client.invokeProcedure(invocationData,{\n        onSuccess : loadSQLQueerySuccess, //success callback\n        onFailure : loadSQLQueeryFailure // failure callback\n});\n```\n\nOn succesful invocation of adapter procedure the success callback is getting called with the JSON response. The success JSON response contains the status code and the invocationResult object. Below is the format of JSON, I have received from my SQL Adapter.\n\n```json\n{\n   \"status\":200,\n   \"invocationContext\":null,\n   \"invocationResult\":{\n      \"responseID\":\"8\",\n      \"isSuccessful\":true,\n      \"resultSet\":[\n         {\n            \"sgrade\":\"A+\",\n            \"sid\":\"PUC001\",\n            \"sclass\":\"PUC\",\n            \"sname\":\"Rohan\"\n         },\n         {\n            \"sgrade\":\"A\",\n            \"sid\":\"PUC002\",\n            \"sclass\":\"PUC\",\n            \"sname\":\"Rakesh\"\n         },\n         {\n            \"sgrade\":\"C\",\n            \"sid\":\"PUC003\",\n            \"sclass\":\"PUC\",\n            \"sname\":\"Raj\"\n         },\n         {\n            \"sgrade\":\"E\",\n            \"sid\":\"PUC004\",\n            \"sclass\":\"PUC\",\n            \"sname\":\"Roman\"\n         }\n      ]\n   }\n}\n```\n\nOn failure callback, another JSON object is being returned with the error code, and error message and HTTP response status code.\n\n## 4. Complete code Snippet\n\n```javascript\nfunction loadSQLRecords(){\n    var invocationData = {\n        adapter : 'StudentInfo',\n        procedure : 'getStudentInfos',\n        parameters : []\n    };\n\n    WL.Client.invokeProcedure(invocationData,{\n        onSuccess : loadSQLQueerySuccess,\n        onFailure : loadSQLQueeryFailure\n    });\n}\n\nfunction loadSQLQueerySuccess(result){\n    WL.Logger.debug(\"Retrieve success\" +  JSON.stringify(result));\n    displayFeeds(result.invocationResult.resultSet);\n}\n\nfunction loadSQLQueeryFailure(result){\n    WL.Logger.error(\"Retrieve failure\");\n}\n```\n\n## 5. Updating UI with results\n\nTo make the example more simplified, I am just creating an simple list and printing the data in rows. You can also have your user interface more beautified using your skills in JQueery, Sencha or any other frameworks. For now below is my code\n\n```javascript\nfunction displayFeeds(items){\n         var ul = $('#
1itemsList');\n         for (var i = 0; i \u003c items.length; i++) {\n              var li = $('\u003cli/\u003e').html(items[i].sid);\n              li.append($('\u003cli/\u003e').html(items[i].sname));\n              li.append($('\u003cli/\u003e').html(items[i].sgrade));\n              li.append($('\u003chr\u003e'));\n              ul.append(li);\n        }\n}\n```\n\n## 6. Output\n\nNow we are done, just deploy your application and then check the results.\n\n[![](/media/articles/389/worklight-console.png)](http://stacktips.com)\n\n[![](/media/articles/389/sql-adapter-procedure-output.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"143:T2190,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial will explain Struts2 Localization, internationalization (i18n) with Example. We will build a sample internationalized web application with support for English, French and Japanese.\n\n# Introduction to Internationalization\n\nInternationalization is the process designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization helps to build internationalized software for a specific region or language by adding locale-specific components and translating text. You can call internationalization as translation or localization. Internationalization is abbreviated i18n because the word starts with i and ends with an n, and there are 18 characters between the first i and the last n.\n\nFor example, while making a search in Google, the expected results appear in different languages based on region. Not just the search result, you will find the Google page menus display as selected language.\n\n# Internationalizing (i18n) / Localization (i10n)\n\nStruts2 provides localization i.e. internationalization (i18n) support through resource bundles, interceptors and tag libraries. Here in this tutorial we will learn to build internationalized application using resource bundle. Resource bundle is a flat file that contains key-value pairs.\n\n**English Resource Bundle**\n\n| Key | Value |\n| --- | --- |\n| key_name | value_value |\n| key_name | value_value |\n\n**French Resource Bundle**\n\n| Key | Value |\n| --- | --- |\n| key_name | value_value |\n| key_name | value_value |\n\nHere the key-value plays major role to adapting the locale language. The key values resource bundle files need to be developed for each of the supporting locale.\n\n# Internationalizing uses in following places:\n\n-   UI Tags\n-   Messages \u0026 Errors from validation interface\n-   getText() method\n\n# Retrieve message from resource bundle:\n\n**1. getText()**\n\n\u003cs:property value=”getText(‘msg.key’)” /\u003e\n\n**2. Key attribute**\n\n\u003cs:textfield key=”msg.key” /\u003e\n\n# Resource Bundle:\n\nThe resource bundle is used to keep the key and value pairs for respective languages such as English Resource Bundle can have value as English Text and France Resource Bundle can have value as France Text but the keys are same across.\n\nResource Bundle can be place in the following places\n\n1.  ActionClass.properties\n2.  Interface.properties\n3.  BaseClass.properties\n4.  ModelDriven’s Model\n5.  Package.properties\n6.  I18n message key\n7.  Global resource properties\n\nThe resource properties are being searched in the above order. At first it looks the resource properties with action class name.properties, if does not found then it looks for interface.properties else goes on till Global resource properties.\n\n**UTF-8:** It represents characters in the Unicode character set.\n\n**Call Flow:** On selecting language the UI will render with respective language.\n\n**Software and tools required**\n\n1.  JAVA 1.6\n2.  Tomcat 6\n3.  Eclipse 3.6\n\n# Steps to create Web Application to support multi-language\n\n1.  Create dynamic web application in eclipse named as **struts2localization**.\n2.  Configure the project with Struts2Framework (refer previous example)\n3.  Modify the **struts.xml** as follows to enable the framework to use resource bundle\n\nAdd the following line just above the package element.\n\n**\u003cconstant name=”struts.custom.i18n.resources” value=”global” /\u003e**\n\n**Value:** Prefix name of resource bundle. I am using global.\n\n```xml\n\u003cstruts\u003e\n    \u003cconstant name=\"struts.custom.i18n.resources\" value=\"global\" /\u003e\n\u003cpackage name=\"struts2web\" namespace=\"/\" extends=\"struts-default\"\u003e\n\u003caction name=\"login\"\u003e\n    \u003cresult\u003epages/login.jsp\u003c/result\u003e\n\u003c/action\u003e\n\u003caction name=\"changelang\"\n        class=\"com.javatechig.struts2web.actions.ChangeLocaleAction\"\u003e\n\u003cresult name=\"success\"\u003epages/login.jsp\u003c/result\u003e\n\u003c/action\u003e\n\u003c/package\u003e\n\u003c/struts\u003e\n```\n\n**4. Create resource properties file as follows under src folder**\n\nNaming Conventions – **prefix\\_lang.properties**\n\n**a. English**\n\nglobal.properties  \nkey : login.here value: Login Here  \nkey : login.user value: User  \nkey : login.password value: Password  \nkey: login.submit value: Login\n\n**b. French**\n\nglobal\\_fr.properties  \nkey : login.here value: Connectez-vous ici  \nkey : login.user value: utilisateur  \nkey : login.password value: mot de passé  \nkey: login.submit value: Connexion\n\n**c. Japanese**\n\nglobal\\_ja.properties  \nkey : login.here value: ここにログイン  \nkey : login.user value: ユーザー  \nkey : login.password value: パスワード  \nkey: login.submit value: ログイン\n\nHere you can observe that keys are same across all file but the value changes as per the language. The language which contains 
1non-English alphabet like Japanese should use Unicode instead of actual characters.\n\n**global\\_ja.properties**\n\n```text\n  key: login.here      value: \\u3053\\u3053\\u306B\\u30ED\\u30B0\\u30A4\\u30F3\n  key: login.user      value: \\u30E6\\u30FC\\u30B6\\u30FC\n  key: login.password  value: \\u30D1\\u30B9\\u30EF\\u30FC\\u30C9\n  key: login.submit    value: \\u30ED\\u30B0\\u30A4\\u30F3\n```\n\n**5. Create Login.jsp with language options as follows**\n\n```html\n\u003c%@ page contentType=\"text/html; charset=UTF-8\"%\u003e\n\n\u003cs:form action=\"loginauth\" theme=\"simple\"\u003e\n\u003ccenter\u003e\n    \u003ctable width=\"300\"\u003e\n        \u003ctr height=\"30\"\u003e\n            \u003ctd width=\"300\" colspan=\"2\"\u003e\n                \u003cs:a href=\"changelang?lang=en\" \u003eEnglish\u003c/s:a\u003e\n                \u003cs:a href=\"changelang?lang=fr\" \u003eFrance\u003c/s:a\u003e\n                \u003cs:a href=\"changelang?lang=ja_JP\" \u003eJapanese\u003c/s:a\u003e\n            \u003c/td\u003e\n        \u003c/tr\u003e\n        \u003ctr\u003e\n            \u003ctd colspan=\"2\" width=\"300\" align=\"left\" style=\"background:#eee\"\u003e\u003cs:property value=\"getText('login.here')\" /\u003e\u003c/td\u003e\n        \u003c/tr\u003e\n        \u003ctr\u003e\n            \u003ctd align=\"left\" width=\"100\"\u003e\u003cs:property value=\"getText('login.user')\" /\u003e:\u003c/td\u003e\u003ctd align=\"left\"\u003e\u003cs:textfield name=\"userId\"/\u003e\u003c/td\u003e\n        \u003c/tr\u003e\n        \u003ctr\u003e\n            \u003ctd align=\"left\"\u003e\u003cs:property value=\"getText('login.password')\" /\u003e:\u003c/td\u003e\u003ctd align=\"left\"\u003e\u003cs:password type=\"text\" name=\"password\"/\u003e\u003c/td\u003e\n        \u003c/tr\u003e\n        \u003ctr\u003e\n            \u003ctd align=\"left\"\u003e\u003c/td\u003e\u003ctd align=\"right\"\u003e\u003cs:submit key=\"login.submit\" name=\"submit\" /\u003e\u003c/td\u003e\n        \u003c/tr\u003e\n    \u003c/table\u003e\n\u003c/center\u003e\n\u003c/s:form\u003e\n```\n\nHere I have added three language options i.e. English, France and Japanese.\n\n```html\n\u003cs:a href=\"changelang?lang=en\" \u003eEnglish\u003c/s:a\u003e\n\u003cs:a href=\"changelang?lang=fr\" \u003eFrance\u003c/s:a\u003e\n\u003cs:a href=\"changelang?lang=ja\" \u003eJapanese\u003c/s:a\u003e\n```\n\n**changelang** – is the action name which is mapped with ChangeLocaleAction in struts.xml.  \nlang – is the parameter to get selected language.\n\nHere is the code to display text in different language in JSP  \n**\u003c%@ page contentType=”text/html; charset=UTF-8″%\u003e** : This tag should be include in all pages where Multilanguage is required to display.\n\nGet Message from resource bundle:\n\n```html\n\u003cs:property value=\"getText('login.user')\" /\u003e\n\u003cs:submit key=\"login.submit\" name=\"submit\" /\u003e\n```\n\nThe above are used to get the message from resource bundle.  \ngetText(String s) : It searches the key(‘login.user’) in the resource bundle and returns the respective value or null if none is found. This can be used as label in the UI.  \nKey : This helps to retrieve the value from resource bundle using key (‘login.submit’). This is used in html field element like TextField and button etc.\n\n**6. Create ChangeLocaleAction.java in com.javatechig.struts2web.actions**\n\n```java\nLocale locale = new Locale(lang);\nActionContext.getContext().setLocale(locale);\n```\n\n**lang** : It is the parameter to get the language  \n**Locale** : It is from java util package.  \nsetLocale : It set the locale object to actionContext which is accessible by resource throughout the context.\n\n**7. Output of the code sample**\n\n**Finally the eclipse project structures looks as follows**\n\n[![Struts2 Localization and Internationalization Example](/media/articles/390/Struts2-Localization-and-Internationalization-Example.png)](http://stacktips.com)\n\n**Output in English by default**  \n[![Struts2 Localization and Internationalization Example output](/media/articles/390/Struts2-Localization-and-Internationalization-Example-output1.png)](http://stacktips.com)\n\n**Output in**France\n\n[
1![Struts2 Localization and Internationalization Example output French](/media/articles/390/Struts2-Localization-and-Internationalization-Example-output-French.png)](http://stacktips.com)\n\n**Output in Japanese**\n\n[![Struts2 Localization and Internationalization Example japnese](/media/articles/390/Struts2-Localization-and-Internationalization-Example-japnese1.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"144:T2ddc,"])</script>
1<script>self.__next_f.push([1,"\n## 1. Introduction\n\nGridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. In this tutorial, we will build an image gallery using Android GridView. Each grid in our example will display an image and a text tile.\n\nCheckout the advance version of this tutorial, that downloads the data from server and displays it on GridView.  \n[Download and Display Image in Android GridView](/articles/download-and-display-image-in-android-gridview)\n\nWhen user clicks on any grid item, it will navigate user to the details page. The output of the example we will build is depicted in following image.\n\n[![Android GridView Example](/media/articles/391/Android-GridView-Example.jpg)](http://stacktips.com)\n\n## 2. Adding GridView layout\n\nTo begin with, let us create a layout for activity that contains a GridView. Let us create a new file named activity\\_main.xml in your application layout folder.\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:background=\"#f0f0f0\"\u003e\n\n    \u003cGridView\n        android:id=\"@+id/gridView\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"5dp\"\n        android:columnWidth=\"100dp\"\n        android:drawSelectorOnTop=\"true\"\n        android:gravity=\"center\"\n        android:numColumns=\"auto_fit\"\n        android:stretchMode=\"columnWidth\"\n        android:verticalSpacing=\"5dp\"\n        android:focusable=\"true\"\n        android:clickable=\"true\"/\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\nNotice that in the above code, we have added a GridView with id gridView, and used some of the attributes such as numColumns, stretchMode, verticalSpacing, etc. Most of the android attributes are self explanatory.\n\n## 3. Define grid item layout\n\nAs you can notice from the above screenshot, each of the grid item contains an `ImageView` and an `TextView`. The following listing will show you the layout for each grid cell item. This layout will be used by the GridView adapter to render the items. Create a new layout inside your project layout directory and name it as `grid_item_layout.xml`.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"wrap_content\"\n    android:layout_height=\"wrap_content\"\n    android:layout_marginTop=\"5dp\"\n    android:background=\"@drawable/grid_color_selector\"\n    android:orientation=\"vertical\"\n    android:padding=\"5dp\"\u003e\n\n    \u003cImageView\n        android:id=\"@+id/image\"\n        android:layout_width=\"100dp\"\n        android:layout_height=\"100dp\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/text\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginTop=\"5dp\"\n        android:gravity=\"center\"\n        android:textSize=\"12sp\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n## 4. Creating GridView adapter\n\nAdapter is acts as a bridge between data source and adapter views such as ListView, GridView. Adapter iterates through the data set from beginning till the end and generate Views for each item in the list.\n\nAndroid SDK provides three different Adapter implementation, that includes `ArrayAdapter`, `CursorAdapter`and `SimpleAdapter`. An ArrayAdapter expects an Array or an List as input, while CursorAdapter accepts the instance of Cursor and SimpleAdapter maps the static data defined in the resources. The type of adapter that suits your app need is purely based on the input data type.\n\nThe BaseAdapter is the generic implementation for all of the three adapter types and can be used for ListView, GridView or for Spinners. You may directly use ArrayAdapter by passing array as input or create your own customized class by extending BaseAdapter.\n\nLet us not proceed with creating a custom adapter for grid view by extending ArrayAdapter. Create a new class GridViewAdapter.java in in your application src directory.\n\n```java\npublic class GridViewAdapter extends ArrayAdapter {\n    private Context context;
1\n    private int layoutResourceId;\n    private ArrayList data = new ArrayList();\n\n    public GridViewAdapter(Context context, int layoutResourceId, ArrayList data) {\n        super(context, layoutResourceId, data);\n        this.layoutResourceId = layoutResourceId;\n        this.context = context;\n        this.data = data;\n    }\n\n    @Override\n    public View getView(int position, View convertView, ViewGroup parent) {\n        View row = convertView;\n        ViewHolder holder = null;\n\n        if (row == null) {\n            LayoutInflater inflater = ((Activity) context).getLayoutInflater();\n            row = inflater.inflate(layoutResourceId, parent, false);\n            holder = new ViewHolder();\n            holder.imageTitle = (TextView) row.findViewById(R.id.text);\n            holder.image = (ImageView) row.findViewById(R.id.image);\n            row.setTag(holder);\n        } else {\n            holder = (ViewHolder) row.getTag();\n        }\n\n        ImageItem item = data.get(position);\n        holder.imageTitle.setText(item.getTitle());\n        holder.image.setImageBitmap(item.getImage());\n        return row;\n    }\n\n    static class ViewHolder {\n        TextView imageTitle;\n        ImageView image;\n    }\n}\n```\n\nThe getView() method implementation is necessary, it is responsible for creating a new View for each grid item. When this is called, a View is passed in, which is normally a recycled object, so there’s a check to see if the object is null. If it is null, an ViewHolder is instantiated and configured for holding an ImageView and a TextView. ViewHolder design patterns are efficient while using composite layouts.\n\nNotice that the above adapter is working on a ImageItem pojo Class. Create a new class for ImageItem and add the following code snippets.\n\n```java\npublic class ImageItem {\n    private Bitmap image;\n    private String title;\n\n    public ImageItem(Bitmap image, String title) {\n        super();\n        this.image = image;\n        this.title = title;\n    }\n\n    public Bitmap getImage() {\n        return image;\n    }\n\n    public void setImage(Bitmap image) {\n        this.image = image;\n    }\n\n    public String getTitle() {\n        return title;\n    }\n\n    public void setTitle(String title) {\n        this.title = title;\n    }\n}\n```\n\n## 5. Setting adapter to GridView\n\nNow we are almost ready to hook up grid view on activity. In our activity we will initialize the GridView by calling `findViewById(int)` method. This method takes the same id as provided in the layout xml file. The `setAdapter()` method then sets a custom adapter (GridViewAdapter) as the source for all items to be displayed in the grid.\n\n```java\npublic class MainActivity extends ActionBarActivity {\n    private GridView gridView;\n    private GridViewAdapter gridAdapter;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        gridView = (GridView) findViewById(R.id.gridView);\n        gridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, getData());\n        gridView.setAdapter(gridAdapter);\n    }\n\n    // Prepare some dummy data for gridview\n    private ArrayList\u003cImageItem\u003e getData() {\n        final ArrayList\u003cImageItem\u003e imageItems = new ArrayList\u003c\u003e();\n        TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);\n        for (int i = 0; i \u003c imgs.length(); i++) {\n            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imgs.getResourceId(i, -1));\n            imageItems.add(new ImageItem(bitmap, \"Image#\" + i));\n        }\n        return imageItems;\n    }\n}\n```\n\nNote that in this example, we are using the static data and image defined in strings.xml file. All the images used in this example is available for download. Visit download section to get the complete project source code.\n\nAt this point we can run the application and and can see the grid view in action.\n\n## 6. Handling GridView click action\n\nWhen user click on any grid item, we have to take user to details activity by passing the image and title of the grid item clicked. To do this we can call `setOnItemClickListener()` method by passing the instance of OnItemClickListener.\n\n```java\ngridView.setOnItemClickListener(new OnItemClickListener() {\npublic void onItemClick(AdapterVie
1w\u003c?\u003e parent, View v, int position, long id) {\n    ImageItem item = (ImageItem) parent.getItemAtPosition(position);\n    //Create intent\n    Intent intent = new Intent(MainActivity.this, DetailsActivity.class);\n    intent.putExtra(\"title\", item.getTitle());\n    intent.putExtra(\"image\", item.getImage());\n\n    //Start details activity\n    startActivity(intent);\n}\n```\n\nLearn  more about [passing data from one activity](/articles/pass-a-data-from-one-activity-to-another-in-android \"How to pass a data from one Activity to another in Android\") to another here.\n\n## 7. Customizing GridView style\n\nWe are pretty much good with the GridView gallery, let us do some customization such as changing the background color of a grid item while user is clicks.\n\nFor this, let us define a color selector `grid_color_selector.xml` and place it inside drawable folder. We can use a selector with `grid_row.xml` layout file by using `android:background` attribute.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cselector xmlns:android=\"http://schemas.android.com/apk/res/android\"\u003e\n    \u003citem android:drawable=\"@color/blue\" android:state_pressed=\"true\"/\u003e\n    \u003citem android:drawable=\"@color/blue\" android:state_selected=\"true\"/\u003e\n    \u003citem android:drawable=\"@color/white\"/\u003e\n\u003c/selector\u003e\n```\n\n## 8. Creating details activity\n\nCreate a new layout file named `details_activity.xml`. This will be used for the layout for my DetailsActivity.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cFrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    android:background=\"#000\"\u003e\n\n    \u003cImageView\n        android:id=\"@+id/image\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:layout_gravity=\"center\"\n        android:scaleType=\"fitCenter\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/title\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"bottom\"\n        android:background=\"#00000c\"\n        android:padding=\"10dp\"\n        android:textColor=\"#fff\"\n        android:textSize=\"20dp\" /\u003e\n\u003c/FrameLayout\u003e\n```\n\nThe above layout is quite simple with an ImageView for displaying full sized image and TextView for displaying the title. Now let us crete DetailsActivity and use the above layout to display the selected image.\n\n```java\npublic class DetailsActivity extends ActionBarActivity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.details_activity);\n\n        String title = getIntent().getStringExtra(\"title\");\n        Bitmap bitmap = getIntent().getParcelableExtra(\"image\");\n\n        TextView titleTextView = (TextView) findViewById(R.id.title);\n        titleTextView.setText(title);\n\n        ImageView imageView = (ImageView) findViewById(R.id.image);\n        imageView.setImageBitmap(bitmap);\n    }\n}\n```\n\nWell, we have now completed the whole exercise to build image gallery using Android GridView. If you find any problem, or something is missing, you can download code and compare your code with mine.\n\n## 9. Download Complete Example\n\n[Download source](https://github.com/javatechig/Android-GridView-Example)\n"])</script>
1<script>self.__next_f.push([1,"145:T1573,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial will help you to understand the SQL adapter and to create a SQL adapter from IBM Worklight. Here it provided step by step tutorials to create, implement and test an adapter using IBM Worklight.\n\n## 1. What is SQL Adapter?\n\nAdapter is a mediator between mobile applications and enterprise system. Adapters provide an easy and secure access to enterprise system. And it is efficient to provide enterprise data to mobile devices in a uniform data format. The data can be presented to mobile device using various interchange formats like XML or JSON (used mostly)\n\nIBM Worklight provides three different types of adapters\n\n1.  HTTP adapter: HTTP adapters provide access to HTTP-based enterprise services, including RESTful and SOAP-based services.\n2.  SQL adapter: SQL adapters provide access to enterprise databases.\n3.  Cast IRON adapter: Cast Iron adapters initiate orchestrations in IBM Web Sphere Cast Iron.\n\nAdapters are coded in JavaScript and it runs at server-side on the IBM Worklight mobile application platform. IBM internally uses Rhino JavaScript engine for executing the JavaScript source code.\n\n[![](/media/articles/392/adapter-archiecture.png)](http://stacktips.com)\n\nConceptually, an adapter is a set of JavaScript functions that can be remotely invoked by an application. Typically an adapter consist of and xml file and a JavaScript implementation file. The XML file will be used for configuring connectivity from the adapter to the enterprise system. Each of the procedures for the adapters needs to be defined in this xml. The JavaScript file will contain the implementation for each of the adapter procedure. Once you are done with the two files we can now deploy and then can test.\n\nThe two files are bundled into a .adapter archive file that is then deployed to the IBM Worklight Server. Once deployed, the adapter procedures are ready to be invoked by Worklight applications running on mobile devices and in browsers.\n\nIn this below example, you will find an SQL adapter working.\n\n## 2. Creating an SQL adapter in IBM Worklight\n\nHere at this point, I assume that your IBM Worklight development environment is ready and working.\n\n### **2.1. Creating a new Worklight project**\n\nCreate a simple Worklight project. Choose project template as “Hybrid Application” and provide an application name. Here I have used “SQLAdapterSampleApp”\n\n[![](/media/articles/392/adapter-newproject.png)](http://stacktips.com)\n\n[![](/media/articles/392/adapter-new-application.png)](http://stacktips.com)\n\n### **2.2. Creating new Worklight Adapter**\n\nClick on “adapter” folder and then New-\u003e Worklight Adapter. You can see a dialog as shown below.\n\n[![](/media/articles/392/adapter-new-sql-adapter.png)](http://stacktips.com)\n\n### **2.3. Create required tables and data in database**\n\nNow let us move to the mysql part. We need to have the database server running. I assume that you have installed the mysql and have a database running. Create a table with and fill with some data. You may use the below SQL command\n\n```sql\nUSE `ibmworklight`;\nDROP TABLE IF EXISTS `studentinfo`;\nCREATE TABLE `studentinfo` (`sid` varchar(20), `sname` varchar(20), `sclass` varchar(20), `sgrade` varchar(20));\nINSERT INTO `studentinfo` ( `sid`, `sname`, `sclass`, `sgrade`) values ('PUC001','Rohan','PUC', 'A+');\nINSERT INTO `studentinfo` ( `sid`, `sname`, `sclass`, `sgrade`) values ('PUC002','Rakesh','PUC', 'A');\nINSERT INTO `studentinfo` ( `sid`, `sname`, `sclass`, `sgrade`) values ('PUC003','Raj','PUC', 'C');\nINSERT INTO `studentinfo` ( `sid`, `sname`, `sclass`, `sgrade`) values ('PUC004','Roman','PUC', 'E');\nselect * from `studentinfo`;\n```\n\nBy now, we are ready with the database and table setup.\n\n### **2.4. Configuring adapter xml**\n\nOpen your adapter .xml file. We need to change the database configurations. Driver calss is used to connect to the database from your project. Mysql database use “com.mysql.jdbc.Driver” class.\n\n**_Note: You have to include “mysql-connector-java-5.1.24-bin.jar” library. If you don’t have one, then download here_****[Download](http://dev.mysql.com/downloads/connector/j/)**\n\nAs I am running my database in my local system, I have provided localhost and default port as 3306.\n\n```xml\n\u003cdataSourceDefinition\u003e\n\n\u003cdriverClass\u003ecom.mysql.jdbc.Driver\u003c/driverClass\u003e\n\n\u003curl\u003ejdbc:mysql://localhost:3306/ibmworklight\u003c/url\u003e\n\n\u003cuser\u003eroot\u003c/user\u003e\n\n\u003cpassword\u003eroot\u003c/password\u003e\n\n\u003c/dataSourceDefinition\u003e\n```\n\n### 2.5. Defining Worklight Procedures\n\nNow, For making my explanation simplified, I am implementing only one procedure. Here in my example “getStudentInfos” procedures fetches all of the available records from “studentinfo” table.\n\n```javascript\nvar selectStatement = WL.Server.createSQLStatement
1(\"select * from studentinfo\");\nfunction getStudentInfos() {\n\n    return WL.Server.invokeSQLStatement({\n        preparedStatement : selectStatement,\n        parameters : []\n    });\n}\n```\n\nNow we are done.\n\n## 3. Testing my SQLAdapter\n\nRight click on the adapter folder -\u003e run as -\u003e Deploy as Worklight adapter. Once deployed you can see it from the admin console. Open your browser and hit [http://localhost:8080/console/](http://localhost:8080/console/). You will see the console window as shown below.\n\n[![](/media/articles/392/adapter-ibl-worklight-console.png)](http://stacktips.com)\n\nNow, RunAs-\u003e Invoke Worklight procedure. Select the procedure to test. For now you can test for getStudentInfos, results will appear as JSON data.\n"])</script>
1<script>self.__next_f.push([1,"146:T10b4,"])</script>
1<script>self.__next_f.push([1,"\n# What is enum in java?\n\nAn enumeration is a special class, which provides a type-safe implementation of constant data in a java program. Java enum type is introduced in Java 5.0. It is used to restrict a variable only a predefined values from an enumerated list. The items in the enumerated list are called enums.\n\nFor example, a MercedesBenz color can be out of only three available colors WHITE, RED, and SILVER. In this context we can take a enum data type for representing the color of MercedesBenz.\n\n```java\n  enum BenzColors {WHITE, RED, SILVER};\n```\n\nFor the above requirement, we can also do it by declaring an int, byte or string type for the color validation. But, this requires an extra effort to check the infeasible types. Here enum can help to reduce the bugs in your code. Compiler will stop you from assigning values other then three defined enums.\n\n# Declaring enum in java\n\nEnum can be declared as their own class or can be enclosed inside another class. It is not required to declare the constants are in all caps, but we are following java code convention, that the constants need to be in upper case. In the above code syntax the enum constants are `WHITE`, `RED` and `SILVER`.\n\n## Declaring an enum outside a class\n\n```java\nenum BenzColors {WHITE, RED, SILVER}\n\npublic class MercedesBenz {\n    private BenzColors color;\n\n    public void setColor(BenzColors color){\n        this.color = color;\n    }\n\n    public BenzColors getColor() {\n        return color;\n    }\n\n    public static void main(String[] args) {\n        MercedesBenz benz = new MercedesBenz();\n        benz.setColor(BenzColors.RED);\n        System.out.println(benz.getColor());\n    }\n\n}\n```\n\n## Declaring an enum as a part of class\n\n```java\npublic class MercedesBenz {\n    enum BenzColors {WHITE, RED, SILVER}\n    private BenzColors color;\n\n    public void setColor(BenzColors color){\n        this.color = color;\n    }\n\n    public BenzColors getColor() {\n        return color;\n    }\n\n    public static void main(String[] args) {\n        MercedesBenz benz = new MercedesBenz();\n        benz.setColor(BenzColors.RED);\n        System.out.println(benz.getColor());\n    }\n\n}\n```\n\n# Declaring Constructor, Member Variables and Methods in Enum in Java\n\nAn enum is a special class, which holds a reference to memory in the heap. It is implicitly final, because the constants should not be changed. It can include other component of a traditional class, such as constructors, member variables and methods. Each enum constant can be declared with parameters to be passed to the constructor when it is created.\n\nLet us go back to our MercedesBenz example, the enum constants represents the three color variants. But what if we want to map some other value like color production ratios along with the color constants. We like to know how many RED color Benz are out of available in the production firm.\n\n```java\nenum BenzColors {\n    WHITE(20), RED(40), SILVER(40);\n\n    private final int colorRatio;\n\n    private BenzColors(int colorRatio) {\n        this.colorRatio = colorRatio;\n    }\n\n    public int getColorRatio() {\n        return colorRatio;\n    }\n};\n\npublic class MercedesBenz {\n\n    private BenzColors color;\n\n    public void setColor(BenzColors color){\n        this.color = color;\n    }\n\n    public BenzColors getColor() {\n        return color;\n    }\n\n    public static void main(String[] args) {\n        MercedesBenz benz = new MercedesBenz();\n        benz.setColor(BenzColors.RED);\n        System.out.println(benz.getColor()); // prints RED\n        System.out.println(benz.getColor().getColorRatio()); // prints 40\n    }\n\n}\n```\n\nDo You Know ?\n\n-   enum cannot be declared inside a method. It can be declared inside a class or as its separate context.\n-   It is optional to put a semicolon to the end of enum declaration.\n-   Each of the enumerated constants are actually instances of enum class. And they represent static and final.\n-   Each enum values knows index of its position. The order in which the constants are declared matters.\n-   enum constructor cannot be directly invoked. The enum constructors are invoked automatically with the constant value you define during declaration.\n-   More than one argument to the constructor can be defined\n-   Enum constructor can be overloaded\n"])</script>
1<script>self.__next_f.push([1,"147:T2608,"])</script>
1<script>self.__next_f.push([1,"\nStrings are sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings.\n\n# 1. How to creating new String?\n\nA new String can be created using two approaches.\n\n1.  String literal\n2.  Using String class constructor\n\n## 1.1. Creating a new String by literals\n\nA string class object can be created by directly assigning values. Each time you create a string it checks for the string value in the String pool, if the reference exists inside pool then the reference to the existing string from the pool is returned. If the pool doesn’t, contain the reference, then a new String object is formed and dumped to the pool.\n\n```java\n //creating string by using literals\n  String string1 = \"Raj\";\n  String string2 = \"Raj\";\n  String string3 = \"Adam\";\n```\n\n[![Java String Complete Tutorial](/media/articles/394/Java-String-Complete-Tutorial.png)](http://stacktips.com)\n\n## 1.2. Creating String using String class constructor\n\nString class constructor new String() can be used to create a new String. We can initialize a newly created String by passing parameters to String class constructor. If we don’t pass any values to the constructor, it initializes a newly created String object so that it represents an empty character sequence. This way it always creates a new String and dumped into String pool.  \nNote, that use of this constructor is unnecessary since Strings are immutable.\n\n```java\n //creating a new String using String class constructor\n  String string1 = new String(\"This is a sample String 1\");\n```\n\n## 1.3. Creating String from Character Array\n\nWe can also create a String class from the sequence of characters. String class constructor takes a character array as parameter and it creates a new String. The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.\n\n```java\n  //creating String from character array\n  char chars[] = {'T', 'h', 'i', 's', ' ' , 'i' , 's' , ' ' , 'S','t','r','i','n','g'};\n  String string2 = new String(chars);\n```\n\n# 2. Why String is immutable in Java?\n\nImmutable means that once an object of that Class has been created it can’t be altered. Main reason is too provide better performance. Creating a copy of existing java String is easier as there is no need to create a new instance but can be easily created by pointing to already existing String. This saves valuable primary memory. Using String as a key for Hashtable guarantees that there will be no need for re hashing because of object change. Using java String in multi-threaded environment is safe by itself and we need not take any precautionary measures.\n\n```java\n  String string1 = \"Akshay\";\n  string1.concat(\"Kumar\");\n  System.out.println(string1);\n```\n\nThe above code will print Akshay. Only reference for Akshay will be created in String pool, no reference will be created for “Akshay Kumar” But if we want to print Akshay Kumar then we need to do the following changes\n\n```java\n  String string1 = \"Akshay\";\n  string1 = string1.concat(\"Kumar\");\n  System.out.println(string1);\n```\n\n[![Java String Complete Tutorial2](/media/articles/394/Java-String-Complete-Tutorial2.png)](http://stacktips.com)\n\n# 3. String class methods\n\nThe String class provides various methods that appear to modify strings. Since strings are immutable, what these methods create and return a new string that contains the result of the operation.\n\n## 3.1. Comparing string in java\n\nThere are three ways to compare two strings in java.\n\n-   String compression using equals() method\n-   String comparison using == method\n-   Using compareTo() method\n\n### 3.1.1. String compression using equals() method\n\nequals() method compares the two string contents. It compares the value of String for equality. It has two varients of methods equals() and equalsIgnoreCase() method. equals() method compare one string with the specified string. equalsIgnoreCase() method compares one string with the specified String ignoring the case.  \nString class equals() method uses three step process to compare two java String’s;\n\n-   Compare references (if both String references are same return true else continue)\n-   Compare length (if both String length are not same return false else continue)\n-   Compare character by character sequentially.\n\n```java\n  Str
1ing string1 = \"Akshay\";\n  String string2 = new String(\"Akshay\");\n  System.out.println(string1.equals(string2)); //returns true\n\n  String string3 = \"rajesh\";\n  System.out.println(string1.equals(string3)); //returns false\n\n  String string4 = \"akshay\";\n  System.out.println(string1.equals(string4)); //returns false\n\n  String string5 = \"akshay\";\n  System.out.println(string1.equalsIgnoreCase(string5)); //returns true\n```\n\n### 3.1.2. String comparison using == method\n\nThis compares two String’s by reference. Let us look into the below code sample\n\n```java\n  String string1 = \"Akshay\";\n  String string2 = \"Akshay\";\n  System.out.println(string1 == string2); //returns true\n\n  String string3 = new String(\"Akshay\");\n  System.out.println(string1 == string3); //returns false\n```\n\nThe first method of string comparison, it retunes true as the same reference is shared by both string1 and string2. But in the second method, while creating string3 object, it force system to create a new string, even though the pool contains the same string literal. So it returns false.\n\nNote: Do not use == operator to compare java String as it compares only the object references and not its contents. == Operator does not 100% guarantee the equality of java String.\n\n### 3.1.3. Using compareTo() method\n\ncomparedTo() method compares values and returns an integer that says if the compared string2 is less then, equals or greater than string1.\n\n-   If first string is equals to second string then it returns zero.\n-   If first string is bigger than second then returns a positive integer\n-   If first string is smaller than second then returns a negative integer\n\n```java\n  String string1 = \"Akshay\";\n  String string2 = \"akshay\";\n  String string3 = \"Akshay\";\n  String string4 = \"Ajay\";\n  System.out.println(string1.compareTo(string2)); // returns negative integer\n  System.out.println(string1.compareToIgnoreCase(string2)); // returns 0\n  System.out.println(string1.compareTo(string3)); // returns 0\n  System.out.println(string1.compareTo(string4)); // returns positive integer\n```\n\n## 3.2. Concatenating strings in java\n\nThere are two way of concatenating strings in java. We can either use concatenation operator (+) or by using concat() method.\n\n```java\n  String string1 = \"Akshay\" + \"Kumar\";\n  System.out.println(string1); // prints Akshay Kumar\n```\n\nString concatenation operator not just concatenates two strings. It can also concatenate a string and primitive types. But note that the primitive type should be\n\n```java\n  String string1 = \"Akshay\" + 25;\n  System.out.println(string1); // prints Akshay250\n\n  String string2 = 20+ \"Akshay\"+25+25;\n  System.out.println(string2); // prints 20Akshay2525\n\n  String string3 = 20+30+ \"Akshay\"+25+25;\n  System.out.println(string3); // prints 50Akshay2525\n```\n\nIn the above code snippet, string3 value is returned after addition of 20+30, because + operator works as concatenation, only if at least one operand is String type.\n\n## 3.3. subString method in java\n\nsubstring() method is used to split a string. It has two variant,\n\n-   substring(startIndex): This method returns a new String object after splitting the original string from the specified index to the last index.\n-   substring(startIndex, endIndex): This method returns a new String object after splitting the original string from the specified startIndex to the endIndex.\n\n```java\n  String string1 = \"Akshay Kumar\";\n  System.out.println(string1.substring(2)); // prints shay Kumar\n  System.out.println(string1.substring(3, 6)); //prints hay\n```\n\n## 3.4. Creating Format Strings\n\nString class has a method called format() that is used to return a formatted string as specified prams and format. Format specifier supported by java are;\n\n-   %d – signed decimal integer\n-   %u – unsigned decimal integer\n-   %o – unsigned octal integer\n-   %f – real number, standard notation\n-   %s – string\n-   %c – character, etc.\n\n```java\n  String string1 = \"Hello %s, isn't %s cool?\";\n  String formatted = String.format(string1, \"Akshay\", \"Javatechig\");\n  System.out.println(formatted);\n  // prints Hello Akshay, isn't Javatechig cool?\n```\n\n# 4. Other String utilities\n\n## 4.1. How do you convert java String to Date\n\nYou can convert String to java date object using SimpleDateFormat class.\n\n```java\n  try {\n    String dateInString = \"March 28, 2013\";\n    SimpleDateFormat dateFormat = new SimpleDateFormat(\"MMMM d, yyyy\", Locale.ENGLISH);\n    Date formattedDate = dateFormat.parse(dateInString);\n  } catch (ParseException e) {\n    e.printStackTrace();\n  }\n```\n\n## 4.2. Converting Strings to Numbers\n\nJava provides wrapper classes that wrap primitive numeric types and used to convert primitive to String and string to primitive types. The wrapper classes are the subclasses of Number class, they are Byte, Integer, Double, Float, Long, and Short.\n\n```java\n  float a = Float.parseFloat(\"15.4\");\n  int b = Integer.parseInt(\"5\");\n  double c = Double.parseDouble(\"25.01\");\n```\n\n## 4.3. Converting primitive numbers to String\n\nEach of the wrapper classes provides a class method n
1amed valueOf that converts a string to an object of that type.\n\n```java\n  int num1 = 50;\n  Integer number1 = Integer.valueOf(num1);\n  String string1 = number1.toString();\n\n  double num2 = 12.5;\n  Double number2 = Double.valueOf(num2);\n  String string2 = number2.toString();\n```\n"])</script>
1<script>self.__next_f.push([1,"148:Td2c,"])</script>
1<script>self.__next_f.push([1,"\nPOJO is an acronym for Plain Old Java Object, basically a class with attributes and it’s getters and setters. The name is used to emphasize that a given object is an ordinary Java Object, not a special object. The term “POJO” is mainly used to denote a Java object which does not follow any of the major Java object models, conventions, or frameworks.\n\nBelow example reads the pojo object instance variable and generates xml tags and values in the order of variable declaration in the given pojo class. You can assign tag names for each element.\n\n#### Student.java\n\n```java\npublic class Student {\n    String name;\n    String section;\n    String id;\n\n    public Student(String name, String id, String section) {\n        this.name = name;\n        this.id = id;\n        this.section = section;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public String getSection() {\n        return section;\n    }\n\n    public void setSection(String section) {\n        this.section = section;\n    }\n\n    public String getId() {\n        return id;\n    }\n\n    public void setId(String id) {\n        this.id = id;\n    }\n\n}\n```\n\n#### MainActivity.java\n\n```java\nimport java.io.IOException;\nimport java.io.StringWriter;\nimport org.xmlpull.v1.XmlSerializer;\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.util.Log;\nimport android.util.Xml;\nimport android.widget.TextView;\n\npublic class MainActivity extends Activity {\n    TextView textView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        textView = (TextView) findViewById(R.id.textView);\n\n        Student pojo = new Student(\"Adam\" , \"100120\", \"Grade 6\");
1\n        // Serialization begins:\n        XmlSerializer serializer = Xml.newSerializer();\n        StringWriter writer = new StringWriter();\n        try {\n            serializer.setOutput(writer);\n            // start document\n            serializer.startDocument(\"UTF-8\", true);\n            serializer.setFeature(\"http://xmlpull.org/v1/doc/features.html#indent-output\", true);\n\n            serializer.startTag(\"\", \"students\");\n            serializer.startTag(\"\", \"student\");\n            serializer.attribute(\"\", \"ID\", pojo.getId());\n            serializer.startTag(\"\", \"name\");\n            serializer.text(pojo.getName());\n            serializer.endTag(\"\", \"name\");\n            serializer.startTag(\"\", \"section\");\n            serializer.text(pojo.getSection());\n            serializer.endTag(\"\", \"section\");\n            serializer.endTag(\"\", \"student\");\n            serializer.endTag(\"\", \"students\");\n\n            serializer.endDocument();\n            // end document.\n\n            Log.i(\"Pojo to xml\", writer.toString());\n            textView.setText(\"\" + writer.toString());\n            // Toast.makeText(getApplicationContext(), \"\"+ writer.toString(), 0).show();\n        } catch (IllegalArgumentException e) {\n            e.printStackTrace();\n        } catch (IllegalStateException e) {\n            e.printStackTrace();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n    }\n}\n```\n\n#### Output XML\n\n```xml\n\u003cstudents\u003e\n\u003cstudent ID=\"100120\"\u003e\n\u003cname\u003eAdam\u003c/name\u003e\n\u003csection\u003eGrade 6\u003c/section\u003e\n\u003c/student\u003e\n\u003c/students\u003e\n```\n"])</script>
1<script>self.__next_f.push([1,"149:T2ae1,"])</script>
1<script>self.__next_f.push([1,"\nThis example explains step by step tutorials for building Login Application using Struts2 Java Framework. The login workflow includes :\n\n-   By default Login page will populate on running the project.\n-   Show error message in case of invalid credentials without losing user enters text.\n-   Redirect to welcome page on successful /valid credentials.\n\n# 1. Software and tool requirements\n\nThis example us using JAVA 1.6 for compilation and and deployed on Tomcat 6.x as application server. We use Eclipse IDE for all of our development purpose.\n\n-   JAVA 1.6\n-   Tomcat 6\n-   Eclipse 3.6\n\n# 2. Struts 2 framework libraries\n\nDownload the latest version of struts 2 lib from [http://struts.apache.org/download.cgi](http://struts.apache.org/download.cgi \"Download Struts 2\") with respect to you platform such as Windows or Linux. We are using struts-2.3.15.1-lib(windows) for this example.\n\nAfter downloading extract the struts-2.3.15.1-lib.zip file to some location e.g. [C:\\\\struts-2.3.15.1-lib](C:\\struts-2.3.15.1-lib)\n\n# 3. Creating a new dynamic Web Project in eclipse as strutsweb\n\nFile -\u003e New -\u003e Dynamic Web Project.\n\nEnter the Project Name as **struts2web**, select the target run-time as Apache Tomcat v6.0 and click on **Finish**.\n\n[![New Dynamic Web Project](/media/articles/396/New-Dynamic-Web-Project.png)](http://stacktips.com)\n\nNow copy following jars from `C:\\struts-2.3.15.1-lib` to `\\WEB-INF\\libs`\n\n[![Struts2 Login Application Libs](/media/articles/396/Struts2-Login-Application-Libs.png)](http://stacktips.com)\n\n# 4. Modify web.xml configuration to enable struts2 framework\n\nDo the following changes in web.xml file to enable struts 2 framework features. You can locate `web.xml` file in `\\WEB-INF\\web.xml` in your project directory.\n\n```xml\n\u003c?xmlversion=\"1.0\"encoding=\"UTF-8\"?\u003e\n\u003cweb-appxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns=\"http://java.sun.com/xml/ns/javaee\"\nxmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\nxsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\nid=\"WebApp_ID\" version=\"2.5\"\u003e\n\u003cdisplay-name\u003estruts2web\u003c/display-name\u003e\n\u003cfilter\u003e\n    \u003cfilter-name\u003estruts2\u003c/filter-name\u003e\n\u003cfilter-class\u003e\n       org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter\n\u003c/filter-class\u003e\n\u003c/filter\u003e\n\n\u003cfilter-mapping\u003e\n    \u003cfilter-name\u003estruts2\u003c/filter-name\u003e\n    \u003curl-pattern\u003e/*\u003c/url-pattern\u003e\n\u003c/filter-mapping\u003e\n\n\u003cwelcome-file-list\u003e\n    \u003cwelcome-file\u003eindex.jsp\u003c/welcome-file\u003e\n\u003c/welcome-file-list\u003e\n\u003c/web-app\u003e\n```\n\n\u003cfilter/\u003e- This is filter dispatcher class act as controller. All requests go through this filter. It looks at the request and determines the appropriate action by looking up the struts configuration file i.e. struts.xml.\n\n\u003cfilter-mapping/\u003e – It is used to map the request to filter. All request action map to filter dispatcher.\n\n\u003cwelcome-file-list/\u003e – It is used to populate the default page.\n\n# 5. Writing Java class to validate the login cridentials\n\nNow, let us jump into validating login credenials from java class. Create `LoginAuthAction.java` inside the following package `com.javatechig.struts2web.actions.` Note, you may have your own package name\n\n```java\npublic class LoginAuthAction extends ActionSupport {\n    Private static final longserialVersionUID = 1L;\n    private String userId;\n    private String password;\n\n    private Boolean error;\n\n    public String execute() {\n        if (userId.equals(\"\")) {\n            addActionError(\"Please Enter user id.\");\n            error = true;\n        }\n        else if(password.equals(\"\")) {\n            addActionError(\"Please Enter password.\");\n            error = true;\n        }\n        else if(!userId.equalsIgnoreCase(password)) {\n            addActionError(\"Invalid userid or password.\");\n            error = true;\n        } else {\n            error = false;\n        }\n\n        if (error) {\n            return ERROR;\n        } else {\n            return SUCCESS;\n        }\n\n    }\n\n    public String getUserId() {\n        return userId;\n    }\n\n    public void setUserId(String userId) {\n        this.userId = userId;\n    }\n\n    public String getPassword() {\n        returnpassword;\n    }\n\n    public void setPassword(String password) {\n        this.password = password;\n    }\n}\n```\n\nThe `LoginAuthAction` extends `ActionSupport` to use core methods such as `addActionError` and static string `ERROR`, `SUCCESS`. The `execute()` is the default method which contains the logic for action class. In this example we are validating userId \u0026 password is empty or equals. If empty showing error “Please enter userId/password” else if equals then its validated.\n\n# 6. Configuring action class in Struts configuration file\n\nNow it’s time to configure the action class in Struts configuration file. Create struts2 configuration file as struts.xml inside project src directory\n\n```xml\n\u003c?xmlversion=\"1.0\"encoding=\"UTF-8\"?\u003e\n\u003c!DOCTYPEstrutsPUBLIC\n\"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n\"http://struts.apache.org/dtds/struts-2.0.dtd\"\u003e\n\n\u003cstruts\u003e\n    \u003cpackagename=\"struts2web\"namespace=\"/\"extends=\"struts-default\"\u003e\n        \u003cactionname=\"login\"\u003e\n            \u003cresult\u003epages/login.jsp\u003c/result\u003e\n        \u003c/action\u003e\n        \u003cactionname=\"welcome\"\u003e\n            \u003cresult\u003epages/welcome.jsp\u003c/result\u003e\n        \u003c/action\u003e\n        \u003cactionname=\"loginauth\"class=\"com.javatechig.struts2web.actions.LoginAuthAction\"\n            \u003cresultname=\"success\"type=\"redirect\"\u003e\n        \u003cparamname=\"location\"\u003e/welcome\u003c/param\u003e\n        \u003c/result\u003e\n            \u003cresultname=\"error\"\u003epages/login.jsp\u003c/result\u003e\n        \u003c/action\u003e\n    \u003c/package\u003e\n\u003c/struts\u003e\n```\n\n**Package – name** – It can be any name but it is good practice to use project name.  \n**Package** – namespace –Default it is root(/). It is used for package modularization if the project has more than one module.  \n**Action** – It is for action class mapping with action name. I have three action name  \n**login** – which is mapped to default struts action dispatcher which populate login.jsp  \n**welcome** – which is mapped to default struts action dispatcher which populatewelcome.jsp  \n**loginauth** – which is mapped to LoginAuthActionclass which returns ERROR \u0026 SUCCESS.  \n**ERROR** – mapped to login.jsp to display the login errors with user entered credentials.  \n**SUCCESS** – Its redirect to “welcome” action.\n\nYou can see at the bottom of class I have created getter and setter method of declared variable. This is used by the interceptor. The interceptor will look for setFieldName while on every action request. The FieldName is the element name in the html form. E.g.  \nI am using text field in the login.jsp for userid . The name of textfield is userId.\n\nWhen you click on login it request for loginauth action, which is goes through struts2 dispatcher filter which executes interceptor before/after the invoking of action class. The interceptor will convert the field name userId to setUserId and then pass the textfield value to setUserId(val). In the same way when dispatcher deliver the view i.e. jsp it uses getUserId(). E.g. when you enter wrong password and valid user id it throws the same page with error saying invalid password with existing user id values.\
1n\n# 7. Creating jsp pages\n\nIn this example we will be needing two jsp pages. Once for login form and other is welcome screen. Welcome screen will appear once user credentials are authenticated\n\n## 7.1. Login form\n\n```html\n\u003c%@pagecontentType=\"text/html; charset=UTF-8\"%\u003e\n\u003c%@taglibprefix=\"s\"uri=\"/struts-tags\"%\u003e\n\u003c!DOCTYPEhtmlPUBLIC\"-//W3C//DTD HTML 4.01 Transitional//EN\"\"http://www.w3.org/TR/html4/loose.dtd\"\u003e\n\u003chtml\u003e\n\u003chead\u003e\n\u003cmetahttp-equiv=\"Content-Type\"content=\"text/html; charset=ISO-8859-1\"\u003e\n\u003ctitle\u003eInsert title here\u003c/title\u003e\n\u003cstyletype=\"text/css\"\u003e\nbody{\n    font-family:Arial,Helvetica,sans-serif;\n    font-size:12px;\n}\n.errors {\n    background-color:#FFCCCC;\n    border:1px solid #CC0000;\n    width:220px;\n    line-height:10px;\n}\n.errorsli{\n    list-style: none;\n}\n\u003c/style\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n\u003cs:formaction=\"loginauth\"theme=\"simple\"\u003e\n\u003ccenter\u003e\n    \u003ctablewidth=\"200\"\u003e\n        \u003ctrheight=\"30\"\u003e\n            \u003ctdwidth=\"200\"colspan=\"2\"\u003e\n                \u003cs:iftest=\"hasActionErrors()\"\u003e\n                    \u003cdivclass=\"errors\"\u003e\n                        \u003cs:actionerror/\u003e\n                    \u003c/div\u003e\n                \u003c/s:if\u003e\n            \u003c/td\u003e\n        \u003c/tr\u003e\n        \u003ctr\u003e\n            \u003ctdcolspan=\"2\"width=\"200\"align=\"left\"style=\"background:#eee\"\u003eLogin Here\u003c/td\u003e\n        \u003c/tr\u003e\n        \u003ctr\u003e\n            \u003ctdalign=\"left\"\u003eUser ID:\u003c/td\u003e\u003ctdalign=\"left\"\u003e\u003cs:textfieldname=\"userId\"/\u003e\u003c/td\u003e\n        \u003c/tr\u003e\n        \u003ctr\u003e\n            \u003ctdalign=\"left\"\u003ePassword:\u003c/td\u003e\u003ctdalign=\"left\"\u003e\u003cs:passwordtype=\"text\"name=\"password\"/\u003e\u003c/td\u003e\n        \u003c/tr\u003e\n        \u003ctr\u003e\n            \u003ctdalign=\"left\"\u003e\u003c/td\u003e\u003ctdalign=\"left\"\u003e\u003cinputtype=\"submit\"name=\"login\"value=\"Login\"\u003e\u003c/td\u003e\n        \u003c/tr\u003e\n    \u003c/table\u003e\n\u003c/center\u003e\n\u003c/s:form\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n\u003cs:form/\u003e – Struts form element which enhanced with html form. The action is the action class to invoke on click on Login button.\n\n\u003cs:textfield/\u003e – Struts textfiled element which is enhanced to \u003cinput type=”text”/\u003e  \n\u003cs:password/\u003e- Struts textfiled element which is enhanced to \u003cinput type=”password”/\u003e\n\nThe name attribute of textfield and password values are important. The value should be same as declared variable in the action class.  \nprivate String userId;  \nprivate String password;\n\n## 7.2. Creating Welcome jsp page\n\nThis page contains the welcome text, and will be displayed, once user credentials are authenticated.\n\n```html\n\u003c%@pagelanguage=\"java\"contentType=\"text/html; charset=ISO-8859-1\"\npageEncoding=\"ISO-8859-1\"%\u003e\n\u003c!DOCTYPEhtmlPUBLIC\"-//W3C//DTD HTML 4.01 Transitional//EN\"\"http://www.w3.org/TR/html4/loose.dtd\"\u003e\n\u003chtml\u003e\n\u003chead\u003e\n\u003cmetahttp-equiv=\"Content-Type\"content=\"text/html; charset=ISO-8859-1\"\u003e\n\u003ctitle\u003eJavatechig :: Struts 2 Tutorial\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n\u003ch1\u003eWelcome!\u003c/h1\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n## 7.3. Create Index.jsp\n\nI am using this page to redirect to login.action. You can see it is configured as welcome-file in web.xml that means it invokes when you run the project with web-context (project-name) name i.e. [http://localhost:8080/](\u003chttp://localhost:8080/ \u003e \"Testing Login App\") and finally you will get login.jsp as default.\n\nNow we are done with the sample and it is ready to run, before that pleas make sure all the created files in proper location as follows:\n\n[![Struts2 Login Application Project Structure](/media/articles/396/Struts2-Login-Application-Project-Structure.png)](http://stacktips.com)\n\n# 8. Output\n\n[
1![Struts2 Login Application Project Output](/media/articles/396/Struts2-Login-Application-Project-Output1.png)](http://stacktips.com)\n\n[![Struts2 Login Application Project Output](/media/articles/396/Struts2-Login-Application-Project-Output2.png)](http://stacktips.com)\n\n[![Struts2 Login Application Project Output](/media/articles/396/Struts2-Login-Application-Project-Output3.png)](http://stacktips.com)\n\n\\[author\\_bio\n"])</script>
1<script>self.__next_f.push([1,"14a:T1580,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial, we show you how to use radio button in android using example.\n\nRadioButton is a two-states button that can be either checked or unchecked. When the radio button is unchecked, the user can click it to check it. Radio button generally works with RadioGroup. Radio group can hold multiple RadioButtons, however only one can be selected at any point of time. Once a radio button is checked by user it cannot be unchecked again by pressing the same button. It automatically gets unchecked, where any other button on the same RadioGroup is selected.\n\nLet us understand some of the RadioButton attributes and properties\n\n1.  The `android:orientation` property on the Radio group defines the orientation to position its child view. It can be either horizontal or vertical.\n2.  `check(id)` – Sets the selection to the radio button whose identifier is passed in parameter. Using -1 as the selection identifier clears the selection.\n3.  `clearCheck()`– Clears the selection. When the selection is cleared, no radio button in this group is selected and getCheckedRadioButtonId() returns null.\n4.  `getCheckedRadioButtonId()` – Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.\n5.  `setOnCheckedChangeListener()` – Register a callback to be invoked when the checked radio button changes in this group. You must supply instance of `RadioGroup.OnCheckedChangeListener` to setOnCheckedChangeListener() method.\n\n# Android RadioButton Example\n\nCreate a new layout file named activity\\_main.xml under layout resource folder and add the following code snippets. The code will generate the layout as shown in the screenshot below.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:orientation=\"vertical\"\n    android:padding=\"20dp\"\u003e\n\n    \u003cTextView\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"How do you like the quality of our tutorials?\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n    \u003cRadioGroup\n        android:id=\"@+id/radioGroup\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:orientation=\"vertical\"\u003e\n\n        \u003cRadioButton\n            android:id=\"@+id/radioButton1\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"Excellent \" /\u003e\n\n        \u003cRadioButton\n            android:id=\"@+id/radioButton2\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"Satisfactory\" /\u003e\n\n        \u003cRadioButton\n            android:id=\"@+id/radioButton3\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"Below Average\" /\u003e\n    \u003c/RadioGroup\u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:orientation=\"horizontal\"\u003e\n\n        \u003cButton\n            android:id=\"@+id/clearBtn\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:onClick=\"onClear\"\n            android:text=\"Clear \" /\u003e\n\n        \u003cButton\n            android:id=\"@+id/submitBtn\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:onClick=\"onSubmit\"\n            android:text=\"Submit\" /\u003e\n    \u003c/LinearLayout\u003e\n\u003c/LinearLayout\u003e\n```\n\n# Using RadioButton from Activity\n\nLet us create a new java class named RadioButtonSampleActivity.java and add the following screenshot.\n\n```java\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.RadioButton;\nimport android.widget.RadioGroup;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity {\n    private RadioGroup radioGroup;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        /* Initialize Radio Group and attach click handler */\n        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);\n        radioGroup.clearCheck();\n\n        /* Attach CheckedChangeListener to radio group */\n        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {\n            @Override\n            public void onCheckedChanged(RadioGroup group, int checkedId) {\n                RadioButton rb = (RadioButton) group.findViewById(checkedId);\n                if(null!=rb \u0026\u0026 checkedId \u003e -1){\n                    Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();\n                }\n\n            }\n        });\n    }\n\n    public void onClear(View v) {\n        /* Clears all selected radio buttons to default */\n        radioGroup.clearCheck();\n    }\n\n    public void onSubmit(View v) {\n        RadioButton rb = (RadioButton) radioGroup.findViewById(radioGroup.getCheckedRadioButtonId());\n        Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();\n    }\n}
1\n```\n\n# Output\n\n[![Android RadioButton Example](/media/articles/397/Android-RadioButton-Example-620x592.png)](/articles/android-radio-button-example/attachment/android-radiobutton-example)\n"])</script>
1<script>self.__next_f.push([1,"14b:Tf05,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains how to create menu in android with example.\n\nMenus are a common user interface component in many types of applications. To provide a familiar and consistent user experience, you should use the Menu APIs to present user actions and other options in your activities.\n\n# Declare Menu Items in XML\n\nYou can create android menus in two ways. One by using the code or using XML declaration. In this tutorial we are crating the menu items using the declarative approach from xml.\n\n1.  Create a new folder named `menu` inside your project resources directory. This folder will contain all the menu declarative XML files.\n2.  Now let us add a new xml file named `menu_myactivity.xml` file, into menu resource directory and paste the following code snippets.\n\n```xml\n\u003cmenu xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    tools:context=\".MainActivity\"\u003e\n    \u003citem\n        android:id=\"@+id/mapMenu\"\n        android:icon=\"@drawable/menu_map\"\n        android:title=\"Map\" /\u003e\n    \u003citem\n        android:id=\"@+id/favMenu\"\n        android:icon=\"@drawable/menu_favourite\"\n        android:title=\"Favorite\" /\u003e\n    \u003citem\n        android:id=\"@+id/listMenu\"\n        android:icon=\"@drawable/menu_list\"\n        android:title=\"List\" /\u003e\n    \u003citem\n        android:id=\"@+id/settingsMenu\"\n        android:icon=\"@drawable/menu_settings\"\n        android:title=\"Settings\" /\u003e\n\u003c/menu\u003e\n```\n\nNotice that in the menu declaration xml, we are using some of the drawable images. Here you need to add your own images to drawable directory.\n\n**Note:** I have used few images for menu items. Copy your images under drawable folder of project. For more details on icon size, Refer [Guides for App Designers!](http://developer.android.com/guide/practices/ui_guidelines/icon_design_menu.html)\n\n# Using Menu from Android Activity\n\nImplement the `onCreateContextMenu()` method from your android Activity class and inflate the menu items created in the `menu_myactivity.xml`. We can also override `OnOptionsItemSelected` method to handle the events while user presses the menu option in android.\n\n```java\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.MenuInflater;\nimport android.view.MenuItem;\nimport android.view.ViewGroup.LayoutParams;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MenuActivity extends Activity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n\n        TextView text = new TextView(this);\n        text.setText(\"Press the menu button to get list of menus.\");\n        addContentView(text, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        MenuInflater inflater = getMenuInflater();\n        inflater.inflate(R.menu.menu_myactivity, menu);\n        return true;\n    }\n\n    @Override\n    public boolean onOptionsItemSelected(MenuItem item) {\n        Toast.makeText(getApplicationContext(),    item.getTitle() + \" selected\", Toast.LENGTH_SHORT).show();\n\n        switch (item.getItemId()) {\n        case R.id.mapMenu:\n            // do something\n            break;\n        case R.id.favMenu:\n            // do something\n            break;\n        case R.id.listMenu:\n            // do something\n            break;\n        case R.id.settingsMenu:\n            // do something\n            break;\n        }\n        return true;\n    }\n\n}\n```\n\n# Demo\n\nRun the application, you will notice the result as shown in the screenshot below.\n\n[![](/media/articles/398/android_menu_sample.png)](http://1.bp.blogspot.com/-zuOxwEk7Mys/UBvBzAwSWFI/AAAAAAAAAb0/1R6PWTpRri8/s1600/android_menu_sample.png)\n"])</script>
1<script>self.__next_f.push([1,"14c:T16e0,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains how to use Button widget in Android. The examples used in this tutorial, will show you how to create different button layout such as normal button, image button, button with image and text, etc.\n\nAndroid button represents a clickable push-button widget. It accepts different user action such as press, click, long press, etc. Button widget is available in android.widget.Button package.\n\nLet us drive straight into creating button views and different Button properties.\n\n## Declaring Button Layout\n\nLike any other view widget, you can declare the Button widget layout in your Activity or Fragment layout or you can create a Button programmatically. The following section will show you how to declare a buttons to activity layout.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cButton\n        android:id=\"@+id/button\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:text=\"Button1\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/button2\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Button2\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/button3\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"right\"\n        android:text=\"Button3\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/button4\"\n        android:layout_width=\"200dp\"\n        android:layout_height=\"90dp\"\n        android:text=\"Button4\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/button5\"\n        android:layout_width=\"200dp\"\n        android:layout_height=\"90dp\"\n        android:gravity=\"right\"\n        android:text=\"Button5\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\n#### How it works\n\nThe above xml code will generate five buttons and will represent layout as shown in the screenshot below.\n\n1.  We have created a LinearLayout and its orientation is set to vertical.\n2.  The `layout_width` parameter indicates the width of the widget. The first button is stretched to the full screen by specifying its value to match\\_parent.\n3.  The `layout_width` attribute indicates the height a view. The wrap\\_content indicates that the height will be adjusted to content of the widget.\n4.  The `android:layout_gravity` defines the positioning of view in its parent layout.\n5.  The `android:gravity` defines the alignment for the view content. It can be of any possible constants like left, right, center\\_vertical, center\\_horizontal, center\n\n[![Android Button Example](/media/articles/400/Android-Button-Example.png)](http://stacktips.com/android/android-button-example/attachment/android-button-example-2)\n\n## Initializing Button in Activity\n\nNow that we have created the activity layout. Let us use this layout in activity. Paste the following code snippet in your activity (MyActivity.java) class.\n\n```java\nprotected void onCreate(Bundle savedInstanceState) {\n    super.onCreate(savedInstanceState);\n    setContentView(R.layout.main;\n    Activity mActivity = this;\n\n    Button button = (Button) findViewById(R.id.button1);\n    button.setOnClickListener(new OnClickListener() {\n\n        @Override\n        public void onClick(View v) {\n            Toast.makeText(mActivity, \"Button1 Clicked!\", Toast.LENGTH_LONG).show();\n        }\n});\n```\n\n## Button Event Handling\n\nTo Attach a click listener to the button, let us first instantiate the Button object by calling `findViewById()` and supplying the unique button id as declared in the layout.\n\nNow, call `setOnClickListener()` method and provide `OnClickListener` event reference. Read here for more on [different way to handle events in Android](http://stacktips.com/android/different-way-to-handle-events-in-android \"Different way to handle events in Android\").\n\n## Styling Android Button\n\nAndroid Button styles can be customized with color, font, background etc. Lets us see some of the button xml attributes to customize the buttons as shown below.\n\n1.  `android:background` – Sets Button background style. This can be an hex color of #RRGGBBAA format or can be a drawable.\n2.  `android:drawableLeft` – Showing an image to the left side of the button. In the following screenshot, the Facebook icon depicts the same.\n3.  `android:textColor` – Allows you to set the background color of button.\n\nLearn more about on customizing Android View’s from the following links.\n\n[Android Styles and Themes Tutorial](http://stacktips.com/android/android-styles-and-themes-tutorial \"Android Styles and Themes Tutorial\")\n\n[Using External Fonts in Android View](http://stacktips.com/android/using-external-fonts-in-android-view \"Using External Fonts in Android View\")\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:orientation=\"vertical\"\n    android:padding=\"10dp\"\u003e\n\n    \u003cButton\n        android:id=\"@+id/button1\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center\"\n        android:layout_marginBottom=\"10dp\"\n        android:background=\"@drawable/button_bg\"\n        android:text=\"Button1\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/button2\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center\"\n        android:background=\"#3B5998\"\n        android:drawableLeft=\"@drawable/facebook\"\n        android:padding=\"10dp\"\n        android:text=\"Login With Facebook\"\n        android:textColor=\"#ffffff\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\nHere is the output of the above code  \n[![Android Button Style](/media/articles/400/Android-Button-Style.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"14d:T134e,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains “How to Programmatically Zip and Unzip File in Android”. Zipping means writing (compress) data into zip files. Below code snippet will help you to zip and unzip files using a generic wrapper class that allows you to easily zip files in Android.\n\n# Why you need a Zip file?\n\n1.  You couldn’t send multiple attachments using Intents to the Google Mail app. The quickest way around that was of course to compress all of the files into one (ZIP).\n2.  For the applications that need to send multiple files to server, it is always easiest to create a zip file and send it across over network.\n\nI have created both zip and unzip method inside a wrapper class called `**ZipManager**`. You may create the same way or you may like to use in your own way.\n\n# How to Zip files\n\nCrete a sample android activity and add the following permission to application Mainfest.xml file. These persmissions are required to store data to your device storage.\n\n```xml\n\u003cuses-permission android:name=\"android.permission.WRITE_INTERNAL_STORAGE\" /\u003e\n\u003cuses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/\u003e\n```\n\nYou can use below code to create zip file. Just copy paste to make it work in your activity\n\n```java\npublic void zip(String[] _files, String zipFileName) {\n        try {\n            BufferedInputStream origin = null;\n            FileOutputStream dest = new FileOutputStream(zipFileName);\n            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(\n                    dest));\n            byte data[] = new byte[BUFFER];\n\n            for (int i = 0; i \u003c _files.length; i++) {\n                Log.v(\"Compress\", \"Adding: \" + _files[i]);\n                FileInputStream fi = new FileInputStream(_files[i]);\n                origin = new BufferedInputStream(fi, BUFFER);\n\n                ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf(\"/\") + 1));\n                out.putNextEntry(entry);\n                int count;\n\n                while ((count = origin.read(data, 0, BUFFER)) != -1) {\n                    out.write(data, 0, count);\n                }\n                origin.close();\n            }\n\n            out.close();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n```\n\n**`BUFFER`** is used for limiting the buffer memory size while reading and writing data it to the zip stream\n\n**`_files`** array holds all the file paths that you want to zip\n\n**`zipFileName`** is the name of the zip file.\n\nYou can use this in your activity\n\n```java\n// declare an array for storing the files i.e the path\n// of your source files\nString[] s = new String[2];\n\n// Type the path of the files in here\ns[0] = inputPath + \"/image.jpg\";\ns[1] = inputPath + \"/textfile.txt\"; // /sdcard/ZipDemo/textfile.txt\n\n// first parameter is d files second parameter is zip file name\nZipManager zipManager = new ZipManager();\n\n// calling the zip function\nzipManager.zip(s, inputPath + inputFile);\n```\n\nYou can get complete working eclipse project to end of this tutorial.\n\n# How to UnZip files\n\nNow let us look into unzipping files. For unzipping you need to know the file path for .zip file and the path to the directory extract the files.\n\n```java\npublic void unzip(String _zipFile, String _targetLocation) {\n\n        //create target location folder if not exist\n        dirChecker(_targetLocatioan);\n\n        try {\n            FileInputStream fin = new FileInputStream(_zipFile);\n            ZipInputStream zin = new ZipInputStream(fin);\n            ZipEntry ze = null;\n            while ((ze = zin.getNextEntry()) != null) {\n\n                //create dir if required while unzipping\n                if (ze.isDirectory()) {\n                    dirChecker(ze.getName());\n                } else {\n                    FileOutputStream fout = new FileOutputStream(_targetLocation + ze.getName());\n                    for (int c = zin.read(); c != -1; c = zin.read()) {\n                        fout.write(c);\n                    }\n\n                    zin.closeEntry();\n                    fout.close();\n                }\n\n            }\n            zin.close();\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n}\n```\n\nYou can use this method in your activity\n\n```java\nZipManager zipManager = new ZipManager();\nzipManager.unzip(inputPath + inputFile, outputPath);\n```\n\n# Download Complete Example\n\nHere you can download complete eclipse project source code from GitHub.\n\n[Download Complete Source Code from GitHub](https://github.com/javatechig/javatechig-android-advanced/tree/master/com.javatechig.androidzip)\n\n[![How to Programmatically Zip and Unzip File in Android  (2)](/media/articles/401/How-to-Programmatically-Zip-and-Unzip-File-in-Android-2.png)](http://stacktips.com)\n\n[![How to Programmatically Zip and Unzip File in Android](/media/articles/401/How-to-Programmatically-Zip-and-Unzip-File-in-Android-.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"14e:T7f7,"])</script>
1<script>self.__next_f.push([1,"\nArrays and `Collection` class provides methods that allows to search a specific element in the list. Things to know while searching a collection or an array;\n\n-   Search is performed using `binarySearch()` method\n-   If the element found in the collection or array it returns the element index. If the index is a non negative integer greater than zero then element found.\n-   The collection array needs to be sorted before performing search algorithm. If the collection is not sorted then the result will be unpredictable. Note that the sorting should be performed in natural order.\n-   If the sorting is not made in natural order, and performed using Comparator, then searching should be performed using same Comparator.\n\nExample of searching Array/Collection in java\n\n```java\npackage com.java.test;\n\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class SearchObjectArray {\n\n    public static void main(String[] args) {\n        String[] names = { \"Neel\", \"Clay\", \"Adams\", \"Joseph\", \"Jack\" };\n\n        // sorting array\n        Arrays.sort(names);\n\n        // printing after sort\n        for (String name : names) {\n            System.out.println(name);\n        }\n\n        // Search result for \"one\"\n        System.out.println(\"Search Adams=\" + Arrays.binarySearch(names, \"Adams\"));\n\n        System.out.println(\"======================================\");\n\n        // reverse sorting\n        ReverseSortComparator reSort = new ReverseSortComparator();\n        Arrays.sort(names, reSort);\n        for (String name : names) {\n            System.out.println(name);\n        }\n\n        // Search result for \"one\"\n        System.out.println(\"Search Adams=\" + Arrays.binarySearch(names, \"Adams\", reSort));\n    }\n\n    static class ReverseSortComparator implements Comparator {\n\n        public int compare(String a, String b) {\n            return b.compareTo(a);\n        }\n\n    }\n\n}\n```\n\nOutput of the above code is\n\n[![Searching arrays and collections](/media/articles/404/Searching-arrays-and-collections.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"14f:T86a,"])</script>
1<script>self.__next_f.push([1,"\nTo import a specific member inside your java source file, put an `import` statement at the beginning of the file before any type definitions but after the package statement, if there is one. Here’s how you would import the `Color` class to `Rectangle` class.\n\n```java\npackage com.java.test;\n\npublic class Constants {\n\n    public static final double PI = 3.141592653589793;\n}\n```\n\nImporting Constants class\n\n```java\nimport com.java.test.Constants;\n\npublic class Circle {\n    private double getArea(int radious) {\n        return Constants.PI * radious * radious;\n\n    }\n\n    public static void main(String[] args) {\n        Circle myCircle = new Circle();\n        System.out.println(\"Area=\" + myCircle.getArea(20));\n    }\n\n}\n```\n\nThis approach works well. However, Java5 has enhanced import feature called static import. Static import can be used when you want to use classe’s static members. After using static import in the above example\n\n```java\nimport static com.java.test.Constants.PI;\n\npublic class Circle {\n    private double getArea(int radious) {\n        return PI * radious * radious;\n\n    }\n\n    public static void main(String[] args) {\n        Circle myCircle = new Circle();\n        System.out.println(\"Area=\" + myCircle.getArea(20));\n    }\n\n}\n```\n\nHowever, both classes produce the same output.\n\n### Note:\n\n1.  To use static import we have to use fully qualified name of the static member you want to import, or a wildcard. In our example we are importing PI from `com.java.test.Constants` class\n2.  In case we have to import several static members, then we can use wildcard (\\*), which will import all of the static members of that class.\n3.  After `static import` we don’t have to write the class name while calling. You can see the example in case-1 where we are using Constants.PI but after static import we just use member name PI.\n4.  You must use `import static \u003cpackagename.Classname.MemberName\u003e`\
1n5.  Static import and ambiguity: If your are importing the static member of two classes that shares common names for two or more members, which leads to an ambiguity. Java compiler wont understand which member it is referring to.\n"])</script>
1<script>self.__next_f.push([1,"150:T13bf,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains creating spinner in android and attaching event to spinner in android. Here in this tutorial, you’ll create a Simple spinner widget that displays a list of countries and shows appropriate flag as per selected country from the spinner.\n\n1. Create a new new project. In this example we named it as **SpinnerExample.**\n\n### Declare Your Activity Layout (layout\\_main.xml)\n\nAdd a new layout file in \\\\layout\\\\layout\\_main.xml and insert the following code.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:orientation=\"vertical\"\n    android:padding=\"10dip\" \u003e\n\n    \u003cTextView\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginTop=\"10dip\"\n        android:text=\"@string/country_label\"\n        android:textAppearance=\"?android:attr/textAppearanceLarge\" /\u003e\n\n    \u003cSpinner\n        android:id=\"@+id/country_spinner\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:prompt=\"@string/country_label\" /\u003e\n\n    \u003cImageView\n        android:id=\"@+id/country_image\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\n        android:layout_gravity=\"center_vertical\"\n        android:scaleType=\"centerInside\"\n        android:src=\"@drawable/ic_launcher\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\nIn the above example, we have declared TextView, Spinner and a ImageView. The text behaves as a title for the spinner. When you select the Spinner, the ImageView to display the flag for selected country in Spinner.\n\n### 3. Declaring String Arrays inside strings.xml\n\nBelow are the strings used in the application. Declare all of them in strings.xml file\n\n```xml\n\u003cstring-array name=\"countries_list\"\u003e\n        \u003citem\u003eAfghanistan\u003c/item\u003e\n        \u003citem\u003eAlbania\u003c/item\u003e\n        \u003citem\u003eAustralia\u003c/item\u003e\n        \u003citem\u003eBangladesh\u003c/item\u003e\n        \u003citem\u003eBhutan\u003c/item\u003e\n        \u003citem\u003eEngland\u003c/item\u003e\n        \u003citem\u003eFinland\u003c/item\u003e\n        \u003citem\u003eIndia\u003c/item\u003e\n        \u003citem\u003eSaudi Arabia\u003c/item\u003e\n        \u003citem\u003eNepal\u003c/item\u003e\n    \u003c/string-array\u003e\n\n    \u003cinteger-array name=\"countries_flag_list\"\u003e\n        \u003citem\u003e@drawable/afghanistan\u003c/item\u003e\n        \u003citem\u003e@drawable/albania\u003c/item\u003e\n        \u003citem\u003e@drawable/australia\u003c/item\u003e\n        \u003citem\u003e@drawable/bangladesh\u003c/item\u003e\n        \u003citem\u003e@drawable/bhutan\u003c/item\u003e\n        \u003citem\u003e@drawable/england\u003c/item\u003e\n        \u003citem\u003e@drawable/finland\u003c/item\u003e\n        \u003citem\u003e@drawable/india\u003c/item\u003e\n        \u003citem\u003e@drawable/saudi_arabia\u003c/item\u003e\n        \u003citem\u003e@drawable/nepal\u003c/item\u003e\n    \u003c/integer-array\u003e\n```\n\n### 4. Activity Java Class (MainActivity.java)\n\nNow create a java class and name it as MainActivity.java. And paste the following code.\n\n```java\npackage com.example.spinnerexample;\n\nimport android.app.Activity;\nimport android.content.res.TypedArray;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemSelectedListener;\nimport android.widget.ArrayAdapter;\nimport android.widget.ImageView;\nimport android.widget.Spinner;\n\npublic class MainActivity extends Activity {\n\n    private ImageView image;\n    private String[] states;\n    private Spinner spinner;\n    private TypedArray imgs;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);
1\n\n        states = getResources().getStringArray(R.array.countries_list);\n        imgs = getResources().obtainTypedArray(R.array.countries_flag_list);\n\n        image = (ImageView) findViewById(R.id.country_image);\n        spinner = (Spinner) findViewById(R.id.country_spinner);\n\n        ArrayAdapter\u003cString\u003e dataAdapter = new ArrayAdapter\u003cString\u003e(this,\n                android.R.layout.simple_spinner_item, states);\n        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n        spinner.setAdapter(dataAdapter);\n\n        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n            @Override\n            public void onItemSelected(AdapterView\u003c?\u003e parent, View view,\n                    int position, long id) {\n                image.setImageResource(imgs.getResourceId(\n                        spinner.getSelectedItemPosition(), -1));\n            }\n\n            @Override\n            public void onNothingSelected(AdapterView\u003c?\u003e arg0) {\n\n            }\n        });\n    }\n}\n```\n\nFirst we are initializing `Spinner` object by getting reference from the xml layout file using `findViewById()` method. Then creates a new `ArrayAdapter`, which binds each item in the string array to the initial appearance for the Spinner (which is how each item will appear in the spinner when selected). `setOnItemSelectedListener()` callback is registered to Spinner to handle the spinner event.\n\n### 5. Output\n\n[![Android Spinner Example](/media/articles/407/Android-Spinner-Example.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"151:T2c30,"])</script>
1<script>self.__next_f.push([1,"\n# 1. Introduction to Android ViewFlipper\n\nViewFlipper is and user interface widget available in android since android API level 1. It can hold two more views, but only one child can be shown at a time. Using this we can implement functionality similar to android gallery item, swiping allows to navigate between images. It also support to auto flip between child at a regular interval.\n\nThe ViewFlipper class has derived from ViewAnimator. It supports the methods to set the animation for the in and out actions using `setInAnimation()` and `setOutAnimation()`. You can either use some of the default animation that are available in android system or you can write your own animation class.\n\n# 2. Defining ViewFlipper Example Layout\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cViewFlipper\n        android:id=\"@+id/view_flipper\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\u003e\n\n        \u003cRelativeLayout\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"fill_parent\"\u003e\n\n            \u003cImageView\n                android:layout_width=\"fill_parent\"\n                android:layout_height=\"fill_parent\"\n                android:layout_gravity=\"center\"\n                android:adjustViewBounds=\"true\"\n                android:scaleType=\"centerCrop\"\n                android:src=\"@drawable/lightning\" /\u003e\n\n            \u003cTextView\n                style=\"@style/ImageTitle\"\n                android:text=\"@string/lightning\" /\u003e\n        \u003c/RelativeLayout\u003e\n\n        \u003cRelativeLayout\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"fill_parent\"\u003e\n\n            \u003cImageView\n                android:layout_width=\"fill_parent\"\n                android:layout_height=\"fill_parent\"\n                android:layout_gravity=\"center\"\n                android:adjustViewBounds=\"true\"\n                android:scaleType=\"centerCrop\"\n                android:src=\"@drawable/color_baloons\" /\u003e\n\n            \u003cTextView\n                style=\"@style/ImageTitle\"\n                android:text=\"@string/color_baloons\" /\u003e\n        \u003c/RelativeLayout\u003e\n\n        \u003cRelativeLayout\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"fill_parent\"\u003e\n\n            \u003cImageView\n                android:layout_width=\"fill_parent\"\n                android:layout_height=\"fill_parent\"\n                android:layout_gravity=\"center\"\n                android:adjustViewBounds=\"true\"\n                android:scaleType=\"centerCrop\"\n                android:src=\"@drawable/natural_wall\" /\u003e\n\n            \u003cTextView\n                style=\"@style/ImageTitle\"\n                android:text=\"@string/natural_wall\" /\u003e\n        \u003c/RelativeLayout\u003e\n    \u003c/ViewFlipper\u003e\n\n    \u003cImageView\n        android:id=\"@+id/swipe_left\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentLeft=\"true\"\n        android:layout_centerVertical=\"true\"\n        android:src=\"@drawable/swipe_left\" /\u003e\n\n    \u003cImageView\n        android:id=\"@+id/swipe_right\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentRight=\"true\"\n        android:layout_centerVertical=\"true\"\n        android:src=\"@drawable/swipe_right\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\nHere in the above xml layout, I am using three `LinearLayout`. Each layout has an image and image caption. All image caption is using the same style. You can see the screenshot’s below for the style. Now, let us create a `style.xml` file in values folder and then add the following style code\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cresources\u003e\n    \u003cstyle name=\"ImageTitle\"\u003e\n        \u003citem name=\"android:layout_width\"\u003efill_parent\u003c/item\u003e\n        \u003citem name=\"android:layout_height\"\u003e50dp\u003c/item\u003e\n        \u003citem name=\"android:layout_alignParentBottom\"\u003etrue\u003c/item\u003e\n        \u003citem name=\"android:background\"\u003e#99000000\u003c/item\u003e\n        \u003citem name=\"android:gravity\"\u003ecenter\u003c/item\u003e\n        \u003citem name=\"android:maxLines\"\u003e2\u003c/item\u003e\n        \u003citem name=\"android:textColor\"\u003e#fff\u003c/item\u003e\n        \u003citem name=\"android:textStyle\"\u003ebold\u003c/item\u003e\n        \u003citem name=\"android:textSize\"\u003e18dp\u003c/item\u003e\n        \u003citem name=\"android:typeface\"\u003esans\u003c/item\u003e\n    \u003c/style\u003e\n\u003c/resources\u003e\n```\n\nI admit the fact that, the style file used here can be more improvised. The color can be placed in `colors.xml` file. But, for the sake of simplicity it is using the colors right inside the styles. Now we are done with the layout design and we will move to controlling the `ViewFlipper` from java code.\n\n[![Android ViewFlipper example](/media/articles/409/ViewFlipper-example-javatechig.png)](http://stacktips.com)\n\n# 3. Using ViewFlipper in Activity\n\nAndroid ViewFlipper can anytime display only one immoderate child at a time. So you can only see the first image in your eclipse graphical layout view. We need to pragmatically move to different child or we can setup an auto timer. Setting an auto flip timer will create a slideshow and can be controlled by `startFlipping()` and `stopFlipping()` method. Later in this example we will see more in detail.\n\n```java\npublic class ViewFlipperSampleActivity extends Activity {\n    private static final int SWIPE_MIN_DISTANCE = 120;\n    private static final int SWIPE_THRESHOLD_VELOCITY = 200;\n    private ViewFlipper mViewFlipper;\n    private Context mContext;\n    private final GestureDetector detector = new GestureDetector(new SwipeGestureDetector());\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.main);\n        mContext = this;\n        mViewFlipper = (ViewFlipper) this.findViewById(R.id.view_flipper);\n        mViewFlipper.setOnTouchListener(new OnTouchListener() {\n            @Override\n            public boolean onTouch(final View view, final MotionEvent event) {\n                detector.onTouchEvent(event);\n                return true;\n            }\n        });\n    }\n\n    class SwipeGestureDetector extends SimpleOnGestureListener {\n        @Override\n        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {\n            try {\n                // right to left swipe\n                if (e1.getX() - e2.getX() \u003e SWIPE_MIN_DISTANCE \u0026\u0026 Math.abs(velocityX) \u003e SWIPE_THRESHOLD_VELOCITY) {\n                    mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.left_in));\n                    mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.left_out));\n                    mViewFlipper.showNext();\n                    return true;\n                }
1 else if (e2.getX() - e1.getX() \u003e SWIPE_MIN_DISTANCE \u0026\u0026 Math.abs(velocityX) \u003e SWIPE_THRESHOLD_VELOCITY) {\n                    mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.right_in));\n                    mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext,R.anim.right_out));\n                    mViewFlipper.showPrevious();\n                    return true;\n                }\n\n            } catch (Exception e) {\n                e.printStackTrace();\n            }\n\n            return false;\n        }\n    }\n}\n```\n\nIn the above code, we are using `GestureListener` to identify the swipe gesture and rotate between ViewFlipper child view’s. `showNext()` and `showPrevious()` method’s are used to show the next and previous ViewFlipper child items. All the ViewFlipper items are added statically inside the layout xml file. However you can also add ViewFlipper child items using `addView()` method.\n\n```java\nImageView imageView = new ImageView(this);\nimageView.setImageResource(R.drawable.color_baloons);\nmViewFlipper.addView(imageView);\n```\n\n# 4. Image Slideshow in ViewFlipper\n\nSo far, our example is supporting swipe gesture. But what if we want to implement a slideshow?  \nAndroid `ViewFlipper` support auto flip which can be controlled with `startFlipping()` and `stopFlipping()` method. We can set the auto flip interval using `setFlipInterval(period)`. Note that the interval period is in milliseconds.\n\nTo control the auto flip we will add play and stop buttons. I have inserted the following code right after `ViewFlipper` in my original layout xml file.\n\n```xml\n\u003cLinearLayout\n        style=\"@style/ButtonContainer\"\n        android:orientation=\"horizontal\" \u003e\n\n        \u003cButton\n            android:id=\"@+id/play\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_marginRight=\"10dp\"\n            android:background=\"@android:drawable/ic_media_play\" /\u003e\n\n        \u003cButton\n            android:id=\"@+id/stop\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:background=\"@android:drawable/ic_media_pause\" /\u003e\n    \u003c/LinearLayout\u003e\n```\n\nAdded the following style\n\n```xml\n\u003cstyle name=\"ButtonContainer\"\u003e\n        \u003citem name=\"android:layout_width\"\u003efill_parent\u003c/item\u003e\n        \u003citem name=\"android:layout_height\"\u003e50dp\u003c/item\u003e\n        \u003citem name=\"android:layout_alignParentTop\"\u003etrue\u003c/item\u003e\n        \u003citem name=\"android:background\"\u003e#99000000\u003c/item\u003e\n        \u003citem name=\"android:gravity\"\u003ecenter\u003c/item\u003e\n    \u003c/style\u003e\n```\n\nViewFlipper auto flip can be controlled from java code. add following code in your java class\n\n```java\nfindViewById(R.id.play).setOnClickListener(new OnClickListener() {\n    @Override\n    public void onClick(View view) {\n        //sets auto flipping\n        mViewFlipper.setAutoStart(true);\n        mViewFlipper.setFlipInterval(4000);\n        mViewFlipper.startFlipping();\n    }\n});\n\nfindViewById(R.id.stop).setOnClickListener(new OnClickListener() {\n    @Override\n    public void onClick(View view) {\n        //stop auto flipping\n        mViewFlipper.stopFlipping();\n    }\n});\n```\n\n[![Android ViewFlipper example](/media/articles/409/ViewFlipper-example.png)](http://stacktips.com)\n\n# 5. ViewFlipper Animation and Events\n\nThe ViewFlipper class has derived from `ViewAnimator`. It supports the methods to set the animation for the in and out actions using `setInAnimation()` and `setOutAnimation()`. You can either use some of the default animation that are available in android system or you can write your own animation class.\n\nSometimes we may need to control our screen while animation is started or completed. AnimationListener enables to handle animation events using `onAnimationStart()`, `onAnimationRepeat()` and `onAnimationEnd()` methods.\n\n```java\n//animation listener\nAnimationListener mAnimationListener = new Animation.AnimationListener() {\n    public void onAnimationStart(Animation animation) {\n        //animation started event\n    }\n\n    public void onAnimationRepeat(Animation animation) {\n    }\n\n    public void onAnimationEnd(Animation animation) {\n        //TODO animation stopped event\n    }\n};\n```\n\nNow add the animation listener to `ViewFlipper`.\n\n```java\nmViewFlipper.getInAnimation().setAnimationListener(mAnimationListener);\n```\n\n# 6. Download source code\n\n[Download source](https://github.com/javatechig/Android-UI-Tutorials/tree/master/ViewFlipperExample)\n"])</script>
1<script>self.__next_f.push([1,"152:T1e50,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial demonstrate the usage of ProgressBar while Loading [WebView](/articles/android-webview-example \"Android WebView Example\") contents in android. This example explains horizontal ProgressBar and ProgressBar dialog with WebView.\n\nProgressbar is a visual indicator of progress in some operation. Displays a bar to the user representing how far the operation has progressed; the application can change the amount of progress (modifying the length of the bar) as it moves forward. There is also a secondary progress displayable on a progress bar which is useful for displaying intermediate progress, such as the buffer level during a streaming playback progress bar.\n\nA progress bar can also be made indeterminate. In indeterminate mode, the progress bar shows a cyclic animation without an indication of progress. This mode is used by applications when the length of the task is unknown. The indeterminate progress bar can be either a spinning wheel or a horizontal bar\n\n[![progressbar-android](/media/articles/410/progressbar-android.png)](http://stacktips.com)\n\n## 1. Determinate Progress Bar Example\n\nHere is my layout\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    tools:context=\".WebViewActivity\" \u003e\n\n    \u003cLinearLayout\n        android:id=\"@+id/urlContainer\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:orientation=\"horizontal\" \u003e\n\n        \u003cEditText\n            android:id=\"@+id/urlField\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"3\"\n            android:hint=\"Enter URL to open\" /\u003e\n\n        \u003cButton\n            android:id=\"@+id/goButton\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"1\"\n            android:text=\"Open\" /\u003e\n    \u003c/LinearLayout\u003e\n\n    \u003cProgressBar\n        android:id=\"@+id/progressBar\"\n        style=\"?android:attr/progressBarStyleHorizontal\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_below=\"@id/urlContainer\" /\u003e\n\n    \u003cWebView\n        android:id=\"@+id/webView\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\n        android:layout_below=\"@id/progressBar\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\nDo the following changes in your java code\n\n```java\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\n\npublic class WebViewActivity extends Activity {\n    private WebView webView;\n    private EditText urlEditText;\n    private ProgressBar progress;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_web_view);\n\n        urlEditText = (EditText) findViewById(R.id.urlField);\n        webView = (WebView) findViewById(R.id.webView);\n        webView.setWebChromeClient(new MyWebViewClient());\n\n        progress = (ProgressBar) findViewById(R.id.progressBar);\n        progress.setMax(100);\n\n        Button openUrl = (Button) findViewById(R.id.goButton);\n        openUrl.setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View view) {\n                String url = urlEditText.getText().toString();\n                if (validateUrl(url)) {\n                    webView.getSettings().setJavaScriptEnabled(true);\n                    webView.loadUrl(url);\n\n                    WebViewActivity.this.progress.setProgress(0);\n                }\n            }\n\n            private boolean validateUrl(String url) {\n                return true;\n            }\n        });\n\n    }\n\n    private class MyWebViewClient extends WebChromeClient {\n        @Override\n        public void onProgressChanged(WebView view, int newProgress) {\n            WebViewActivity.this.setValue(newProgress);\n            super.onProgressChanged(view, newProgress);\n        }\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        getMenuInflater().inflate(R.menu.web_view, menu);\n        return true;\n    }\n\n    public void setValue(int progress) {\n        this.progress.setProgress(progress);\n    }\n}\n```\n\nOutput of the above program is\n\n[![progressbar1](/media/articles/410/progressbar1.png)](http://stacktips.com)\n\n## 2. Indeterminate Progress Bar Example\n\nIn the above layout xml file, do the following changes\n\n```xml\n\u003cProgressBar\n        android:id=\"@+id/progressBar\"\n        android:layout_width=\"wrap_content\"\n        android:layout_centerHorizontal=\"true\"\n        android:layout_height=\"wrap_content\"\n        android:layout_below=\"@id/urlContainer\" /\u003e\n```\n\nBelow is my activity java class\n\n```java\nimport android.app.Activity;\nimport android.graphics.Bitmap;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\n\npublic class WebViewActivity extends Activity {\n    private WebView webView;\n    private EditText urlEditText;\n    private ProgressBar progress;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_web_view);\n\n        urlEditText = (EditText) findViewById(R.id.urlField);\n        webView = (WebView) findViewById(R.id.webView);\n        webView.setWebViewClient(new MyWebViewClient());\n\n        progress = (ProgressBar) findViewById(R.id.progressBar);\n        progress.setVisibility(View.GONE);\n        Button openUrl = (Button) findViewById(R.id.goButton);\n        openUrl.setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View view) {\n                String url = urlEditText.getText().toString();
1\n                if (validateUrl(url)) {\n                    webView.getSettings().setJavaScriptEnabled(true);\n                    webView.loadUrl(url);\n\n                }\n            }\n\n            private boolean validateUrl(String url) {\n                return true;\n            }\n        });\n\n    }\n\n    private class MyWebViewClient extends WebViewClient {\n         @Override\n            public boolean shouldOverrideUrlLoading(WebView view, String url) {\n                view.loadUrl(url);\n                return true;\n            }\n\n         @Override\n        public void onPageFinished(WebView view, String url) {\n             progress.setVisibility(View.GONE);\n                WebViewActivity.this.progress.setProgress(100);\n            super.onPageFinished(view, url);\n        }\n\n         @Override\n        public void onPageStarted(WebView view, String url, Bitmap favicon) {\n             progress.setVisibility(View.VISIBLE);\n            WebViewActivity.this.progress.setProgress(0);\n            super.onPageStarted(view, url, favicon);\n        }\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        getMenuInflater().inflate(R.menu.web_view, menu);\n        return true;\n    }\n\n    public void setValue(int progress) {\n        this.progress.setProgress(progress);\n    }\n}\n```\n\nBelow is the Output of the above code\n\n[![progressbar](/media/articles/410/progressbar2.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"153:Tc0d,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains example for using external fonts in Android View. Android applications are capable of loading the external font files with .ttf extension. Follow below simple steps to create an example that uses custom font on TextView.\n\n1.  At first, download a font of your choice. Note that android supports .ttf extension. Here I have downloaded `Maximum.ttf` file.\n2.  Create a new folder `font` in your assets folder and paste your recently downloaded font file.  \n    We can change the font settings for a view simply by adding two lines of code\n\n```java\nTextView textview = (TextView) findViewById(R.id.textView);\nTypeface font = Typeface.createFromAsset(getContext().getAssets(), \"fonts/Maximum.ttf\");\ntextView. setTypeface(font);\n```\n\n3.  This solution will work for you, but sometimes you may have to maintain the theme font across the application for each of the text view you use. You can do that by just extending your class from android TextView. Below is the code to my customized TextView.\n\n```java\nimport android.content.Context;\nimport android.graphics.Typeface;\nimport android.util.AttributeSet;\nimport android.widget.TextView;\n\npublic class CustomTextView extends TextView {\n    public CustomTextView(Context context) {\n        super(context);\n        setFont();\n    }\n    public CustomTextView(Context context, AttributeSet attrs) {\n        super(context, attrs);\n        setFont();\n    }\n    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {\n        super(context, attrs, defStyle);\n        setFont();\n    }\n\n    private void setFont() {\n        Typeface font = Typeface.createFromAsset(getContext().getAssets(), \"fonts/Maximum.ttf\");\n        setTypeface(font, Typeface.NORMAL);\n    }\n}\n```\n\n5.  Now change the following in your android layout xml file\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    android:background=\"#0F0F0F\"\u003e\n\n    \u003ccom.javatechig.droid.ui.CustomTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"@string/font_sample_text\"\n        android:textSize=\"18dp\"\n        android:textColor=\"#AAD4DE\" /\u003e\n\n    \u003ccom.javatechig.droid.ui.CustomTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"@string/font_sample_text\"\n        android:textColor=\"#FFDE46\"\n        android:textSize=\"24dp\"/\u003e\n\n    \u003ccom.javatechig.droid.ui.CustomTextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"@string/font_sample_text\"\n        android:textSize=\"30dp\"\n        android:textColor=\"#7FBA00\"/\u003e\n\u003c/LinearLayout\u003e\n```\n\nHere is the output of the above code\n\n[![](/media/articles/411/custom-font-android.png)](http://stacktips.com)\n\n\\[download src=”https://github.com/javatechig/Android-UI-Tutorials/tree/master/AndroidCustomFont”\\]\n"])</script>
1<script>self.__next_f.push([1,"154:Tce9,"])</script>
1<script>self.__next_f.push([1,"\nHandler and AsyncTasks are way to implement multithreading in android with UI/Event Thread. Handler is available since Android API level 1 \u0026 AsyncTask is available since API level 3.\n\n# What is Handler?\n\n1.  Handler allows to add messages to the thread which creates it and It also enables you to schedule some runnable to execute at some time in future.\n2.  The Handler is associated with the application’s main thread. It handles and schedules messages and runnables sent from background threads to the app main thread.\n3.  If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews (like downloading thumbnails) upon download, use a task queue with Handler.\n4.  There are two main uses for a Handler. First is to schedule messages and runnables to be executed as some point in the future; and second Is to enqueue an action to be performed on a different thread than your own.\n5.  Scheduling messages is accomplished with the the methods like `post(Runnable)`, `postAtTime(Runnable, long)`, `postDelayed(Runnable, long)`, `sendEmptyMessage(int)`, `sendMessage(Message)`, `sendMessageAtTime(Message, long)`, and `sendMessageDelayed(Message, long)` methods.\n6.  When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create.\n7.  You can create your own threads, and communicate back with the main application thread through a Handler.\n\n# What is AsyncTask ?\n\n1.  Async task enables you to implement multi threading without get hands dirty into threads. AsyncTask enables proper and easy use methods that allows performing background operations and passing the results back to the UI thread.\n2.  If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use `AsyncTask`.\n3.  AsyncTasks should ideally be used for short operations (a few seconds at the most.)\n4.  An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.\n5.  In onPreExecute you can define code, which need to be executed before background processing starts.\n6.  `doInBackground` have code which needs to be executed in background, here in doInBackground we can send results to multiple times to event thread by `publishProgress()` method, to notify background processing has been completed we can return results simply.\n7.  `onProgressUpdate()` method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread\n8.  `onPostExecute()` method handles results returned by doInBackground\n9.  The generic types used are\n    -   `Params`, the type of the parameters sent to the task upon execution,\n    -   `Progress`, the type of the progress units published during the background computation.\n    -   `Result`, the type of the result of the background computation.\n10.  If an async task not using any types, then it can be marked as Void type.\n11.  An running async task can be cancelled by calling cancel(boolean) method.\n"])</script>
1<script>self.__next_f.push([1,"155:T1b6d,"])</script>
1<script>self.__next_f.push([1,"\nAndroid supports seamless integration of applications and content providers. Lot many things are handy provided to developers, which helps in reducing the code and consumes less time to integrate different features to app.\n\nFor example, if we have an application that allow user to change his profile picture. In this requirement user will be welling to browse his mobile gallery and pick a picture of his own to set his profile picture. Integrating this feature in traditional operating system, need lot of effort write code to integrate file browser. But in android we can use `Intent.ACTION_PICK` action to get this feature integrated in not more than five minutes.\n\n# What is intent in android?\n\nIntent is an abstract description of an operation to be performed. It can be used with `startActivity` to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and `startService(Intent)` or `bindService(Intent, ServiceConnection, int)` to communicate with a background Service.\n\nIntent provides a facility for performing late run-time binding between the codes in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.\n\n# Writing image picker using Intent.ACTION\\_PICK in android\n\n`Intent.ACTION_PICK` action is in buit in android and helps to pick an image item from a data source. We just need to provide the URI of the provider. Almost all core android applications (eg. Messaging, Gallery, Contacts etc) provide this facility. All you need is to set the intent action and the data.\n\n**action** – tells what to perform, such as `ACTION_VIEW`, `ACTION_EDIT`, `ACTION_MAIN`, etc.  \n**data**– data needed to operate the action. It is expressed as uri. Example such as a person record in the contacts database. Some examples of action/data pairs are:\n\nACTION\\_VIEW content://contacts/people/1 — Display information about the person whose identifier is “1”.  \nACTION\\_DIAL content://contacts/people/1 — Display the phone dialer with the person filled in.  \nACTION\\_VIEW tel:123 — Display the phone dialer with the given number filled in. Note how the VIEW action does what what is considered the most reasonable thing for a particular URI.  \nACTION\\_DIAL tel:123 — Display the phone dialer with the given number filled in.\n\nThere are also some more additional attributes. Visit the below llink for more details\n\n**[http://developer.android.com/reference/android/content/Intent.html](http://developer.android.com/reference/android/content/Intent.html \"developer.android.com\")**\n\n## Creating layout Code Snippet\n\nAs you can see in the screenshot below, my example is using simple LinearLayout with a ImageView and a button aligned to vertical orientation. You may have some complex layout as per your needs.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:orientation=\"vertical\"\n    tools:context=\".ImagePickerActivity\" \u003e\n\n    \u003cImageView\n        android:id=\"@+id/imageView\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center_horizontal\"\n        android:maxHeight=\"200dp\"\n        android:src=\"@drawable/ic_launcher\" /\u003e\n\n    \u003cButton\n        android:id=\"@+id/btn_pick\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center\"\n        android:layout_marginTop=\"20dp\"\n        android:text=\"@string/change_image\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n## Activity class Code Snippet\n\nBelow is my activity class using `Intent.ACTION_PICK` action\n\n```java\npackage com.javatechig.filepicker;\n\nimport java.io.FileNotFoundException;\nimport java.io.InputStream;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.view.Menu;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.ImageView;\n\npublic class ImagePickerActivity extends Activity {\n\n    private final int SELECT_PHOTO = 1;\n    private ImageView imageView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_image_picker);\n\n        imageView = (ImageView)findViewById(R.id.imageView);\n\n        Button pickImage = (Button) findViewById(R.id.btn_pick);\n        pickImage.setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View view) {\n                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);\n                photoPickerIntent.setType(\"image/*\");\n                startActivityForResult(photoPickerIntent, SELECT_PHOTO);\n            }\n        });\n    }\n\n    @Override\n    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {\n        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);\n\n        switch(requestCode) {\n        case SELECT_PHOTO:\n            if(resultCode == RESULT_OK){\n                try {\n                    final Uri imageUri = imageReturnedIntent.getData();\n                    final InputStream imageStream = getContentResolver().openInputStream(imageUri);\n                    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);\n                    imageView.setImageBitmap(selectedImage);\n                } catch (FileNotFoundException e) {\n                    e.printStackTrace();\n                }\n\n            }\n        }\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        return true;\n    }\n}\n```\n\nAs you can see the code snippet used is pretty simple. Here in this example, I am handling button click event and their Image picker using `Intent.ACTION_PICK` has been called. `setType()` method is used to define the file filter criteria. This will invoke the default gallery and user will be able to select an image.\n\nOnce image is selected, the result will be back to our main activity, and the result will be returned to `onActivityResult()` method. Here we are receiving the selected image Uri. Once we have the uri, we can convert them to `Bitmap` and then dis
1play it on `ImageView`. Below coded snippet is used to get the image from the Uri and convert into bitmap.\n\n```java\nInputStream imageStream = getContentResolver().openInputStream(imageUri);\nBitmap selectedImage = BitmapFactory.decodeStream(imageStream);\n```\n\nAnd now we are done.\n\n## Output of the above code is below\n\n[![image picker example in anroid](/media/articles/416/image-picker-example-in-anroid-javatechig.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"156:Td91,"])</script>
1<script>self.__next_f.push([1,"\nTypically events do responds to user interactions. Android platform supports multiple ways to handle the events on View’s. When user clicks on an Android View, some method is getting called by the android framework and then passed the control to the application listeners.\n\nFor example, when a user clicks on a view such as a Button, the `onTouchEvent()` method is called on that Button object. In order to make our application to responds to the event we must extend the class and override the method. But extending every View object in order to handle such an event would not be practical. Each View classes in Android provide collection of nested interfaces called listeners with callbacks that you can much more easily define in order to handle event.\n\n# 1. Anonymus click listener\n\n```java\nbutton.setOnClickListener(new OnClickListener(){\n    @Override\n    public void onClick(View v) {\n        //do stuff\n    }\n});\n```\n\nThis way will create anonymous classes as much as you create buttons. This is recommended only if you have fewer listener in your class. But if we have a complex screen layout with many view’s then writing a listener programmatically for each view will make the code messy. Its less readable and costly\n\n# 2. Using android:OnClick layout attribute\n\n```xml\n\u003cButton android:id=\"@+id/btnView\"\n    ...............\n    ...............\n    android:OnClick=\"btnViewOnClick\"/\u003e\n```\n\nMany people use this way of handling the click events by writing `OnClick` attribute in XML. But, usually it is not preferable as I because better to keep listeners inside code. Internally android is using java reflection concept behind the scene to handle this. It is less readable, and confuses other developers.\n\n# 3. Using OnClickListener interface on the Activity\n\n```java\npublic class MainActivity extends Activity implements OnClickListener{\n    @Override\n    public void onClick(View v) {\n        //do stuff\n    }\n\n    protected void onCreate(Bundle savedInstanceState) {\n        ...\n        button.setOnClickListener(this);\n    }\n}\n```\n\nHere we are implementing the `OnClickListener` interface on the Activity class and passing a self reference to the Button. This way the onclick listener will hold the reference to the activity object, and so it is a heavy operation to keep the whole activity’s object in it.\n\nThis way we can handle the click event for all views. However, we need to differentiate view’s using their id’s. We can use `view.getId()` method to see which button was clicked. Again, this is preferable only when we have fewer views to handle. This way all the click event handling codes are done at one place.\n\nThis way is hard to navigate through, because you can’t determine the type of the listener you are using with current button (I know eclipse will highlight the methods this are pointing at, but with huge code I think it will be hard to find).\n\n# 4. Creating the OnClickListener field\n\n```java\nprivate OnClickListener onClickHandler = new OnClickListener(){\n\n    @Override\n    public void onClick(View v) {\n        //stuff\n    }\n};\n\nprotected void onCreate(Bundle savedInstanceState) {\n    ...\n    button.setOnClickListener(onClickHandler);\n}\n```\n\nThe best practice is the create a local variable with the `OnClickListener` type. This way it is easy to navigate and more readable. But it doesn’t stop you to implement the other three options provided above. Just that every one has different way of looking at the problem.\n"])</script>
1<script>self.__next_f.push([1,"157:T31fb,"])</script>
1<script>self.__next_f.push([1,"\nIn this example we will learn about creating a simple 4×2 home screen App widget using an App Widget provider. It shall show two text view and a button. and clicking on the button will change the widget text contents.\n\n## 1. Introduction\n\nApp widget is a simple way to enhance your application by having a view on android HomeScreen. This helps to inform user about some important update about the application also this is help user to use the application over and often. App Widgets I available since API Level 3 (Android 1.5). To create an App Widget we need the following classes.\n\n## 2. Creating View layout for Widget\n\nWidget layout can be defined in XML and can be saved in project’s res/layout/ directory. Currently App Widget layouts are based on RemoteViews and android currently supports limited View widget. Creating layout for the widget is same as creating the layout for other activity type. But to make a good widget we need to follow the android widget guidelines.\n\nA RemoteViews object or App Widget currently supports the following layout classes\n\n-   FrameLayout\n-   LinearLayout\n-   RelativeLayout\n-   GridLayout\n\nSupported widget classes are\n\n-   AnalogClock\n-   Button\n-   Chronometer\n-   ImageButton\n-   ImageView\n-   ProgressBar\n-   TextView\n-   ViewFlipper\n-   ListView\n-   GridView\n-   StackView\n-   AdapterViewFlipper\n\nFor our example we will take a simple layout with two TextField and a button. Pressing on the button it will change the content on the widget. below is my widget-layout\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:layout_margin=\"5sp\"\n    android:background=\"@drawable/appwidget_dark_bg\"\n    android:orientation=\"vertical\" \u003e\n\n    \u003cRelativeLayout\n        android:id=\"@+id/buttonContainer\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentBottom=\"true\" \u003e\n\n        \u003cButton\n            android:id=\"@+id/sync_button\"\n            android:layout_width=\"30dp\"\n            android:layout_height=\"30dp\"\n            android:layout_centerInParent=\"true\"\n            android:background=\"@drawable/ic_sync_button\"\n            android:text=\"\" /\u003e\n    \u003c/RelativeLayout\u003e\n\n    \u003cLinearLayout\n        android:id=\"@+id/contentContainer\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_above=\"@id/buttonContainer\"\n        android:layout_alignParentTop=\"true\"\n        android:orientation=\"vertical\"\n        android:padding=\"8dp\" \u003e\n\n        \u003cTextView\n            android:id=\"@+id/title\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"wrap_content\"\n            android:maxLines=\"2\"\n            android:paddingBottom=\"5dp\"\n            android:text=\"\"\n            android:textColor=\"#fcfcfc\"\n            android:textSize=\"16sp\"\n            android:textStyle=\"bold\" /\u003e\n\n        \u003cTextView\n            android:id=\"@+id/desc\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"wrap_content\"\n            android:maxLines=\"5\"\n            android:text=\"\"\n            android:textColor=\"#fcfcfc\"\n            android:textSize=\"13sp\"\n            android:textStyle=\"normal\" /\u003e\n    \u003c/LinearLayout\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n## 3. Creating AppWidgetProviderInfo in XML\n\nThis is used to describe the metadata for an App Widget, such as the App Widget’s layout, update frequency, and the AppWidgetProvider class. This is always defined as XML file.\n\nBelow is my AppWidgetProvider xml configuration file\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cappwidget-provider xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:initialLayout=\"@layout/widget_layout\"\n    android:minHeight=\"146dp\"\n    android:minWidth=\"292dp\"\n    android:previewImage=\"@drawable/widget\"\n    android:updatePeriodMillis=\"1000000\" \u003e\n\u003c/appwidget-provider\u003e\n```\n\nThe minWidth and minHeight attribute is used to specify the minimum amount of space the App Widget consumes by default. The default Home screen positions App Widgets in its window based on a grid of cells that have a defined height and width. If the values for an App Widget’s minimum width or height don’t match the dimensions of the cells, then the App Widget dimensions round up to the nearest cell size.\n\nTo make your app widget portable across devices, your app widget’s minimum size should never be larger than 4 x 4 cells. Check out the below link for the App Widget Design Guidelines\n\n[http://developer.android.com/guide/practices/ui\\_guidelines/widget\\_design.html](http://developer.android.com/guide/practices/ui_guidelines/widget_design.html \"Android App Widget Design Guidelines\")\n\nThe updatePeriodMillis attribute defines the update timer for the App Widget framework. It calls AppWidgetProvider by calling the onUpdate() callback method. This update timer is not guaranteed to refresh exactly on the same time.  \nNote: The lesser the refresh timer, consumes more battery. It is better to always provide user an option to select the refresh timer frequency.\n\nThe initialLayout attribute points to the layout resource that defines the App Widget layout.\n\n### 3.1 Setting preview image to Android App Widget\n\nYou can set a preview image to specify what the app widget will look like on the widgets list screen. This help users to know about the widget while configuration. This is optional configuration, if not provided then the application icon will be displayed as default widget preview image.\n\n**Note: This attribute is introduced from Android 3.0**\n\nYou can set the preview image using the following code\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cappwidget-provider xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    ...................\n    ...................\n    android:previewImage=\"@drawable/widget\"\n\u003c/appwidget-provider\u003e\n```\n\n### 3.2 How to make Android App Widget re sizable\n\nThe resizeMode attribute is used to specify whether the widget can be resizable on the home screen. Android home screen widget can be resized horizontally, vertically, or on both axes. We can resize a widget by touch-holding a widget on home screen. resizeMode attribute can be configured to either “horizontal”, “vertical”, and “none”. We can also define a widget resizable to both directions by specifying “horizontal|vertical”.\n\n**Note: This attribute is introduced from Android 3.1**\n\n## 4. Implementing AppWidgetProvider class\n\nNow we need to add a class extending AppWidgetProvider which will be used to control the behavior of the widget. The onUpdate() call back method is used to change the text view text at runtime. This class is used to interface with the App Widget, based on broadcast events. Using AppWidgetProvider we can receive broadcast events while the App Widget state has been updated, enabled, disabled or deleted.\n\n```java\npackage com.javatechig.widgetdemo;\n\nimport android.app.PendingIntent;\nimport android.appwidget.AppWidgetManager;\nimport android.appwidget.AppWidgetProvider;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.widget.RemoteViews;\n\npublic class MyWidgetProvider extends AppWidgetProvider {\n    @Override\n    public void onUpdate(Context context, AppWidgetManager appWidgetManager,\n            int[] appWidgetIds) {\n\n        // initializing widget layout\n        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),\n                R.layout.widget_layout);\n\n        // register for button event\n        remoteViews.setOnClickPendingIntent
1(R.id.sync_button,\n                buildButtonPendingIntent(context));\n\n        // updating view with initial data\n        remoteViews.setTextViewText(R.id.title, getTitle());\n        remoteViews.setTextViewText(R.id.desc, getDesc());\n\n        // request for widget update\n        pushWidgetUpdate(context, remoteViews);\n    }\n\n    public static PendingIntent buildButtonPendingIntent(Context context) {\n        ++MyWidgetIntentReceiver.clickCount;\n\n        // initiate widget update request\n        Intent intent = new Intent();\n        intent.setAction(WidgetUtils.WIDGET_UPDATE_ACTION);\n        return PendingIntent.getBroadcast(context, 0, intent,\n                PendingIntent.FLAG_UPDATE_CURRENT);\n    }\n\n    private static CharSequence getDesc() {\n        return \"Sync to see some of our funniest joke collections\";\n    }\n\n    private static CharSequence getTitle() {\n        return \"Funny Jokes\";\n    }\n\n    public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) {\n        ComponentName myWidget = new ComponentName(context,\n                MyWidgetProvider.class);\n        AppWidgetManager manager = AppWidgetManager.getInstance(context);\n        manager.updateAppWidget(myWidget, remoteViews);\n    }\n}\n```\n\n## 5. Writing BroadcastReceiver for your widget\n\nNow, we will write a BroadcastReciever to perform action on the button click. This implementation is pretty straight forward. The onReceive() method is requesting the app widget provider for updating the widget.\n\n```java\npackage com.javatechig.widgetdemo;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.widget.RemoteViews;\n\npublic class MyWidgetIntentReceiver extends BroadcastReceiver {\n    public static int clickCount = 0;\n    private String msg[] = null;\n\n    @Override\n    public void onReceive(Context context, Intent intent) {\n        if (intent.getAction().equals(WidgetUtils.WIDGET_UPDATE_ACTION)) {\n            updateWidgetPictureAndButtonListener(context);\n        }\n    }\n\n    private void updateWidgetPictureAndButtonListener(Context context) {\n        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),\n                R.layout.widget_layout);\n\n        // updating view\n        remoteViews.setTextViewText(R.id.title, getTitle());\n        remoteViews.setTextViewText(R.id.desc, getDesc(context));\n\n        // re-registering for click listener\n        remoteViews.setOnClickPendingIntent(R.id.sync_button,\n                MyWidgetProvider.buildButtonPendingIntent(context));\n\n        MyWidgetProvider.pushWidgetUpdate(context.getApplicationContext(),\n                remoteViews);\n    }\n\n    private String getDesc(Context context) {\n        // some static jokes from xml\n        msg = context.getResources().getStringArray(R.array.news_headlines);\n        if (clickCount \u003e= msg.length) {\n            clickCount = 0;\n        }\n        return msg[clickCount];\n    }\n\n    private String getTitle() {\n        return \"Funny Jokes\";\n    }\n}\n```\n\n## 6. Registering receiver in in Android Manifest\n\nFinally, we need to register the app widget in your application Manifest file. To do this, you will use the tag. This block of XML should be placed inside the application tag in application Manifest.\n\n```xml\n\u003creceiver android:name=\".MyWidgetProvider\" \u003e\n            \u003cintent-filter\u003e\n                \u003caction android:name=\"android.appwidget.action.APPWIDGET_UPDATE\" /\u003e\n            \u003c/intent-filter\u003e\n\n            \u003cmeta-data\n                android:name=\"android.appwidget.provider\"\n                android:resource=\"@xml/demo_widget_provider\" /\u003e\n        \u003c/receiver\u003e\n\n        \u003creceiver\n            android:name=\".MyWidgetIntentReceiver\"\n            android:label=\"@string/app_name\" \u003e\n            \u003cintent-filter\u003e\n                \u003caction android:name=\"com.javatechig.intent.action.UPDATE_WIDGET\" /\u003e\n            \u003c/intent-filter\u003e\n\n            \u003cmeta-data\n                android:name=\"android.appwidget.provider\"\n                android:resource=\"@xml/demo_widget_provider\" /\u003e\n        \u003c/receiver\u003e\n```\n\nNote that the receiver name is the name of your app widget provider class implementation. We add an intent filter for the UPDATE\\_WIDGET event such that your widget will update at regular intervals.\n\n## 7. Working Demo\n\nNow we have an app widget! From the Home screen, press and hold an empty space to get list if widgets instlled, then choose “WidgetDemo” from the list. The app widget will then be added to your Home screen. You can watch a live video of the tutorial below\n\n{{\u003c youtube AguqhQHHrcs \u003e}}\n\n## 8. Download Complete Source Code\n\n[![dl_github](/media/articles/419/dl_github.png)](https://github.com/javatechig/Advance-Android-Tutorials/tree/master/WidgetDemo)\n\n## 9. References\n\n[http://developer.android.com/guide/topics/appwidgets/index.html](http://developer.android.com/guide/topics/appwidgets/index.html)  \n[http://developer.android.com/guide/practices/ui\\_guidelines/widget\\_design.html](http://developer.android.com/guide/practices/ui_guidelines/widget_design.html)\n"])</script>
1<script>self.__next_f.push([1,"158:T45b5,"])</script>
1<script>self.__next_f.push([1,"\nIn the course of this tutorial, we will take step by step look into building a JSON feed reader in Android. All the source code used in this example, are open source. You may grab a copy of the project source code from the download link provided.\n\nThis app will fetch the recent posts from stacktips.com and display list of posts along with post title, thumbnail, description on screen. You can also view details of each feed, share the article and can view the article on original website using Android `WebView`.\n\n#### JSON Feed URL\n\n```text\nhttp://stacktips.com/api/get_category_posts/?dev=1\u0026slug=android\n```\n\nYou will learn following things in this article.\n\n-   Designing User Interface\n-   Using AsyncTask to Download Data From Remote Server\n-   JSON Parsing In Android\n-   Downloading Image Asynchronously and Displaying In Android ListView\n-   Using Share Intent to Share Article in Android\n-   Loading Original Feed Link on Android WebView\n\n# 1. Designing User Interface\n\nHere in this example, we are using three Activities. While first Activity is used to list out all feed items on a ListView, Second one is used to show the image preview and the description of each feed. Another Activity is used to view the original feed item on a WebView.\n\nBelow are the listed three activity classes\n\n-   com.javatechig.feedreader.FeedDetailsActivity\n-   com.javatechig.feedreader.FeedListActivity\n-   com.javatechig.feedreader.WebViewActivity\n\nIn this tutorial, I assume you already have knowledge of creating basic user interfaces. We will be creating the layouts as shown in the images below.\n\n[![json-feed-reader-android-featured-715x300](/media/articles/420/json-feed-reader-android-featured-715x300.png)](http://stacktips.com)\n\nOn landing page of my example, It uses a ListView which can display thumbnail image, title and date published, so here we need to create a custom ListView. If you are not proficient on creating such custom ListView, then you may visit my previous post on Android ListView Tutorial.\n\nFor simplicity sake, our previous ListView Tutorial was using static data for list. But in this example, I am fetching the data from [JavatechIG](http://stacktips.com/ \"JavatechIG\") feed server and then displaying on list view. During fetching data from server it will display a loading ProgressBar on screen and disappears once the list items are downloaded. Let’s start getting our the code to build the user interface set up.\n\n#### activity\\_post\\_list.xml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cFrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:orientation=\"vertical\" \u003e\n\n    \u003cProgressBar\n        android:id=\"@+id/progressBar\"\n        style=\"?android:attr/progressBarStyleLarge\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center\" /\u003e\n\n    \u003cListView\n        android:id=\"@+id/custom_list\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\n        android:cacheColorHint=\"#00000000\"\n        android:dividerHeight=\"1dp\"\n        android:focusable=\"false\"\n        android:listSelector=\"@drawable/list_selector_flatcolor\"\n        android:visibility=\"gone\" /\u003e\n\n\u003c/FrameLayout\u003e\n```\n\nIn the above xml code, we are using FrameLayout. We will be displaying either of the UI widgets. During loading we will display ProgressBar and then we will display ListView after feed data is downloaded.\n\n#### list\\_row\\_layout.xml\n\nThis layout will be used for ListView row. Each Row is an RelativeLayout with an ImageView and two TextViews placed adjacent to ImageView.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:minHeight=\"50dp\"\n    android:orientation=\"horizontal\" \u
1003e\n\n    \u003cImageView\n        android:id=\"@+id/thumbImage\"\n        android:layout_width=\"70dp\"\n        android:layout_height=\"70dp\"\n        android:layout_alignParentLeft=\"true\"\n        android:layout_centerVertical=\"true\"\n        android:background=\"@drawable/list_placeholder\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/title\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_toRightOf=\"@id/thumbImage\"\n        android:lineSpacingExtra=\"3dp\"\n        android:paddingLeft=\"5dp\"\n        android:paddingTop=\"5dp\"\n        android:text=\"\"\n        android:textColor=\"@drawable/list_item_text_selector\"\n        android:textStyle=\"bold\"\n        android:typeface=\"sans\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/date\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_below=\"@+id/title\"\n        android:layout_toRightOf=\"@id/thumbImage\"\n        android:paddingLeft=\"5dp\"\n        android:paddingTop=\"5dp\"\n        android:text=\"\"\n        android:textColor=\"@drawable/list_item_text_selector\"\n        android:textSize=\"11sp\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\nIn the above code, I have used “list\\_item\\_text\\_selector” for changing the TextView color while list row is pressed.\n\n#### list\\_item\\_text\\_selector.xml\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cselector xmlns:android=\"http://schemas.android.com/apk/res/android\"\u003e\n    \u003citem android:state_pressed=\"true\"\n        android:color=\"@color/text_color_inverse\" /\u003e\n    \u003citem android:state_focused=\"true\"\n        android:color=\"@color/text_color_inverse\" /\u003e\n    \u003citem android:color=\"@color/text_color_default\" /\u003e\n\u003c/selector\u003e\n```\n\nWe are ready with the layout for FeedList Screen. Now lets create a custom Adapter.\n\n#### CustomListAdapter.java\n\n```java\npublic class CustomListAdapter extends BaseAdapter {\n    private ArrayList listData;\n    private LayoutInflater layoutInflater;\n    private Context mContext;\n\n    public CustomListAdapter(Context context, ArrayList listData) {\n        this.listData = listData;\n        layoutInflater = LayoutInflater.from(context);\n        mContext = context;\n    }\n\n    @Override\n    public int getCount() {\n        return listData.size();\n    }\n\n    @Override\n    public Object getItem(int position) {\n        return listData.get(position);\n    }\n\n    @Override\n    public long getItemId(int position) {\n        return position;\n    }\n\n    public View getView(int position, View convertView, ViewGroup parent) {\n        ViewHolder holder;\n        if (convertView == null) {\n            convertView = layoutInflater.inflate(R.layout.list_row_layout, null);\n            holder = new ViewHolder();\n            holder.headlineView = (TextView) convertView.findViewById(R.id.title);\n            holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);\n            holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);\n            convertView.setTag(holder);\n        } else {\n            holder = (ViewHolder) convertView.getTag();\n        }\n\n        FeedItem newsItem = (FeedItem) listData.get(position);\n        holder.headlineView.setText(newsItem.getTitle());\n        holder.reportedDateView.setText(newsItem.getDate());\n\n        if (holder.imageView != null) {\n            new ImageDownloaderTask(holder.imageView).execute(newsItem.getAttachmentUrl());\n        }\n\n        return convertView;\n    }\n\n    static class ViewHolder {\n        TextView headlineView;\n        TextView reportedDateView;\n        ImageView imageView;\n    }\n}\n```\n\nNow you must be getting some compilation error for FeedItem. FeedItem is an model class used for reading feeds. It has the following fields with public getter and setter methods.\n\n#### FeedItem.java\n\n```java\npublic class FeedItem implements Serializable {\n    private String title;\n    private String date;\n    private String attachmentUrl;\n    private String id;\n    private String content;\n    private String url;\n}\n```\n\nNow, we are ready for the first screen layout. Let’s move on to the FeedDetail
1sActivity layout. In this screen we have thumbnail image, title and the content to be displayed. Below is the layout code snippet.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:background=\"#ffffff\"\n    android:orientation=\"vertical\" \u003e\n\n    \u003cRelativeLayout\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"200dp\" \u003e\n\n        \u003cImageView\n            android:id=\"@+id/featuredImg\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"fill_parent\" \u003e\n        \u003c/ImageView\u003e\n\n        \u003cTextView\n            android:id=\"@+id/title\"\n            android:layout_width=\"fill_parent\"\n            android:layout_height=\"100dp\"\n            android:layout_alignParentBottom=\"true\"\n            android:background=\"@drawable/image_border\"\n            android:ellipsize=\"end\"\n            android:gravity=\"bottom\"\n            android:lineSpacingExtra=\"3dp\"\n            android:maxLines=\"2\"\n            android:padding=\"5dp\"\n            android:text=\"\"\n            android:textColor=\"#00000c\"\n            android:textStyle=\"bold\" /\u003e\n    \u003c/RelativeLayout\u003e\n\n    \u003cScrollView\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\n        android:padding=\"5dp\" \u003e\n\n        \u003cTextView\n            android:id=\"@+id/content\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:text=\"\"\n            android:textColor=\"#00000c\" /\u003e\n    \u003c/ScrollView\u003e\n\n\u003c/LinearLayout\u003e\n```\n\nIn FeedDetailsActivity, we are using Android ActionBar commands.\n\n##### menu.xml\n\n```xml\n\u003cmenu xmlns:android=\"http://schemas.android.com/apk/res/android\" \u003e\n\n    \u003citem\n        android:id=\"@+id/menu_share\"\n        android:icon=\"@android:drawable/ic_menu_share\"\n        android:showAsAction=\"always\"\n        android:title=\"Share\"/\u003e\n    \u003citem\n        android:id=\"@+id/menu_view\"\n        android:icon=\"@android:drawable/ic_menu_info_details\"\n        android:showAsAction=\"always\"\n        android:title=\"View\"/\u003e\n\n\u003c/menu\u003e\n```\n\nNow we are done with all xml layouts. Let us have a look into the Activity components\n\n# 2. AsyncTask to Download Data from Server\n\nAsyncTask enables you to implement MultiThreading without get Hands dirty into threads. AsyncTask enables proper and easy use of the UI thread. It allows performing background operations and passing the results on the UI thread. If we are doing something isolated related to UI, for example downloading data and prepare for a list, it is recemended to use AsyncTask.\n\n**[http://stacktips.com/android/difference-between-handler-and-asynctask-in-android/](http://stacktips.com/android/difference-between-handler-and-asynctask-in-android/)**\n\n#### DownloadFeedTask.java\n\n```java\nprivate class DownloadFilesTask extends AsyncTask\u003cString, Integer, Void\u003e {\n\n        @Override\n        protected void onProgressUpdate(Integer... values) {\n        }\n\n        @Override\n        protected void onPostExecute(Void result) {\n            if (null != feedList) {\n                updateList();\n            }\n        }\n\n        @Override\n        protected Void doInBackground(String... params) {\n            String url = params[0];\n\n            // getting JSON string from URL\n            JSONObject json = getJSONFromUrl(url);\n\n            //parsing json data\n            parseJson(json);\n            return null;\n        }\n    }\n```\n\n#### Downloading JSON from server\n\nAs downloading of feed data from JavatechIG is a long running task, we are doing it inside doInBackground method. Once we have the data downloaded and parsed, then we can update the ListView with appropriate updated data.\n\n```java\npublic JSONObject getJSONFromUrl(String url) {\n        InputStream is = null;\n        JSONObject jObj = null;\n        String json = null;\n\n        // Making HTTP request\n        try {\n            // defaultHttpClient\n            DefaultHttpClient httpClient = new DefaultHttpClient();\n            HttpPost httpPost = new HttpPost(url);\n\n            HttpResponse httpResponse = httpClient.execute(httpPost);\n            HttpEntity httpEntity = httpResponse.getEntity();\n            is = httpEntity.getContent();\n\n            BufferedReader reader = new BufferedReader(new InputStreamReader(\n                    is, \"iso-8859-1\"), 8);\n            StringBuilder sb = new StringBuilder();\n            String line = null;\n            while ((line = reader.readLine()) != null) {\n                sb.append(line + \"\\n\");\n            }\n            is.close();\n            json = sb.toString();\n        } catch (UnsupportedEncodingException e) {\n            e.printStackTrace();\n        } catch (ClientProtocolException e) {\n            e.printStackTrace();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        try {\n            jObj = new JSONObject(json);\n        } catch (JSONException e) {\n            Log.e(\"JSON Parser\", \"Error parsing data \" + e.toString());\n        }\n\n        // return JSON String\n        return jObj;\n\n    }\n```\n\nThe above method will download the Json feed and returned as a JSONObject. Now its the time to parse the JSON feed data\n\n# 3. JSON Parsing In Android\n\nThe aove Feed link gives the below JSON object structure.\n\n```json\n{\n   \"status\": \"ok\",\n   \"count\": 10,\n   \"pages\": 3,\n   \"posts\": [\n      {\n         \"id\": 2398,\n         \"type\": \"post\",\n         \"slug\": \"asynchronous-image-loader-in-android-listview\",\n         \"url\": \"http://stacktips.com/android/asynchronous-image-loader-in-android-listview/\",\n         \"status\": \"publish\",\n         \"title\": \"Asynchronous Image Loader in Android ListView\",\n         \"date\": \"2013-06-01 19:31:07\",\n         \"attachments\": [\n            {\n               \"id\": 2402,\n               \"url\": \"http://stacktips.com/w
1p-content/uploads/2013/06/Async_ListView.png\",\n               \"slug\": \"async_listview\",\n               \"title\": \"Async_ListView\",\n               \"description\": \"\",\n               \"caption\": \"\",\n               \"parent\": 2398,\n               \"mime_type\": \"image/png\",\n               \"images\": []\n            }\n         ],\n         \"comment_count\": 3\n      }\n   ]\n}\n```\n\nFrom this above structure we will be needing the title, date, url and attachment url. check out the code snippet below for json parsing.\n\n```java\npublic void parseJson(JSONObject json) {\n    try {\n\n        // parsing json object\n        if (json.getString(\"status\").equalsIgnoreCase(\"ok\")) {\n            JSONArray posts = json.getJSONArray(\"posts\");\n\n            feedList = new ArrayList();\n\n            for (int i = 0; i \u003c posts.length(); i++) {\n                JSONObject post = (JSONObject) posts.getJSONObject(i);\n                FeedItem item = new FeedItem();\n                item.setTitle(post.getString(\"title\"));\n                item.setDate(post.getString(\"date\"));\n                item.setId(post.getString(\"id\"));\n                item.setUrl(post.getString(\"url\"));\n                item.setContent(post.getString(\"content\"));\n                JSONArray attachments = post.getJSONArray(\"attachments\");\n                if (null != attachments \u0026\u0026 attachments.length() \u003e 0) {\n                    JSONObject attachment = attachments.getJSONObject(0);\n                    if (attachment != null)\n                    item.setAttachmentUrl(attachment.getString(\"url\"));\n                }\n\n                feedList.add(item);\n            }\n        }\n        } catch (JSONException e) {\n        e.printStackTrace();\n    }\n}\n```\n\n# 4. Downloading Image Asynchronously\n\nA good practice to bring the best performance for android application is to make sure your main thread does the minimum amount of work. Any long running tasks or heavy operations are usually performed in a different thread. Typical long running tasks could be network operations, reading files form memory, animations, etc.\n\nCheck out the below post for detailed implementation\n\n[http://stacktips.com/android/asynchronous-image-loader-in-android-listview/](http://stacktips.com/android/asynchronous-image-loader-in-android-listview/)\n\n# 5. Share Article in Android\n\nOne of the best and most useful feature is sharing of information across different social networks. Android platform provides handy way of sharing contents across different application using Share Intent. It lists out all of the available application that can handle the share event. Check out the code snippet\n\n```java\nIntent sendIntent = new Intent();\nsendIntent.setAction(Intent.ACTION_SEND);\nsendIntent.putExtra(Intent.EXTRA_TEXT, feed.getTitle()+\"\\n\"+feed.getUrl());\nsendIntent.setType(\"text/plain\");\nstartActivity(Intent.createChooser(sendIntent, \"Share using\"));\n```\n\nNote: As sharing intent is taken care by platform, we don’t have control on the way and behavior of each application while sharing. For example, twitter has a limit of maximum of 140 characters for a message.\n\n# 6. Loading url on Android WebView\n\nWe have an excellent post on using WebView in another section on our site. It will gives complete understanding on loading external URL on android WebView and different configurations.\n\n[http://stacktips.com/android/android-webview-example/](http://stacktips.com/android/android-webview-example/)\n\n[http://stacktips.com/android/display-html-in-android-](http://stacktips.com/android/display-html-in-android-textview/)\n\n[http://stacktips.com/android/progressbar-while-loading-webview/](http://stacktips.com/android/progressbar-while-loading-webview/)\n\n# 7. Download Complete Example\n\n[![dl_github](/media/articles/420/dl_github.png)](https://github.com/javatechig/javatechig-android-advanced/tree/master/Feed%20Reader)\n\n# 8. Working Demo\n\n{{\u003c youtube YTAMIK_ldhA \u003e}}\n"])</script>
1<script>self.__next_f.push([1,"159:T1c11,"])</script>
1<script>self.__next_f.push([1,"\nAndroid operating system provides developers some of the cool API’s such as Text to speech API. converting Text-To-Speech (TTS) or also known as “speech synthesis”. Text-To-Speech enables your Android device to speak text of different languages.\n\n1.  It is introduced from android 1.6, API Level 4. All of the TTS API’s are available in `android.speech.tts.TextToSpeech` class.\n2.  TTS supports various languages like English, French, German, Italian and Spanish, etc. and some additional languages depending on the region.\n3.  You have to pre-configure the Text-To-Speech engine with which language to speak. The initial language configuration is important to initialize the specific voice dictionary.\n\nFollowing section of this tutorial will teach you the steps required to implement TTS in your Android application.\n\n# TextToSpeech Example\n\nBefore you go ahead implementing the Text to Speech, you must note the following points\n\n1.  A TextToSpeech instance can only be used to synthesize text once it has completed its initialization.\n2.  The constructor of TextToSpeech class takes `TextToSpeech.OnInitListener` parameter. You must implement the TextToSpeech.OnInitListener to be notified, when the TTS is initialized.\n3.  Call `speak()` method on TextToSpeech instance for making Text to Speech to work.\n4.  The speak() method accepts three parameter, a String that accepts text, an integer queue mode and Bundle. The queue mode can be either `QUEUE_FLUSH` or `QUEUE_ADD`.\n\nIn this example, we have an simple activity with an EditText and button, that allows user to enter text for converting into Speech. A screenshot of output is shown below\n\n[![Android TextToSpeech Example](/media/articles/421/Android-TextToSpeech-Example.png)](http://stacktips.com/android/android-example-to-convert-text-to-speech/attachment/android-texttospeech-example)\n\n# Define Activity Layout\n\nAs described above, for the sake of simplicity we will be creating the simple layout with an EditText and a Button.\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:layout_alignParentBottom=\"true\"\n    android:layout_marginBottom=\"10dp\"\n    android:orientation=\"vertical\"\n    android:padding=\"20dp\" \u003e\n\n    \u003cEditText\n        android:id=\"@+id/input_text\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginBottom=\"20dp\"\n        android:ems=\"10\"\n        android:hint=\"Enter your command\"\n        android:minLines=\"2\"\n        android:padding=\"10dp\" \u003e\n        \u003crequestFocus /\u003e\n    \u003c/EditText\u003e\n\n    \u003cButton\n        android:id=\"@+id/speak_now\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"Speak Now\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n# TextToSpeech Manager\n\nIn this example, we will be crating a generic class named `TTSManager`, which will encapsulate all of the logic to implement TextToSpeech in Android. You can reuse the class and use it anywhere you like.\n\n```java\nimport android.content.Context;\nimport android.speech.tts.TextToSpeech;\nimport android.util.Log;\nimport java.util.Locale;\n\n/**\n * Created by Nilanchala\n * http://www.stacktips.com\n */\npublic class TTSManager {\n\n    private TextToSpeech mTts = null;\n    private boolean isLoaded = false;\n\n    public void init(Context context) {\n        try {\n            mTts = new TextToSpeech(context, onInitListener);\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    private TextToSpeech.OnInitListener onInitListener = new TextToSpeech.OnInitListener() {\n        @Override\n        public void onInit(int status) {\n                if (status == TextToSpeech.SUCCESS) {\n                    int result = mTts.setLanguage(Locale.US);\n                    isLoaded = true;\n\n                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {\n                        Log.e(\"error\", \"This Language is not supported\");\n                    }\n                } else {\n                    Log.e(\"error\", \"Initialization Failed!\");\n                }\n        }\n    };\n\n    public void shutDown() {\n        mTts.shutdown();\n    }\n\n    public void addQueue(String text) {\n        if (isLoaded)\n            mTts.speak(text, TextToSpeech.QUEUE_ADD, null);\n        else\n            Log.e(\"error\", \"TTS Not Initialized\");\n    }\n\n    public void initQueue(String text) {\n\n        if (isLoaded)\n            mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null);\n        else\n            Log.e(\"error\", \"TTS Not Initialized\");\n    }\n}\n```\n\n**How it works**\n\n1.  To make the TTS engine to work, the basic configuration is the language that TTS will initialize. You can set the language just by calling set
1Language(locale) method.\n2.  Before we call `setLanguage()`, you need to check if the specified locale is supported. To query whether a specific Locale is supported, you can use `isLanguageAvailable()`, which returns the level of support for the given Locale.\n3.  The TTS engine manages a global queue of all the entries to synthesize, which are also known as “utterances”.\n4.  Each TextToSpeech instance can manage its own queue in order to control which utterance will interrupt the current one and which one is simply queued.\n\n# Making your app to speak\n\n```java\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\n\npublic class MainActivity extends Activity {\n    private Button speakNowButton;\n    private EditText editText;\n    TTSManager ttsManager = null;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        ttsManager = new TTSManager();\n        ttsManager.init(this);\n\n        editText = (EditText) findViewById(R.id.input_text);\n        speakNowButton = (Button) findViewById(R.id.speak_now);\n        speakNowButton.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View arg0) {\n                String text = editText.getText().toString();\n                ttsManager.initQueue(text);\n            }\n        });\n    }\n\n    /**\n     * Releases the resources used by the TextToSpeech engine.\n     */\n    @Override\n    public void onDestroy() {\n        super.onDestroy();\n        ttsManager.shutDown();\n    }\n}\n```\n\n# Queue multiple texts\n\nIf you have multiple text to be queued for TTS engine, you may do it by calling speak() method with `TextToSpeech.QUEUE_ADD` flag.\n\n```java\nString myText1 = \"Hi\";\nString myText2 = \"Hello\";\nttsManager.initQueue(myText1);\n//adding it to queue\nttsManager.addQueue(myText2);\n```\n\n**How it works**\n\n1.  Here in this example, the call to the first speak() method would interrupt whatever was currently being synthesized and the queue is flushed and the new utterance is queued, which places it at the head of the queue.\n2.  On the second call to speak() method, the utterance is queued and will be played after myText1 has completed.\n"])</script>
1<script>self.__next_f.push([1,"15a:T399f,"])</script>
1<script>self.__next_f.push([1,"\n## 1. Introduction\n\nAs mobile devices are limited with memory, we must follow certain best practices to provide best performance and smooth user experience. Among set of best practices, the one holds priority is to take the long running heavy operations off the main thread.\n\nAny long running tasks or heavy operations are usually performed in a different thread, to make sure your main thread does the minimum amount of work. Example of a typical long running tasks could be network operations, reading files form memory, animations, etc.\n\nIn this tutorial, we will create a simple [ListView](/articles/android-listview-tutorial \"Android ListView Example\") in Android that downloads data asynchronously from the internet using a AsyncTask. As you can see in the screenshot below, the ListView contains a image thumbnails on each row, we will download the images asynchronously form server.\n\nIf you’re looking for downloading data from asynchronously from server, we recommend you to read through [Android networking tutorial.](/articles/android-networking-tutorial \"Android Networking Tutorial\")\n\n[![Async ListView Android Example](/media/articles/423/Async-ListView-Android-Example.png)](http://stacktips.com)\n\n## 2. What is Android AsyncTask\n\nAsyncTask enables you to implement MultiThreading without getting your hands dirty into threads. AsyncTask is easy to use, and it allows performing background operation in dedicated thread and passing the results back UI thread. If you are doing something isolated related to UI, for example downloading data for List view, go ahead and use AsyncTask. Some of the basic characteristics of AsyncTask are as follows\n\n1.  An asynchronous task is defined by 3 generic types, called `Params`, `Progress` and `Result`, and 4 steps, called `onPreExecute`, `doInBackground`, `onProgressUpdate` and `onPostExecute`.\n2.  In onPreExecute you can define code, which need to be executed before background processing starts.\n3.  The `doInBackground()` method contains the code which needs to be executed in background, here in doInBackground we can send results to multiple times to event thread by `publishProgress()` method, to notify background processing has been completed we can return results simply.\n4.  The `onProgressUpdate()` method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread\n5.  The `onPostExecute()` method handles results returned by doInBackground method.\n6.  If an async task not using any types, then it can be marked as `Void` type.\n7.  An running async task can be cancelled by calling `cancel()` method.\n\nThe generic types used by AsyncTask are\n\n-   Params, the type of the parameters sent to the task upon execution\n-   Progress, the type of the progress units published during the background computation.\n-   Result, the type of the result of the background computation.\n\n## 3. Downloading image using AsyncTask\n\nWe had learnt the basics of AsyncTask. Let us take a glance at how to use it practically for downloading image asynchronously from web. To achieve this, let us create a new class and name it as `ImageDownloaderTask`.\n\nThe following code snippet expects the url of image as an parameter and initiate download image download request. Once download is over, it displays the bitmap on the image view.\n\n```java\nclass ImageDownloaderTask extends AsyncTask\u003cString, Void, Bitmap\u003e {\n    private final WeakReference\u003cImageView\u003e imageViewReference;\n\n    public ImageDownloaderTask(ImageView imageView) {\n        imageViewReference = new WeakReference\u003cImageView\u003e(imageView);\n    }\n\n    @Override\n    protected Bitmap doInBackground(String... params) {\n        return downloadBitmap(params[0]);\n    }\n\n    @Override\n    protected void onPostExecute(Bitmap bitmap) {\n        if (isCancelled()) {\n            bitmap = null;\n        }\n\n        if (imageViewReference != null) {\n            ImageView imageView = imageViewReference.get();\n            if (imageView != null) {\n                if (bitmap != null) {\n                    imageView.setImageBitmap(bitmap);\n                } else {\n                    Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.placeholder);\n                    imageView.setImageDrawable(placeholder);\n                }\n            }\n        }\n    }\n}\n```\n\n## 4. Downloading image from web\n\nNotice that, in the above step we are calling downloadBitmap() method but haven’t declared it yet. Let us create declare the downloadBitmap method which takes care of loading image and returning the bitmap. Here we are using HttpURLConnection to download the stream from given url. Learn more about HttpURLConnection from our [android networking tutorial](/articles/android-networking-tutorial \"Android Networking Tutorial\").\n\n```java\nprivate Bitmap downloadBitmap(String url) {\n    HttpURLConnection urlConnection = null;\n    try {\n        URL uri = new URL(url);\n        urlConnection = (HttpURLConnection) uri.openConnection();\n        int statusCode = urlConnection.getResponseCode();\n        if (statusCode != HttpStatus.SC_OK) {\n            return null;\n        }\n\n        InputStream inputStream = urlConnection.getInputStream();\n        if (inputStream != null) {\n            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);\n            return bitmap;\n        }\n    } catch (Exception e) {\n        urlConnection.disconnect();\n        Log.w(\"ImageDownloader\", \"Error downloading image from \" + url);\n    } finally {\n        if (urlConnection != null) {\n            urlConnection.disconnect();\n        }\n    }\n    return null;\n}\n```\n\n## 5. Creating custom ListView\n\nNow that we understand the basics of AsyncTask, let us proceed with creating the custom list view in android. The focus of this tutorial is tried to image download. If you not familiar with creating custom list view in android, you can read our [Android ListView tutorial](/articles/android-listview-tutorial \"Android ListView Example\").\n\n### 5.1. Adding ListView to activity layout\n\nFor sake of simplicity our activity layout contains a simple ListView that covers the total available width and height of the device. Create a new file `activity_main.xml` in layout directory.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cListView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:id=\"@+id/custom_list\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\u003e\n\u003c/ListView\u003e\n```\n\n### 5.2. Create list view activity\n\nLet us now create a new activity class MainActivity.java in your project src directory and paste the following code. We will complete this activity in Section 3.5\n\n```java\npublic class MainActivity extends Activity {\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n    }\n}\n```\n\n### 5.3. Create list row layout\n\nNow let us focus on the layout for list view row item. As you can notice form the above screenshot, we will use [RelativeLayout](/articles/android-relativelayout-example \"Android RelativeLayout Example\") for building a simple list row view. Crete a new file list\\_row\\_layout.xml file in layout directory and paste the following code blocks.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:minHeight=\"50dp\"\n    android:padding=\"8dp\"\u003e\n\n    \u003cImageView\n        android:id=\"@+id/thumbImage\"\n        android:layout_width=\"70dp\"\n        android:layout_height=\"70dp\"\n        android:layout_alignParentLeft=\"true\"\n        android:layout_centerVertical=\"true\"\n        android:layout_marginRight=\"10dp\"\n        android:background=\"@drawable/placeholder\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/title\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_toRightOf
1=\"@id/thumbImage\"\n        android:minLines=\"2\"\n        android:paddingTop=\"5dp\"\n        android:textStyle=\"bold\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/reporter\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_below=\"@id/title\"\n        android:layout_marginTop=\"5dp\"\n        android:layout_toRightOf=\"@id/thumbImage\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/date\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignBottom=\"@+id/reporter\"\n        android:layout_alignParentRight=\"true\" /\u003e\n\n\u003c/RelativeLayout\u003e\n```\n\n### 5.4. Creating custom list adapter\n\nAdapter is acts as a bridge between data source and adapter views such as ListView, GridView. Adapter iterates through the data set from beginning till the end and generate Views for each item in the list.\n\nCreate a new class named CustomListAdapter and extend it from BaseAdapter. [Visit here](/articles/android-listview-tutorial \"Android ListView Example\") to learn more about android adapters.\n\n```java\npublic class CustomListAdapter extends BaseAdapter {\n    private ArrayList listData;\n    private LayoutInflater layoutInflater;\n\n    public CustomListAdapter(Context context, ArrayList listData) {\n        this.listData = listData;\n        layoutInflater = LayoutInflater.from(context);\n    }\n\n    @Override\n    public int getCount() {\n        return listData.size();\n    }\n\n    @Override\n    public Object getItem(int position) {\n        return listData.get(position);\n    }\n\n    @Override\n    public long getItemId(int position) {\n        return position;\n    }\n\n    public View getView(int position, View convertView, ViewGroup parent) {\n        ViewHolder holder;\n        if (convertView == null) {\n            convertView = layoutInflater.inflate(R.layout.list_row_layout, null);\n            holder = new ViewHolder();\n            holder.headlineView = (TextView) convertView.findViewById(R.id.title);\n            holder.reporterNameView = (TextView) convertView.findViewById(R.id.reporter);\n            holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);\n            holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);\n            convertView.setTag(holder);\n        } else {\n            holder = (ViewHolder) convertView.getTag();\n        }\n\n        NewsItem newsItem = (NewsItem) listData.get(position);\n        holder.headlineView.setText(newsItem.getHeadline());\n        holder.reporterNameView.setText(\"By, \" + newsItem.getReporterName());\n        holder.reportedDateView.setText(newsItem.getDate());\n        if (holder.imageView != null) {\n            new ImageDownloaderTask(holder.imageView).execute(newsItem.getUrl());\n        }\n        return convertView;\n    }\n\n    static class ViewHolder {\n        TextView headlineView;\n        TextView reporterNameView;\n        TextView reportedDateView;\n        ImageView imageView;\n    }\n}\n```\n\n### 5.5. Using list view adapter\n\nNow that we have the list view and adapter class ready. Let us proceed to complete the MainActivity class. The following code snippet is used to initialize the list view and assign the custom adapter to it.\n\n```java\npublic class MainActivity extends Activity {\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        ArrayList\u003cListItem\u003e listData = getListData();\n\n        final ListView listView = (ListView) findViewById(R.id.custom_list);\n        listView.setAdapter(new CustomListAdapter(this, listData));\n        listView.setOnItemClickListener(new OnItemClickListener() {\n\n            @Override\n            public void onItemClick(AdapterView\u003c?\u003e a, View v, int position, long id) {\n                ListItem newsData = (ListItem) listView.getItemAtPosition(position);\n                Toast.makeText(MainActivity.this, \"Selected :\" + \" \" + newsData, Toast.LENGTH_LONG).show();\n            }\n        });\n    }
1\n\n    private ArrayList\u003cListItem\u003e getListData() {\n        ArrayList\u003cListItem\u003e listMockData = new ArrayList\u003cListItem\u003e();\n        String[] images = getResources().getStringArray(R.array.images_array);\n        String[] headlines = getResources().getStringArray(R.array.headline_array);\n\n        for (int i = 0; i \u003c images.length; i++) {\n            ListItem newsData = new ListItem();\n            newsData.setUrl(images[i]);\n            newsData.setHeadline(headlines[i]);\n            newsData.setReporterName(\"Pankaj Gupta\");\n            newsData.setDate(\"May 26, 2013, 13:35\");\n            listMockData.add(newsData);\n        }\n        return listMockData;\n    }\n}\n```\n\nNotice that, `getListData()` method in the activity is used to create some dummy list data for the list view. To make this example simple, we are using the string arrays defined in the `strings.xml` resource file. But in realtime you might download the data from server or get it from any other sources.\n\nAdd the following string array declarations to string.xml file.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cresources\u003e\n    \u003cstring name=\"app_name\"\u003eAsync ListView\u003c/string\u003e\n    \u003carray name=\"images_array\"\u003e\n        \u003citem\u003ehttp://lh5.ggpht.com/_hepKlJWopDg/TB-_WXikaYI/AAAAAAAAElI/715k4NvBM4w/s144-c/IMG_0075.JPG\u003c/item\u003e\n        \u003citem\u003ehttp://lh4.ggpht.com/_4f1e_yo-zMQ/TCe5h9yN-TI/AAAAAAAAXqs/8X2fIjtKjmw/s144-c/IMG_1786.JPG\u003c/item\u003e\n        \u003citem\u003ehttp://lh3.ggpht.com/_GEnSvSHk4iE/TDSfmyCfn0I/AAAAAAAAF8Y/cqmhEoxbwys/s144-c/_MG_3675.jpg\u003c/item\u003e\n        \u003citem\u003ehttp://lh6.ggpht.com/_ZN5zQnkI67I/TCFFZaJHDnI/AAAAAAAABVk/YoUbDQHJRdo/s144-c/P9250508.JPG\u003c/item\u003e\n        \u003citem\u003ehttp://lh4.ggpht.com/_XjNwVI0kmW8/TCOwNtzGheI/AAAAAAAAC84/SxFJhG7Scgo/s144-c/0014.jpg\u003c/item\u003e\n        \u003citem\u003ehttp://lh6.ggpht.com/_Nsxc889y6hY/TBp7jfx-cgI/AAAAAAAAHAg/Rr7jX44r2Gc/s144-c/IMGP9775a.jpg\u003c/item\u003e\n        \u003citem\u003ehttp://lh6.ggpht.com/_ZN5zQnkI67I/TCFFZaJHDnI/AAAAAAAABVk/YoUbDQHJRdo/s144-c/P9250508.JPG\u003c/item\u003e\n    \u003c/array\u003e\n\n    \u003carray name=\"headline_array\"\u003e\n        \u003citem\u003eDance of Democracy\u003c/item\u003e\n        \u003citem\u003eMajor Naxal attacks in the past\u003c/item\u003e\n        \u003citem\u003eBCCI suspends Gurunath pen
1ding inquiry \u003c/item\u003e\n        \u003citem\u003eLife convict can`t claim freedom after 14 yrs: SC\u003c/item\u003e\n        \u003citem\u003eIndian Army refuses to share info on soldiers mutilated at LoC\u003c/item\u003e\n        \u003citem\u003eFrench soldier stabbed; link to Woolwich attack being probed\u003c/item\u003e\n        \u003citem\u003eLife convict can`t claim freedom after 14 yrs: SC\u003c/item\u003e\n    \u003c/array\u003e\n\u003c/resources\u003e\n```\n\n## 5. Download Complete Example\n\n[Download source](https://github.com/javatechig/Async-ListView-Image-Loader)\n"])</script>
1<script>self.__next_f.push([1,"15b:T1511,"])</script>
1<script>self.__next_f.push([1,"\nArrayList are also called as dynamic arrays that can grow as needed. In Java ArrayList class extends AbstractList and implements List interface. In Java ArrayList’s are created with an initial size. The size of the collection is changes dynamically as the items are exceeded the size or deleted. This example will explain sorting of ArrayList using `Comparator`, `Comparable` and `Collectiolns.sort()` method.\n\n\\[box style=”1″\\]Note: Typically standard Array in java is fixed sized in nature. Once created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.\\[/box\\]\n\nAt times, you may need to sort the ArrayList to make it alphabetically order. In this below example, it shows the use of Collections.sort and comparator to sort an ArrayList.\n\n# 1. Sorting using Collections.sort method:\n\n```java\npublic class SortArrayList {\n\n    public static void main(String[] args) {\n        ArrayList unsortList = new ArrayList();\n        unsortList.add(\"1011\");\n        unsortList.add(\"5460\");\n        unsortList.add(\"1000\");\n        unsortList.add(\"Abdul\");\n        unsortList.add(\"1012\");\n        unsortList.add(\"Adam\");\n\n        System.out.println(\"********** Value before sorting **************\");\n        for (String str : unsortList) {\n            System.out.println(str);\n        }\n\n        Collections.sort(unsortList);\n\n        System.out.println(\"********** Value after sorting **************\");\n        for (String str : unsortList) {\n            System.out.println(str);\n        }\n\n    }\n}\n```\n\nHere in this above example the sorting happens according to ASCII.\n\n##### Output:\n\n[![sorting-array-list-using-collections.sort](/media/articles/424/sorting-array-list-using-collections.sort_.png)](http://stacktips.com)\n\n# 2. Sorting objects in an ArrayList using Comparable interface\n\nIn my example I want to sort the employees list as per their salary in descending order. My Employee class implements Comparable interface and overridden compareTo method. In Compare to method add your logic, weather to sort ascending or descending order.\n\n```java\npublic class Employee implements Comparable {\n    private String name;\n    private String id;\n    private double salary;\n\n    public Employee(String id, String name, double salary) {\n        this.id = id;\n        this.name = name;\n        this.salary = salary;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public String getId() {\n        return id;\n    }\n\n    public void setId(String id) {\n        this.id = id;\n    }\n\n    public double getSalary() {\n        return salary;\n    }\n\n    public void setSalary(double salary) {\n        this.salary = salary;\n    }\n\n    @Override\n    public int compareTo(Employee employee) {\n        double compareSalary = ((Employee) employee).getSalary();\n\n        // ascending order\n        // return (int) (this.salary - compareSalary);\n\n        // descending order\n        return (int) (compareSalary - this.salary);\n    }\n\n    @Override\n    public String toString() {\n        return \"[ id=\" + id + \", name=\" + name + \", salary=\" + salary + \"]\";\n    }\n\n}\n```\n\n# 3. Sorting Objects in an ArrayList using Comparator\n\nCheck out the below code snippet, I am sorting Employees list using Anonymous Comparator\n\n```java\n//Sorting using Anonymous inner class type\n        Collections.sort(emplyoees, new Comparator() {\n            @Override\n            public int compare(Employee e1, Employee e2) {\n                String id1 = ((Employee) e1).getId();\n                String id2 = ((Employee) e2).getId();\n\n                // ascending order\n                 return id1.compareTo(id2);\n\n                // descending order\n                //return id2.compareTo(id1);\n            }\n        });\n```\n\n##### Complete Code\n\n```java\npublic class SortArrayListObjects {\n\n    public static void main(String[] args) {\n\n        ArrayList employees = new ArrayList();\n        employees.add(new Employee(\"1001\", \"Adam\", 5000));\n        employees.add(new Employee(\"1006\", \"Rajan\", 8400));\n        employees.add(new Employee(\"1040\", \"Keay\", 2500));\n        employees.add(new Employee(\"1056\", \"Ashok\", 12000));\n\n        System.out.println(\"**** Value before sorting ***\");\n        for(Employee employee: employees){\n            System.out.println(employee);\n        }\n\n        Collections.sort(employees);\n\n        System.out.println(\"**** After sorting salary desce
1nding ***\");\n        for(Employee employee: employees){\n            System.out.println(employee);\n        }\n\n        //Sorting using Anonymous inner class type\n        Collections.sort(employees, new Comparator() {\n            @Override\n            public int compare(Employee e1, Employee e2) {\n                String id1 = ((Employee) e1).getId();\n                String id2 = ((Employee) e2).getId();\n\n                // ascending order\n                 return id1.compareTo(id2);\n\n                // descending order\n                //return id2.compareTo(id1);\n            }\n        });\n\n        System.out.println(\"**** After sorting id ascending ***\");\n        for(Employee employee: employees){\n            System.out.println(employee);\n        }\n\n    }\n}\n```\n\n##### Output[![sorting-array-list-using-Comparator](/media/articles/424/sorting-array-list-using-Comparator.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"15c:Td25,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial we will see How To Loop ArrayList In Java in different ways. Below example will loop through ArrayList and print its content.\n\n1.  Using regular for loop\n2.  Using advance for loop\n3.  Using While Loop\n4.  Using Iterator\n\nIterator is an interface in the collection framework. ArrayList is a collection class and implements the List Inteface. All the elements of the ArrayList can be traversed by the Iterator. Iterator has methods hasNext() and next()\n\n```java\npackage com.test;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class ArrayListDemo {\n\n    public static void main(String[] args) {\n\n        // adding items to list\n        // in real time you might get this data from a db or from other sources\n        // We are hard-coding the values here to simplify this example\n        List list = new ArrayList();\n        list.add(new NewsObject(1001,\n                \"Soldier beheaded in suspected terror attack in London\",\n                \"en_in\"));\n        list.add(new NewsObject(1002,\n                \"Passive smoking can make kids aggressive\", \"en_in\"));\n        list.add(new NewsObject(\n                1003,\n                \"Police prepare to question BCCI chief's son-in-law for betting links\",\n                \"en_in\"));\n        list.add(new NewsObject(1004,\n                \"Shun body tattoos if you wish to join armed forces\", \"en_in\"));\n        list.add(new NewsObject(1005,\n                \"Man linked to Boston bombings killed by FBI agent\", \"en_in\"));\n\n        System.out.println(\"#1. Looping using regular for loop\");\n        for (int i = 0; i \u003c list.size(); i++) {\n            NewsObject news = (NewsObject) list.get(i);\n            System.out.println(news);\n        }\n\n        System.out.println(\"#2.  Looping using advance for loop\");\n        for (NewsObject news : list) {\n            System.out.println(news);\n        }\n\n        System.out.println(\"#3. Looping using while loop\");\n        int j = 0; // initilisation\n        while (list.size() \u003e j) { // condition checking\n            NewsObject news = (NewsObject) list.get(j);\n            System.out.println(news);\n            j++; // iteration\n        }\n\n        System.out.println(\"#4. Looping using iterator\");\n        Iterator iterator = (Iterator) list.iterator();\n        while (iterator.hasNext()) {\n            NewsObject news = (NewsObject) iterator.next();\n            System.out.println(news);\n        }\n    }\n\n}\n```\n\nHere in my above example, I am storing NewsObject object in my ArrayList.\n\n```java\npublic class NewsObject {\n    int id;\n    String headline;\n    String edition;\n\n    NewsObject(int id, String headline, String edition) {\n        this.id = id;\n        this.headline = headline;\n        this.edition = edition;\n\n    }\n\n    public int getId() {\n        return id;\n    }\n\n    public void setId(int id) {\n        this.id = id;\n    }\n\n    public String getHeadline() {\n        return headline;\n    }\n\n    public void setHeadline(String headline) {\n        this.headline = headline;\n    }\n\n    public String getEdition() {\n        return edition;\n    }\n\n    public void setEdition(String edition) {\n        this.edition = edition;\n    }\n\n    @Override\n    public String toString() {\n        return \"NewsObject : \" + \"Id = \" + id + \", Headline=\" + headline\n                + \", Editon=\" + edition;\n    }\n\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"15d:T1a4b,"])</script>
1<script>self.__next_f.push([1,"\nA frame animation created by moving an object little-by-little over several consecutive frames. In Android, we can create Frame Animation by swapping frames repeatedly, so that it appears continuous to the human eye and we feel that it is animated.\n\nFrame is referred to an image. So to implement frame by frame animation in android, we needs to have set of images, which describes a motion. Now let’s move on and see how to implement frame by frame animation in Android\n\nThe following steps will guide you through step by step approach to create frame animation in Android.\n\n## 1. Identifying the Image Frames\n\nFirst step towards creating frame animation is to prepare a series of images with the individual frames of your animation. Add the images to your project’s drawable folder. In this example, I have used the following sequence of images.\n\n![](/media/articles/426/frame1.png)![](/media/articles/426/frame2.png)![](/media/articles/426/frame3.png)![](/media/articles/426/frame4.png)![](/media/articles/426/frame5.png)![](/media/articles/426/frame6.png)![](/media/articles/426/frame7.png)![](/media/articles/426/frame8.png)![](/media/articles/426/frame9.png)![](/media/articles/426/frame10.png)\n\n## 2. Define Animation Sequence\n\nDeclare a XML file that defines the animation sequence that holds the list of drawables. Create a new file named `frame_animation_list.xml` and paste it to your project resource `res/anim` or `res/drawable` folder.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003canimation-list xmlns:android=\"http://schemas.android.com/apk/res/android\" android:oneshot=\"false\"\u003e\n        \u003citem android:drawable=\"@drawable/frame1\" android:duration=\"210\" /\u003e\n    \u003citem android:drawable=\"@drawable/frame2\" android:duration=\"210\" /\u003e\n    \u003citem android:drawable=\"@drawable/frame3\" android:duration=\"210\" /\u003e\n    \u003citem android:drawable=\"@drawable/frame4\" android:duration=\"210\" /\u003e\n    \u003citem android:drawable=\"@drawable/frame5\" android:duration=\"210\" /\u003e\n    \u003citem android:drawable=\"@drawable/frame6\" android:duration=\"210\" /\u003e\n    \u003citem android:drawable=\"@drawable/frame7\" android:duration=\"210\" /\u003e\n    \u003citem android:drawable=\"@drawable/frame8\" android:duration=\"210\" /\u003e\n    \u003citem android:drawable=\"@drawable/frame9\" android:duration=\"210\" /\u003e\n    \u003citem android:drawable=\"@drawable/frame10\" android:duration=\"210\" /\u003e\n\n\u003c/animation-list\u003e\n```\n\n-   Notice that in the above layout declaration, we are using `AnimationDrawable` class. This takes the list of `Drawable` resources and render them at specified intervals.\n-   Note that the AnimationDrawable class, loads all the images into memory before it starts animation.\n-   You must be careful about using this for images of larger size. Depending on the size of the images, you have to restrict the number of frames for making animation smoother.\n\n## 3. Declare Activity Layout\n\nNow declare an image view to your activity layout where the animation will be shown. In my example, I have declared an image view and two buttons Start and Stop to control the animation. Add the following snippet to your `activity_main.xml` file.\n\n```xml\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\u003e\n\n    \u003cImageView\n        android:id=\"@+id/imageView\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerInParent=\"true\"\n        android:adjustViewBounds=\"true\" /\u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignParentBottom=\"true\"\n        android:layout_marginBottom=\"20dp\"\n        android:orientation=\"horizontal\"\u003e\n\n        \u003cButton\n            android:id=\"@+id/start\"\n            android:layout_width=\"0dp\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"0.5\"\n            android:text=\"Start\" /\u003e\n\n        \u003cButton\n            android:id=\"@+id/stop\"\n            android:layout_width=\"0dp\"\n            android:layout_height=\"wrap_content\"\n            android:layout_weight=\"0.5\"\n            android:text=\"Stop\" /\u003e\n    \u003c/LinearLayout\u003e\n\u003c/RelativeLayout\u003e\n```\n\n## 4. Control the Animation Behaviour\n\nNow that we are ready with the animation sequence, we need to add this Drawable as a background resource for our ImageView. Use the following code snippet to set the AnimationDrawable as the background of the ImageView.\n\n```java\n// Setting animation_list.xml as the background of the image view\nview.setBackgroun
1dResource(R.drawable.frame_animation_list);\n```\n\nOnce this is set, you can access this AnimationDrawable object by doing a get on the view object like this:\n\n```java\n// Type casting the Animation drawable\nframeAnimation = (AnimationDrawable) view.getBackground();\n```\n\n-   Now we can control the behaviour of animation by using `start()` and `stop()` methods to start and stop the animation.\n-   You may use `setOneShot()` method runs the animation once and then stops.\n-   The `addFrame(drawable, duration)` method can be used to add a new frame by passing a Drawable object and sets its display duration.\n\n## 5. Completing Example Code\n\nNow that we understand the concepts, let us complete the example. Here is the complete code that goes inside `MainActivity.java`.\n\n```java\nimport android.graphics.drawable.AnimationDrawable;\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.ImageView;\n\npublic class MainActivity extends ActionBarActivity implements OnClickListener {\n\n    private ImageView view;\n    private AnimationDrawable frameAnimation;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        // Type casting the Image View\n        view = (ImageView) findViewById(R.id.imageView);\n\n        // Setting animation_list.xml as the background of the image view\n        view.setBackgroundResource(R.drawable.frame_animation_list);\n\n        // Type casting the Animation drawable\n        frameAnimation = (AnimationDrawable) view.getBackground();\n\n        //set true if you want to animate only once\n        frameAnimation.setOneShot(true);\n\n        findViewById(R.id.start).setOnClickListener(this);\n        findViewById(R.id.stop).setOnClickListener(this);\n    }\n\n    @Override\n    public void onClick(View v) {\n        int id = v.getId();\n        if(id == R.id.start){\n            frameAnimation.start();\n        }else if(id==R.id.stop){\n            frameAnimation.stop();\n        }\n    }\n}\n```\n"])</script>
1<script>self.__next_f.push([1,"15e:Tb90,"])</script>
1<script>self.__next_f.push([1,"\n[![Android Studio IDE](/media/articles/427/Android-Studio-IDE.png)](http://developer.android.com/sdk/index.html#Other)\n\nAndroid Studio is an IDE based on IntelliJ IDEA used for android application development. It is released on 15th may 2013. This tool has more options for Android Development, making the process faster and more productive. A “live layout” was shown that renders your app as you’re editing in real-time. In this tutorial you can learn steps for Installing Android Studio.  \nKnow more about android studio features from [Android Studio Features](http://stacktips.com/2013/05/19/android-studio-features/ \"Android Studio Features\").\n\n\\[box style=”2″\\] Android Studio is currently available as an early access preview. Several features are either incomplete or not yet implemented and you may encounter bugs. If you are not comfortable using an unfinished product, you may want to instead download (or continue to use) the ADT Bundle (Eclipse with the ADT Plug-in). \\[/box\\]\n\n# Installing Android Studio\n\n[![android-studio-viewing-layout_builder](/media/articles/427/android-studio-viewing-layout_builder.png)](http://stacktips.com)\n\n# Some Common Problems\n\n### 1. ERROR: cannot start Android Studio\n\n```text\nERROR: cannot start Android Studio. No JDK found. Please validate either ANDROID_STUDIO_JDK, or JDK_HOME or JAVA_HOME points to valid JDK installation. ECHO is off. Press any key to continue\n```\n\nIt is a known issue with android studio**.** On some Windows systems, the launcher script does not find where Java is installed. If you encounter this problem, you need to set an environment variable indicating the correct location. Select **Start menu \u003e Computer \u003e System Properties \u003e Advanced System Properties**. Then open **Advanced tab \u003e Environment Variables**, add new system variable `JAVA_HOME` that points to your JDK folder, for example `C:\\Program Files\\Java\\jdk1.7.0_21`. [![setting up java path](/media/articles/427/setting-up-java-path.png)](http://stacktips.com)\n\n### 2.Android SDK is out of date or is missing templates\n\n```text\nYour Android SDK is out of date or is missing templates. Please ensure you are using SDK version 22 or later.\n```\n\nThis may happen because you already have your SDK installation up for Android Developers Bundle with eclipse. First open your SDK manager in the ADT Bundle and update you Android SDK Tools from 21.1 to 22 and then open your Android Studio. For windows user the tools and other SDK packages are saved with the Android Studio application directory. Windows:\n\n\\\\Users\\\\AppData\\\\Local\\\\Android\\\\android-studio\\\\sdk\\\\ Mac: /Applications/Android\\\\ Studio.app/sdk/ Make sure your android-sdk-path is correct and the sdk tool version is 22 or later. Once android studio started, open the **Configure \u003e Project Defaults \u003e Project Structure**, set your project sdk is Android SDK. Then select SDK tab and select build target (eg: Android 4.2.2). Now you should be good to start.\n"])</script>
1<script>self.__next_f.push([1,"15f:Tc30,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains Android Studio Features and Installation steps. Android Studio is an IDE based on IntelliJ IDEA used for android application development. It is released on 15th may 2013. This tool has more options for Android Development, making the process faster and more productive. A “live layout” was shown that renders your app as you’re editing in real-time.\n\nPrior to Android Studio, developers were relying only on the open source eclipse as IDE with ADT plugin for android development. Due to this android was always falling back compared Apples xCode IDE for iOS based development. After android studio release Google can equally bet with iOS platform in terms of development assets. Now let’s see more of the IDE capabilities.\n\n## Android Studio Features\n\nAndroid studio is based on IntelliJ IDEA, which does all the functionality that Eclipse with ADT plug-in do, with lot more additional features. The initial version of android studio offers\n\n1.  Gradle-based build support.\n2.  Android-specific refactoring and quick fixes\n3.  Lint tools to catch performance, usability, version compatibility and other problems\n4.  ProGuard and app-signing capabilities\n5.  Template-based wizards to create common Android designs and components.\n6.  **A rich layout editor:** it allows you to drag-and-drop UI components, preview layouts on multiple screen configurations. Preview appears instantly as you change in the layout editor. You can choose a language, and can see the preview of layout with that locale.\n7.  **Rich Color Preview editor:** While adding colors as a resource, and we can see the color preview at the left hand side of the editor.\n8.  **Deep Code Analysis:** If you point to a line and it gives detailed explanation about an exception based on the annotation added. And you can also know which constants are allowed for which API. It also has the powerful code completion. You can also inspect code in whole project, InteliJ lists all Lint errors during code inspection.\n\n\\[box style=”2″\\]\n\n**Note:** Android Studio is currently available as an early access preview. Several features are either incomplete or not yet implemented and you may encounter bugs. If you are not comfortable using an unfinished product, you may want to instead download (or continue to use) the ADT Bundle (Eclipse with the ADT Plug-in)\n\n\\[/box\\]\n\n[![android-studio-viewing-layout_builder](/media/articles/428/android-studio-viewing-layout_builder.png)](http://stacktips.com)\n\n[![android-studio-viewing-layout](/media/articles/428/android-studio-viewing-layout.png)](http://stacktips.com)\n\n[![android-studio-color-editor](/media/articles/428/android-studio-color-editor.png)](http://stacktips.com)\n\nWith this new features, hope it will help developers to get their development faster.\n\nYou can find a Youtube tutorial from Devbytes which will help you getting started with IDE\n\n{{\u003c youtube e0fXuyL0xVU \u003e}}\n\n## Installing Android Studio\n\nFind my post explaining steps to install android studio on windows.\n\n[http://stacktips.com/articels/installing-android-studio/](/articl/installing-android-studio/)\n"])</script>
1<script>self.__next_f.push([1,"160:T149d,"])</script>
1<script>self.__next_f.push([1,"\nIn this tutorial we will explain how to work with Android Toast with example. The example below demonstrates the usages of simple and customized toast in Android.\n\n1.  Toast is a solution for android developer when required to notify user about an operation without expecting any user input.\n2.  This provides a small popup that displays for a small period and fades out automatically after timeout. Sometimes developers use this for debugging.\n3.  For example, some of the app shows “Press back once to Exit” message when pressed back button in home page. Another real-time example is Gmail app, It shows a Toast, when a mail message is saved to draft.\n\n### How to Create a Toast\n\nWe can instantiate a `android.widget.Toast` object using static `makeText()` method. This method takes three parameters: the application `Context`, the text `message`, and the `duration` for the toast. You can display the toast notification by calling show() method.\n\nCheckout below code snippet to show an simple toast in Android\n\n```java\n//display in short period of time\nToast.makeText(getApplicationContext(), \"Your toast message.\",\n                      Toast.LENGTH_SHORT).show();\n//display in long period of time\nToast.makeText(getApplicationContext(), \"Your toast message\",\n                      Toast.LENGTH_LONG).show();\n```\n\nToast notification in android always appears near the bottom of the screen, centered horizontally as shown in the image. However, it allows us to change its position with the `setGravity(int, int, int)` method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.\n\nFor example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:\n\n```java\nToast toast = Toast.makeText(getApplicationContext(), \"Your toast message.\", Toast.LENGTH_SHORT);\ntoast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);\ntoast.show();\n```\n\n### Creating Custom Toast in Android\n\nSometimes a simple Toast may not be satisfactory, and then we can go for customizing the Toast. To create a custom layout, define a View layout, in XML and pass the root View object to the setView(View) method.\n\nIn my example, I have created an XML layout named as `custom_toast.xml`\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:id=\"@+id/toast_layout_root\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:layout_marginLeft=\"10dp\"\n    android:layout_marginRight=\"10dp\"\n    android:orientation=\"horizontal\"\n    android:paddingLeft=\"10dp\"\n    android:paddingRight=\"10dp\" \u003e\n\n    \u003cLinearLayout\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"\n        android:background=\"#00AAE9\"\n        android:orientation=\"horizontal\"\n        android:paddingBottom=\"5dp\"\n        android:paddingTop=\"5dp\" \u003e\n\n    \u003cImageView\n        android:id=\"@+id/toastImage\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"fill_parent\"\n        android:layout_marginRight=\"10dp\"\n        android:src=\"@drawable/ic_warning\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/toastText\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"fill_parent\"\n        android:gravity=\"center_vertical\"\n        android:textColor=\"#FFFFFF\"\n        android:textSize=\"7pt\"\n        android:textStyle=\"italic\" /\u003e\n    \u003c/LinearLayout\u003e\n\u003c/LinearLayout\u003e\n```\n\nBelow is the code changes for the activity class\n\n```java\npublic class MainActivity extends Activity {\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        Button toastButton = (Button) this.findViewById(R.id.toastButton);\n        toastButton.setOnClickListener(new OnClickListener() {\n            public void onClick(View v) {\n                //create the toast object, set display duration,\n                Toast.makeText(getApplicationContext(), \"This is a plain toast.\", Toast.LENGTH_SHORT).show();\n            }\n        });\n\n        Button customToastButton = (Button) this.findViewById(R.id.customToastButton);\n        customToastButton.setOnClickListener(new OnClickListener() {\n            public void onClick(View v) {\n\n                //get the LayoutInflater and inflate the custom_toast layout\n                LayoutInflater inflater = getLayoutInflater();\n                View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup)\n                findViewById(R.id.toast_layout_root));\n\n                //get the TextView from the custom_toast layout\n                TextView text = (TextView) layout.findViewById(R.id.toastText);\n                text.setText(\"This is my custom toast\");\n\n                //create the toast object, set display duration,\n                //set the view as layout that's inflated above and then call show()\n                Toast t = new Toast(getApplicationContext());\n                t.setDuration(Toast.LENGTH_LONG);\n                t.setView(layout);\n                t.show();\n            }\n        });\n    }\n}\n```\n\nBelow is the output of the above code\n\n[![](/media/articles/429/thumb-toast-custom.png)](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"161:T1976,"])</script>
1<script>self.__next_f.push([1,"\n# 1. Introduction to Android WebView\n\nIn the course of this tutorial, we will teach you how to use Android WebView and answer to some of the most common questions on android WebView.\n\n1.  Android WebView is an embedded browser that can render static HTML data or even remote URL. A WebView is an android UI component that displays webpages.\n2.  WebView encompasses the functionality of a browser that can be integrated to Android application.\n3.  It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, and perform text searches and more.\n4.  Most of the android applications like WordPress, Flipboard, fiddly; Google Reader, etc. do integrate WebView, in order to display certain piece of online contents.\n\nAndroid WebView use WebKit rendering engine to display web pages. If you see the android underlying platform architecture, the WebKit core resides in library layer, and the source is developed in C/C++. From Android application framework layer, the WebView can connect to WebKit using JNI (Java native Interface).\n\n[![Android-system-architecture](/media/articles/430/Android-system-architecture.jpg)](http://elinux.org/images/c/c2/Android-system-architecture.jpg)\n\nAndroid-system-architecture\n\n
1If you are interested in taking a look into the Android platform source code, you may visit the following links  \n[Webkit JNI code](https://android.googlesource.com/platform/external/webkit/+/f10585d69aaccf4c1b021df143ee0f08e338cf31/WebKit/android/jni)  \n[BrowserWebView.Java](http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/4.1.1_r1/com/android/browser/BrowserWebView.java?av=f)\n\n# 2. Open Link on Android Device Browser\n\nAt times, you may require to invoke the device browser, when an external link is clicked from app. For example, in most of the mobile advertising platform, when user click on a banner, it redirect user to the ad publisher website to show more info on specific ad. For such similar requirement, you need to open device browser with a URL.\n\nFollowing code show how to invoke device browser using Android Intent method.\n\n```java\nUri uri = Uri.parse(\"http://stacktips.com\");\nIntent intent = new Intent(Intent.ACTION_VIEW, uri);\nstartActivity(intent);\n```\n\nThe ACTION\\_VIEW intent action is used to invoke the application based on the specified data. Here in this example, we are using URL as bundle data so it will invoke the specified url in the application that can take such action, eg. browser. If you provide the data type as phone number, it will automatically open phone dialer.\n\n# 3. Android WebView Example\n\nFollowing section of the tutorial, will drive you with step by step approach to create a simple WebView with different configuration params and load stacktips.com home page.\n\n# 4. Declare WebView Layout\n\nLike any other UI controls in android, you can include the WebView in your xml layout. Below is my xml layout\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:id=\"@+id/urlContainer\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:orientation=\"horizontal\" \u003e\n\n    \u003cWebView\n        android:id=\"@+id/webView\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"fill_parent\"/\u003e\n\u003c/LinearLayout\u003e\n```\n\n# 5. Load Static Html Data on WebView\n\nFollowing activity class snippet will show you how to initialize WebView instance and load static Html string onto it. Just call loadData() It takes html string data, mime-type and encoding param as three parameters.\n\n```java\n//Instantiating WebView instance\nWebView webView = (WebView) findViewById(R.id.webView);\nString customHtml = \"\u003chtml\u003e\u003cbody\u003e\u003ch1\u003eHello, WebView\u003c/h1\u003e\" +\n           \"\u003ch1\u003eHeading 1\u003c/h1\u003e\u003ch2\u003eHeading 2\u003c/h2\u003e\u003ch3\u003eHeading 3\u003c/h3\u003e\" +\n           \"\u003cp\u003eThis is a sample paragraph.\u003c/p\u003e\" +\n           \"\u003c/body\u003e\u003c/html\u003e\";\nwebView.loadData(customHtml, \"text/html\", \"UTF-8\");\n```\n\nOutput of the above code is  \n[![Load Static HTML Data on WebView](/media/articles/430/Load-Static-HTML-Data-on-WebView-300x294.png)](http://stacktips.com)\n\n# 6. Load Remote URL on WebView\n\n1.  The default behavior of Android is to open device browser, when links are clicked. But as our WebView should work like a embedded browser, we must override to always open the links in the WebView instead redirecting it to the default browser.\n2.  We can do this using android `WebViewClient`. WebViewClient helps to monitor events in a WebView. We have to override the `shouldOverrideUrlLoading()` method. This method allows performing your own action when a particular URL is selected. Once we are ready with the WebViewClient, we can set the WebViewClient of your WebView using the `setWebViewClient()` method.\n3.  The WebViewClient class has some other useful methods such as `onPageStarted()`, `onPageFinished()` and `onReceivedError()` that helps you to show loading progress of WebView content, or handle error.\n\nCheckout my Android tutorial that explains [How to show loading progress in Android WebView](http://stacktips.com/android/progressbar-while-loading-webview \"ProgressBar while Loading WebView in Android\").\n\nNow let us go back to our example, and take a look into how our activity class looks like.\n\n```java\npublic class WebViewActivity extends Activity {\n    private WebView webView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_webview);\n\n        webView = (WebView) findViewById(R.id.webView);\n        webView.setWebViewClient(new MyWebViewClient());\n\n        String url = \"http://stacktips.com\";\n                webView.getSettings().setJavaScriptEnabled(true);\n        webView.loadUrl(url);\n    }\n\n    private class MyWebViewClient extends WebViewClient {\n        @Override\n        public boolean shouldOverrideUrlLoading(WebView view, String url) {\n            view.loadUrl(url);\n            return true;\n        }\n    }\n}\n```\n\nOutput of the above code is here\n\n[![Load Remote URL on WebView](/media/articles/430/Load-Remote-URL-on-WebView-300x416.png)](http://stacktips.com)\n\n# 7. Display HTML Text in TextView\n\nAndroid TextView is also capable of rendering the HTML text. Checkout my post [How to Display HTML in Android TextView](http://stacktips.com/android/display-html-in-android-textview \"How to Display HTML in Android TextView\").\n"])</script>
1<script>self.__next_f.push([1,"162:T3cfd,"])</script>
1<script>self.__next_f.push([1,"\n## Introduction\n\nThis post will walk you through building simple and customized `ListView` in Android using different Android adapters.\n\nScrollview is ideal for screens where scrolling is required, but it is not efficient when scroll view is used to render a larger data set. Instead you can use specialized adapter views like [ListView](http://stacktips.com/articles/android-listview-tutorial \"Android ListView Example\"), [GridView](http://stacktips.com/articles/android-gridview-example-building-image-gallery-in-android \"Android Gridview Example- Building Image Gallery in android\") and [Recycler View](http://stacktips.com/articles/android-recyclerview-example \"Android RecyclerView Example\") (Introduced in Android Lollipop) for long lists.\n\n1.  ListView is an Android ViewGroup, used extensively to display the collection of data in vertical scrollable rows.\n2.  The list items are automatically inserted to the list using an Adapter and Adapter pulls data from data source source such as an array, cursor, etc.\n\n## Android Adapter\n\nAdapter is acts as a bridge between data source and adapter views such as ListView, GridView. Adapter iterates through the data set from beginning till the end and generate Views for each item in the list.\n\nAndroid SDK provides three different Adapter implementation, that includes `ArrayAdapter`, `CursorAdapter` and `SimpleAdapter`. An ArrayAdapter expects an Array or an List as input, while CursorAdapter accepts the instance of Cursor and SimpleAdapter maps the static data defined in the resources. The type of adapter that suits your app need is purely based on the input data type.\n\nThe BaseAdapter is the generic implementation for all of the three adapter types and can be used for ListView, GridView or for Spinners.\n\nYou may directly use ArrayAdapter by passing array as input or create your own customized class by extending BaseAdapter.\n\n[](http://stacktips.com)\n\nThe image above, provides idea of customizable list views can be done using adapters.\n\n## ListView Using ArrayAdapter\n\nThe simplest way for building list view is by using ArrayAdapter. Following are some of the steps used to implement simple ListView using array adapter.\n\n1.  First step towards building list view is to identify the input data, which you want to display in list. In this example, we will be using a static array of strings.\n2.  Secondly, let us declare list view in activity layout. In our example, the activity layout contains a list view inside linear layout. Provide `android:id=\"@+id/months_list\"` as ListView id.\n3.  Now finally, let us instantiate the  the ArrayAdapter and set to ListView by calling `setAdapter()` method.\n\nFollowing code snippet depicts the list view declaration inside activity layout\n\n```xml\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\u003e\n\n    \u003cListView\n        android:id=\"@+id/months_list\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\" \u003e\n    \u003c/ListView\u003e\n\u003c/LinearLayout\u003e\n```\n\nNow instantiate the ListView and Array adapter. Following code snippet depicts the activity code.\n\n**ListActivity.java**\n\n```java\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\n\npublic class ListActivity extends Activity {\n    private String[] monthsArray = { \"JAN\", \"FEB\", \"MAR\", \"APR\", \"MAY\", \"JUNE\", \"JULY\",\n \"AUG\", \"SEPT\", \"OCT\", \"NOV\", \"DEC\" };\n\n    private ListView monthsListView;\n    private ArrayAdapter arrayAdapter;\n\n    /** Called when the activity is first created. */\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_list);\n\n        monthsListView = (ListView) findViewById(R.id.months_list);\n\n        // this-The current activity context.\n        // Second param is the resource Id for list layout row item\n        // Third param is input array\n        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, monthsArray);\n        monthsListView.setAdapter(arrayAdapter);\n    }\n}\n```\n\n## ListView Using Custom Adapter\n\nSo far we have created a simple list view using ArrayAdapter. Now it time to create something fancy custom a list by extending BaseAdapter. Following steps are used to implement customized ListView:\n\n1.  First step towards building custom list is to identify the data model for each row. In our example we will display list of `NewsItem` objects.\n2.  Secondly, let us declare list view in activity layout.\n3.  Now declare the layout for each row item.\n4.  Create your custom adapter class by extending `BaseAdapter` class.\n5.  Finally, let us instantiate your custom adapter and set to ListView by calling setAdapter() method.\n\nThe NewsItem object will represent each row in list. Declare NewsItem.java class and add the following code snippets.\n\n```java\npublic class NewsItem {\n    private String headline;\n    private String reporterName;\n    private String date;\n    public String getHeadline() {\n        return headline;\n    }\n\n    public void setHeadline(String headline) {\n        this.headline = headline;\n    }\n\n    public String getReporterName() {\n        return reporterName;\n    }\n\n    public void setReporterName(String reporterName) {\n        this.reporterName = reporterName;\n    }\n\n    public String getDate() {\n        return date;\n    }\n\n    public void setDate(String date) {\n        this.date = date;\n    }\n}\n```\n\n### Define List Row Layout\n\nLet us create a new custom layout for list view row item containing headline, name and date TextView.\n\n**list\\_row\\_layout.xml**\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cRelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:orientation=\"horizontal\"\n    android:padding=\"5dip\" \u003e\n\n    \u003cTextView\n        android:id=\"@+id/title\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:textStyle=\"bold\"\n        android:typeface=\"sans\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/reporter\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_below=\"@id/title\"\n        android:layout_marginTop=\"5dip\"\n        android:textColor=\"#343434\"\n        android:textSize=\"12sp\" /\u003e\n\n    \u003cTextView\n        android:id=\"@+id/date\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_alignBaseline=\"@+id/reporter\"\n        android:layout_alignBottom=\"@+id/reporter\"\n        android:layout_alignParentRight=\"true\"\n        android:textColor=\"#343434\"\n        android:textSize=\"12sp\" /\u003e\n\u003c/RelativeLayout\u003e\n```\n\n### Custom List Adapter\n\nLet us create a new class 
1named `CustomListAdapter.java`, and extend it from BaseAdapter. You must override  the following methods form BaseAdpter class.\n\n| getCount() | This method returns the total number of row counts for the listview. Typically this contains the size of the list you passing as input. |\n| --- | --- |\n| getItem() | Returns object representing data for each row. |\n| getItemId() | This returns the unique integer id that represents each row item. Let us return the integer position value. |\n| getView() | The getView() method returns a view instance that represents a single row in ListView item. Here you can inflate your own layout and update values on list row. |\n\nCheckout the  following code snippets for CustomListAdapter class.\n\n```java\npublic class CustomListAdapter extends BaseAdapter {\n    private ArrayList\u003cNewsItem\u003e listData;\n    private LayoutInflater layoutInflater;\n\n    public CustomListAdapter(Context aContext, ArrayList\u003cNewsItem\u003e listData) {\n        this.listData = listData;\n        layoutInflater = LayoutInflater.from(aContext);\n    }\n\n    @Override\n    public int getCount() {\n        return listData.size();\n    }\n\n    @Override\n    public Object getItem(int position) {\n        return listData.get(position);\n    }\n\n    @Override\n    public long getItemId(int position) {\n        return position;\n    }\n\n    public View getView(int position, View convertView, ViewGroup parent) {\n        ViewHolder holder;\n        if (convertView == null) {\n            convertView = layoutInflater.inflate(R.layout.list_row_layout, null);\n            holder = new ViewHolder();\n            holder.headlineView = (TextView) convertView.findViewById(R.id.title);\n            holder.reporterNameView = (TextView) convertView.findViewById(R.id.reporter);\n            holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);\n            convertView.setTag(holder);\n        } else {\n            holder = (ViewHolder) convertView.getTag();\n        }\n\n        holder.headlineView.setText(listData.get(position).getHeadline());\n        holder.reporterNameView.setText(\"By, \" + listData.get(position).getReporterName());\n        holder.reportedDateView.setText(listData.get(position).getDate());\n        return convertView;\n    }\n\n    static class ViewHolder {\n        TextView headlineView;\n        TextView reporterNameView;\n        TextView reportedDateView;\n    }\n}\n```\n\n### Declaring ListView Layout\n\nDeclare ListView in your activity layout.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"fill_parent\"\n    android:orientation=\"vertical\" \u003e\n\n    \u003cListView\n        android:id=\"@+id/custom_list\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:dividerHeight=\"1dp\" /\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n### Hooking Up to Activity\n\nWell, we are almost ready. Let us put all of them together and hook it up to the activity. Following code snippet depicts the activity class (MainActivity.java), where we initialize Adapter and hook it up to ListView.\n\n```java\npublic class MainActivity extends Activity {\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        ArrayList image_details = getListData();\n        final ListView lv1 = (ListView) findViewById(R.id.custom_list);\n        lv1.setAdapter(new CustomListAdapter(this, image_details));\n        lv1.setOnItemClickListener(new OnItemClickListener() {\n\n            @Override\n            public void onItemClick(AdapterView\u003c?\u003e a, View v, int position, long id) {\n                Object o = lv1.getItemAtPosition(position);\n                NewsItem newsData = (NewsItem) o;\n                Toast.makeText(MainActivity.this, \"Selected :\" + \" \" + newsData, Toast.LENGTH_LONG).show();\n            }\n        });\n    }
1\n\n    private ArrayList getListData() {\n        ArrayList\u003cNewsItem\u003e results = new ArrayList\u003cNewsItem\u003e();\n        NewsItem newsData = new NewsItem();\n        newsData.setHeadline(\"Dance of Democracy\");\n        newsData.setReporterName(\"Pankaj Gupta\");\n        newsData.setDate(\"May 26, 2013, 13:35\");\n        results.add(newsData);\n\n                // Add some more dummy data for testing\n        return results;\n    }\n}\n```\n\n[](http://stacktips.com)\n\n### Styling Android ListView\n\nLike any other view, ListView in Android can customized by color, background, selection color, etc. In this section of tutorial, we will learn how to customize an Android ListView.\n\n### Changing ListView Selection Color\n\nListView default selection color can be changed using selectors. Selectors enables to decide how list row will visually be represented based on different states. Let us change the background and text color while list row is in pressed state.\n\nCreate a new file named list\\_color\\_selector.xml inside your drawable folder and paste the following code snippets. This selector style will be used to change the background color when list row is pressed.\n\n```xml\n\u003cselector xmlns:android=\"http://schemas.android.com/apk/res/android\"\u003e\n     \u003c!-- Normal state. --\u003e\n    \u003citem android:drawable=\"@color/list_row_default_bg\"\n        android:state_pressed=\"false\"\n        android:state_selected=\"false\"/\u003e\n    \u003c!-- pressed state. --\u003e\n    \u003citem android:drawable=\"@color/list_row_pressed_bg\"\n        android:state_pressed=\"true\"/\u003e\n    \u003c!-- Selected state. --\u003e\n    \u003citem android:drawable=\"@color/list_row_selected_bg\"\n        android:state_pressed=\"false\"\n        android:state_selected=\"true\"/\u003e\n\n\u003c/selector\u003e\n```\n\nNow, let us create file and named it as list\\_item\\_text\\_selector.xml. This style will be used to change the text color while list row is pressed.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cselector xmlns:android=\"http://schemas.android.com/apk/res/android\"\u003e\n    \u003citem android:state_pressed=\"true\" android:color=\"@color/text_color_inverse\" /\u003e\n    \u003citem android:state_focused=\"true\" android:color=\"@color/text_color_inverse\" /\u003e\n    \u003citem android:color=\"@color/text_color_default\" /\u003e\n\u003c/selector\u003e\n```\n\nDefine the following colors inside colors.xml file. If you don’t have colors.xml file already than create one inside values folder and paste the following code snippets.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cresources\u003e\n    \u003ccolor name=\"text_color_default\"\u003e#00000C\u003c/color\u003e\n    \u003ccolor name=\"text_color_inverse\"\u003e#FFFFFF\u003c/color\u003e\n    \u003ccolor name=\"white\"\u003e#FFFFFF\u003c/color\u003e\n    \u003ccolor name=\"list_row_default_bg\"\u003e#ffffff\u003c/color\u003e\n    \u003ccolor name=\"list_row_pressed_bg\"\u003e#008cef\u003c/color\u003e\n    \u003ccolor name=\"list_row_selected_bg\"\u003e#86d3f6\u003c/color\u003e\n\u003c/resources\u003e\n```\n\nNow let us apply the list selector styles to ListView inside activity\\_main.xml file\n\n```xml\n \u003cListView\n        android:id=\"@+id/custom_list\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:listSelector=\"@drawable/list_color_selector\"\n        android:dividerHeight=\"1dp\" /\u003e\n```\n\nNow, we can apply the styles to text in “list\\_row\\_layout.xml”. Change all TextView widget textColor attribute as shown below\n\n```xml\n\u003cTextView\n        android:id=\"@+id/title\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"\"\n        android:textColor=\"@drawable/list_item_text_selector\"\n        android:textStyle=\"bold\"\n        android:typeface=\"sans\" /\u003e\n```\n\n### ListView Divider Style\n\nYou can use the following properties to change the list divider styles\n\n1.  The `android:divider` property is used to set the list divider color. It accepts the color in `#RRGGBBAA` format. It also accepts reference to the drawable, which will be shown as list drawable.\n2.  The `android:dividerHeight` property used to set the height of list divider. It can be defined in dp.\n\n```xml\n\u003cListView\n        android:id=\"@+id/custom_list\"\n        android:layout_width=\"fill_parent\"\n        android:layout_height=\"wrap_content\"\n        android:divider=\"#FF0000\"\n        android:dividerHeight=\"1dp\"\n        android:listSelector=\"@drawable/list_selector_flatcolor\" /\u003e\n```\n\n### Changing List Divider Pragmatically\n\nYou can also change the list view divider style programmatically form java code using `setDivi
1der()` method.\n\n```java\nListView listView = getListView();\nColorDrawable devidrColor = new ColorDrawable(\n      this.getResources().getColor(R.color.devidrColor));\nlistView.setDivider(devidrColor);\nlistView.setDividerHeight(1);\n```\n\n[](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"163:T4ac,\nJava provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.\n\nThe significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the StringBuffer Class we can remove the White spaces from a string.\n\n```java\nString normalizeWhitespaces(String s) {\n        StringBuffer res = new StringBuffer();\n        int prevIndex = 0;\n        int currIndex = -1;\n        int stringLength = s.length();\n        String searchString = \" \";\n        while ((currIndex = s.indexOf(searchString, currIndex + 1)) \u003e= 0) {\n            res.append(s.substring(prevIndex, currIndex + 1));\n\n            while (currIndex \u003c stringLength \u0026\u0026 s.charAt(currIndex) == ' ') {\n                currIndex++;\n            }\n\n            prevIndex = currIndex;\n        }\n        res.append(s.substring(prevIndex));\n\n        return res.toString();\n    }\n```\n164:T1aa6,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial explains how to download Image using AsyncTask in Android. The example below download image while showing progress bar while during download.\n\n## Understanding Android AsynkTask\n\nAsync task enables you to implement MultiThreading without get Hands dirty into threads. AsyncTask enables proper and easy use of the UI thread. It allows performing background operations and passing the results on the UI thread. If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.\n\n-   AsyncTasks should ideally be used for short operations (a few seconds at the most.)\n-   An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.\n-   In onPreExecute you can define code, which need to be executed before background processing starts.\n-   doInBackground have code which needs to be executed in background, here in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply.\n-   onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread\n-   onPostExecute() method handles results returned by doInBackground method.\n-   The generic types used are\n    -   Params, the type of the parameters sent to the task upon execution\n    -   Progress, the type of the progress units published during the background computation.\n    -   Result, the type of the result of the background computation.\n-   If an async task not using any types, then it can be marked as Void type.\n-   An running async task can be cancelled by calling cancel(boolean) method.\n\n## Downloading image using Android AsyncTask\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nandroid:layout_width=\"fill_parent\"\nandroid:layout_height=\"fill_parent\"\nandroid:orientation=\"vertical\" \u003e\n\n\u003cButton\nandroid:id=\"@+id/downloadButton\"\nandroid:layout_width=\"match_parent\"\nandroid:layout_height=\"wrap_content\"\nandroid:text=\"Click Here to Download\" /\u003e\n\n\u003cImageView\nandroid:id=\"@+id/imageView\"\nandroid:layout_width=\"match_parent\"\nandroid:layout_height=\"match_parent\"\nandroid:contentDescription=\"Your image will appear here\" \u003e\n\u003c/ImageView\u003e\n\n\u003c/LinearLayout\u003e\n```\n\n.java class\n\n```java\npackage com.javatechig.droid;\n\nimport java.io.InputStream;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.HttpStatus;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.Button;\nimport android.widget.ImageView;\n\npublic class ImageDownladerActivity extends Activity {\n\n    private ImageView downloadedImg;\n    private ProgressDialog simpleWaitDialog;\n    private String downloadUrl = \"http://www.9ori.com/store/media/images/8ab579a656.jpg\";\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.asynch);\n        Button imageDownloaderBtn = (Button) findViewById(R.id.downloadButton);\n\n        downloadedImg = (ImageView) findViewById(R.id.imageView);\n\n        imageDownloaderBtn.setOnClickListener(new OnClickListener() {\n\n            @Override\n            public void onClick(View v) {\n                // TODO Auto-generated method stub\n                new ImageDownloader().execute(downloadUrl);\n            }\n\n        });\n    }\n\n    private class ImageDownloader extends AsyncTask {\n\n        @Override\n        protected Bitmap doInBackgroun
1d(String... param) {\n            // TODO Auto-generated method stub\n            return downloadBitmap(param[0]);\n        }\n\n        @Override\n        protected void onPreExecute() {\n            Log.i(\"Async-Example\", \"onPreExecute Called\");\n            simpleWaitDialog = ProgressDialog.show(ImageDownladerActivity.this,\n                    \"Wait\", \"Downloading Image\");\n\n        }\n\n        @Override\n        protected void onPostExecute(Bitmap result) {\n            Log.i(\"Async-Example\", \"onPostExecute Called\");\n            downloadedImg.setImageBitmap(result);\n            simpleWaitDialog.dismiss();\n\n        }\n\n        private Bitmap downloadBitmap(String url) {\n            // initilize the default HTTP client object\n            final DefaultHttpClient client = new DefaultHttpClient();\n\n            //forming a HttoGet request\n            final HttpGet getRequest = new HttpGet(url);\n            try {\n\n                HttpResponse response = client.execute(getRequest);\n\n                //check 200 OK for success\n                final int statusCode = response.getStatusLine().getStatusCode();\n\n                if (statusCode != HttpStatus.SC_OK) {\n                    Log.w(\"ImageDownloader\", \"Error \" + statusCode +\n                            \" while retrieving bitmap from \" + url);\n                    return null;\n\n                }\n\n                final HttpEntity entity = response.getEntity();\n                if (entity != null) {\n                    InputStream inputStream = null;\n                    try {\n                        // getting contents from the stream\n                        inputStream = entity.getContent();\n\n                        // decoding stream data back into image Bitmap that android understands\n                        final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);\n\n                        return bitmap;\n                    } finally {\n                        if (inputStream != null) {\n                            inputStream.close();\n                        }\n                        entity.consumeContent();\n                    }\n                }\n            } catch (Exception e) {\n                // You Could provide a more explicit error message for IOException\n                getRequest.abort();\n                Log.e(\"ImageDownloader\", \"Something went wrong while\" +\n                        \" retrieving bitmap from \" + url + e.toString());\n            }\n\n            return null;\n        }\n    }\n}\n```\n\nOutput of the above code is  \n[![](/media/articles/433/image-downloader-thumb.png)](http://stacktips.com)\n\n**[Download Complete eclipse project from GitHub](https://github.com/javatechig/javatechig-android-advanced/tree/master/com.javatechig.imagedownloader)**\n"])</script>
1<script>self.__next_f.push([1,"165:T303a,"])</script>
1<script>self.__next_f.push([1,"\nThis tutorial describes how to create and use styles and themes in Android applications with examples and code snippets.\n\n## 1. Android Design Patterns\n\nAndroid is one among the most matured mobile platform today. Like every platforms, android development follows certain guidelines and patterns. The patterns are derived in order to make the app look amazing, simplifying life, and to provide the best performance. Google developers insist to follow the platform design guidelines for developing android applications. Remember to focus on below three overreaching goals while developing your applications\n\n1.  Application should be usable and easy to understand\n2.  Your app should strive to combine beauty. But remember not to make it too complex\n3.  Make your app not to heavy, it should be responsive.\n\nCheck out Google’s official design pattern guidelines [here.](http://developer.android.com/design/get-started/creative-vision.html)\n\n## 2. Using Custom Styles\n\nAndroid supports customizing view and widgets by applying styles. A style is a collection of properties that specify the look and format for a View or widget. A style can specify properties such as height, padding, font color, font size, background color, and much more. In Android Styles works similar to CSS (cascading stylesheets) that are used in web designing application.\n\nIn android Style’s are XML files that are placed in the `/res/values` directory of your project. The root node of the XML file must be `\u003cresources\u003e` and you use a style tag that includes the name attribute. This tag contains than more or more item tags which define values for named attributes. For example, the below example we will create a `TextView` in android using XML layout editor.\n\n```xml\n\u003cTextView\n    android:layout_width=\"fill_parent\"\n    android:layout_height=\"wrap_content\"\n    android:text=\"@string/hello_world\"\n    android:textColor=\"#006633\"\n    android:background=\"#f0f0f0\"\n    android:typeface=\"monospace\"\n    android:textStyle=\"italic\"\n    android:padding=\"5dp\"\u003e\n\u003c/TextView\u003e\n```\n\nThis works great for us, but what if we have to use the same or similar TextView style at multiple places in our application?? Yes, we can surely achieve this by copying the same style in multiple places. But that will result in following problems\n\n1.  What if we have to re-skinning our application tomorrow? We have to change in all over the places we have used the color, styles. And I am sure this will consume quite a lot time.\n2.  We will end up writing repetitive code, which is again difficult to maintain.\n\nSounds Frustrating? Now, we can overcome this by declaring a style for the `TextView`. A single style can be used by multiple places in our application. Change in the style at single place will reflect the changes all over. Sounds interesting? Let us see the below code snippet.\n\n```xml\n\u003cTextView\n    android:id=\"@+id/textView2\"\n    style=\"@style/MtTextViewStyle\"\n    android:text=\"@string/hello_world\"\u003e\n\u003c/TextView\u003e\n```\n\nIn this above code snippet, the `TextView` is referencing `@style/MyTextViewStyle` style.\n\n### 2.1. Defining Style Class\n\nA style xml file can be declared separately and that can be used or applied in other layout files. We can create a new xml file and save it in the `res/values/ directory` of your project. The root node of the XML file must be `\u003cresources\u003e`.\n\nMultiple styles can be defined in a single `style.xml` file. For each style you want to create, add a \u003cstyle\u003e element to the file with a name that uniquely identifies the style. Then add an `\u003citem\u003e` element for each property of that style, with a name that declares the style property and a value to go with it. The value for the `\u003citem\u003e` can be a keyword string, a hex color, a reference to another resource type, or other value depending on the style property.\n\nHere is the style we have defined for the TextView example\n\n```xml\n\u003cstyle name=\"MyTextViewStyle\"\u003e\n    \u003citem name=\"android:layout_width\"\u003efill_parent\u003c/item\u003e\n    \u003citem name=\"android:layout_height\"\u003ewrap_content\u003c/item\u003e\n    \u003citem name=\"android:textColor\"\u003e#006633\u003c/item\u003e\n    \u003citem name=\"android:typeface\"\u003emonospace\u003c/item\u003e\n    \u003citem name=\"android:background\"\u003e#f0f0f0\u003c/item\u003e\n    \u003citem name=\"android:textStyle\"\u003eitalic\u003c/item\u003e\n    \u003citem name=\"android:padding\"\u003e5dp\u003c/item\u003e\n\u003c/style\u003e\n```\n\n### 2.2. Apply a Style to View\n\nHere’s how to set a style for a View in the XML layout:\n\n```xml\n\u003cTextView\n    android:id=\"@+id/textView2\"\n    style=\"@style/MyTextViewStyle\"\n    android:text=\"@string/hello_world\"\u003e\n\u003c/TextView\u003e\n```\n\nNow this TextView will be styled as defined by the style named `**MyTextViewStyle**`\n\n### 2.3. Inheriting Built-in Platform Styles\n\nThe parent attribute in the `\u003cstyle\u003e` element lets you specify a style from which your style should inherit properties. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add. You can inherit from styles that you’ve created yourself or from styles that are built into the platform.\n\nBelow code snippet inherits the android platform’s default text appearance and then modify it `@android:style/TextAppearance.Large`\n\n```xml\n\u003cstyle name=\"MyTextViewStyle\" parent=\"@android:style/TextAppearance.Large\"\u003e\n        \u003citem name=\"android:layout_width\"\u003efill_parent\u003c/item\u003e\n        \u003citem name=\"android:layout_height\"\u003ewrap_content\u003c/item\u003e\n        \u003citem name=\"android:textColor\"\u003e#006633\u003c/item\u003e\n        \u003citem name=\"android:typeface\"\u003emonospace\u003c/item\u003e\n        \u003citem name=\"android:background\"\u003e#f0f0f0\u003c/item\u003e\n        \u003citem name=\"android:textStyle\"\u003eitalic\u003c/item\u003e\n        \u003citem name=\"android:padding\"\u003e5dp\u003c/item\u003e\n\u003c/style\u003e\n```\n\n### 2.4. Inheriting Self Defined Styles\n\nAndroid allows you to inherit other styles defined in the applications. Find the example below\n\n```xml\n\u003cstyle name=\"MyTextViewStyle\" parent=\"@android:style/TextAppearance.Large\"\u003e\n        \u003citem name=\"android:layout_width\"\u003efill_parent\u003c/item\u003e\n        \u003citem name=\"android:layout_height\"\u003ewrap_content\u003c/item\u003e\n        \u003citem name=\"android:textColor\"\u003e#006633\u003c/item\u003e\n        \u003citem name=\"android:typeface\"\u003emonospace\u003c/item\u003e\n        \u003citem name=\"android:background\"\u003e#f0f0f0\u003c/item\u003e\n        \u003citem name=\"android:textStyle\"\u003eitalic\u003c/item\u003e\n        \u003citem name=\"android:padding\"\u003e5dp\u003c/item\u003e\n    \u003c/style\u003e\n\n    \u003cstyle name=\"MyTextViewStyle.BoldRed\"\u003e\n        \u003citem name=\"android:textColor\"\u003e#FF0000\u003c/item\u003e\n        \u003citem name=\"android:textStyle\"\u003ebold\u003c/item\u003e\n    \u003c/style\u003e\n```\n\nNotice that there is no parent attribute in the \u003cstyle\u003e tag, but because the name attribute begins with the `MyTextViewStyle` style name, which is a style that you have created. `MyTextViewStyle.BoldRed` style inherits all style properties from that `MyTextViewStyle`. This style then overrides the android:textColor and android:textStyle property to make the text red and bold. The newly created style can be referenced from `TextView` as `@style/MyTextViewStyle.BoldRed`.\n\nYou can continue inheriting like this as many times as you’d like, by chaining names with periods.\n\n```xml\n\u003cstyle name=\"MtTextViewStyle\" parent=\"@android:style/TextAppearance.Large\"\u003e\n        \u003citem name=\"android:layout_width\"\u003efill_parent\u003c/item\u003e\n        \u003citem name=\"android:layout_height\"\u003ewrap_content\u003c/item\u003e\n        \u003citem name=\"android:textColor\"\u003e#006633\u003c/item\u003e\n        \u003citem name=\"android:typeface\"\u003emonospace\u003c/item\u003e\n        \u003citem name=\"android:background\"\u003e#f0f0f0\u003c/item\u003e\n        \u003citem name=\"android:textStyle\"\u003eitalic\u003c/item\u003e\n        \u003citem name=\"android:padding\"\u003e5dp\u003c/item\u003e\n    \u003c/style\u003e\n\n    \u003cstyle name=\"MtTextViewStyle.BoldRed\"\u003e\n        \u003citem name=\"android:textColor\"\u003e#FF0000\u003c/item\u003e\n        \u003citem name=\"android:textStyle\"\u003ebold\u003c/item\u003e\n    \u003c/style\u003e\n\n    \u003cstyle name=\"MtTextViewStyle.BoldRed.Big\"\u003e\n        \u003citem name=\"android:textSize\"\u003e30sp\u003c/item\u003e\n    \u003c/style\u003e\n```\n\nThis inherits from both `MyTextViewStyle` and `MyTextViewStyle.BoldRed` styles, then adds the `android:textSize` property.\n\n## 3. Applying Activity Themes\n\nA theme is a style applied to an entire activity or application, rather than an individual View. The technique of defining a theme is the same as defining a style.\n\n```xml\n\u003cstyle name=\"MyTheme\" parent=\"android:Theme.Light\"\u003e\n        \u003citem name=\"android:windowNoTitle\"\u003etrue\u003c/item\u003e\n        \u003citem name=\"android:colorBackgroun
1d\"\u003e@color/default_bg\u003c/item\u003e\n\u003c/style\u003e\n```\n\nThe above code, overrides the default `android:Theme.Light` theme and overrides `android:windowNoTitle` property.\n\nTo set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the \u003capplication\u003e tag to include the android:theme attribute with the style name. For example\n\n```xml\n\u003capplication android:theme=\"@style/MyTheme\"\u003e\n```\n\nIf you want a theme applied to just one Activity in your application, then add the android:theme attribute to the `\u003cactivity\u003e` tag.\n\n## 4. Using Nine-Patch Background\n\nA nine-patch drawable is a special kind of image which can be scaled in width and height while maintaining its visual integrity. Nine-patches are the most common way to specify the appearance of Android buttons, though any drawable type can be used. Notice the one pixel black lines around the edge; they control the scaling of the image.\n\nBelow are the images used in this example\n\n[![ic_green_button.9](/media/articles/434/ic_green_button.9-300x69.png)](http://stacktips.com)\n\n[![ic_orange_button.9](/media/articles/434/ic_orange_button.9-300x69.png)](http://stacktips.com)  \n\n1.  Save this bitmap inside drawable folder `/res/drawable/ic_green_button.9.png`\n2.  You may define a new style as explained below. Here we have created two styles `MyButton.Green` and `MyButton.Orange` for creating two buttons.\n\n```xml\n\u003cstyle name=\"MyButton\" parent=\"android:Widget.Button\"\u003e\n        \u003citem name=\"android:layout_width\"\u003efill_parent\u003c/item\u003e\n        \u003citem name=\"android:layout_height\"\u003ewrap_content\u003c/item\u003e\n        \u003citem name=\"android:textColor\"\u003e#ffffff\u003c/item\u003e\n         \u003citem name=\"android:textSize\"\u003e22sp\u003c/item\u003e\n    \u003c/style\u003e\n\n     \u003cstyle name=\"MyButton.Green\"\u003e\n        \u003citem name=\"android:background\"\u003e@drawable/ic_green_button\u003c/item\u003e\n    \u003c/style\u003e\n\n      \u003cstyle name=\"MyButton.Orange\"\u003e\n       \u003citem name=\"android:background\"\u003e@drawable/ic_orange_button\u003c/item\u003e\n    \u003c/style\u003e\n```\n\n1.  Apply the new button style to your button created inside your layout xml.\n\n```xml\n     \u003cButton\n         style=\"@style/MyButton.Green\"\n         android:text=\"GREEN BUTTON\" /\u003e\n\n     \u003cButton\n         style=\"@style/MyButton.Orange\"\n         android:text=\"ORANGE BUTTON\" /\u003e\n```\n\n# 5. Using Selector\n\nA selector is a drawable which changes based on state. Here is an example selector which switches between two images or two colors. For example, create `/res/drawable/button_selector.xml` to display two images depending on the button state.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cselector xmlns:android=\"http://schemas.android.com/apk/res/android\"\u003e\n\n    \u003citem android:drawable=\"@drawable/ic_green_button\" android:state_pressed=\"true\"/\u003e\n    \u003citem android:drawable=\"@drawable/ic_orange_button\"/\u003e\n\n\u003c/selector\u003e\n```\n\nNow you can use this selector as the drawable applied to the button style.\n\n```xml\n  \u003cstyle name=\"MyButton.Orange.Selector\"\u003e\n       \u003citem name=\"android:background\"\u003e@drawable/button_selector\u003c/item\u003e\n  \u003c/style\u003e\n```\n\n## 6. Gradient Drawables\n\nWe can define gradients in android xml file and apply to the interface. You can a gradient file in drawable folder `/res/drawable/my_gradient.xml` and add the following code\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cshape xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:shape=\"rectangle\" \u003e\n\n    \u003cgradient\n        android:angle=\"270\"\n        android:endColor=\"#62c4e7\"\n        android:startColor=\"#4a557c\" /\u003e\n\n\u003c/shape\u003e\n```\n\nNow apply the style to the button as background property\n\n```xml\n   \u003cstyle name=\"MyButton.Orange.Gradient\"\u003e\n       \u003citem name=\"android:background\"\u003e@drawable/my_gradient\u003c/item\u003e\n    \u003c/style\u003e\n```\n\n## 7. Make Activity L
1ook Like Dialog\n\nAndroid provides other built-in themes and styles which can be used without rewriting them yourself. You can use the Dialog theme and make your Activity appear like a dialog box\n\n```xml\n\u003cactivity android:theme=\"@android:style/Theme.Dialog\"\u003e\n```\n\nOr if you want the background to be transparent, use the translucent theme:\n\n```xml\n\u003cactivity android:theme=\"@android:style/Theme.Translucent\"\u003e\n```\n\n[](http://stacktips.com)\n"])</script>
1<script>self.__next_f.push([1,"166:T108f,"])</script>
1<script>self.__next_f.push([1,"\nThis post answers some of the common android interview questions and answers.\n\n### How to send SMS in Android?\n\nYou may send sms either using SmsManager or by invoking Built-in SMS application\n\nSending SMS using SmsManager API\n\n```java\nSmsManager smsManager = SmsManager.getDefault();\nsmsManager.sendTextMessage(\"\", null, \"\u003c message body\u003e\", null, null);\n```\n\nSmsManager require, SMS\\_SEND permission in your android mainfeast.\n\nSending SMS by invoking Built-in SMS application\n\n```java\nIntent sendIntent = new Intent(Intent.ACTION_VIEW);\nsendIntent.putExtra(\"sms_body\", “\");\nsendIntent.setType(\"vnd.android-dir/mms-sms\");\nstartActivity(sendIntent);\n```\n\n### How to Make a call in Android?\n\n```java\nIntent callIntent = new Intent(Intent.ACTION_CALL);\ncallIntent.setData(Uri.parse(\"tel:03777788\"));\nstartActivity(callIntent);\n```\n\n### How to send Email in Android?\n\nAndroid Intent is the handy way to send Email using your app.\n\n```java\nString to = toEmail.getText().toString();\nString subject = emailSubject.getText().toString();\nString message = emailBody.getText().toString();\nIntent email = new Intent(Intent.ACTION_SEND);\nemail.putExtra(Intent.EXTRA_EMAIL, new String[] { to });\nemail.putExtra(Intent.EXTRA_SUBJECT, subject);\nemail.putExtra(Intent.EXTRA_TEXT, message);\n\n// need this to prompts email client only\nemail.setType(\"message/rfc822\");\nstartActivity(Intent.createChooser(email, \"Choose an Email client\"));\n```\n\n### How to integrating sharing in Android?\n\nAndroid API made sharing feature handy. You don’t need to integrate the third party applications SDK’s like Facebook, twitter. Just a step to use share intent and it makes your application ready to share data to your social networks.\n\n```java\nIntent sendIntent = new Intent();\nsendIntent.setAction(Intent.ACTION_SEND);\nsendIntent.putExtra(Intent.EXTRA_TEXT, \"This is my text to send.\");\nsendIntent.setType(\"text/plain\");\nstartActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));\n```\n\n### How to open link in Android Browser?\n\n```java\nIntent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http://stacktips.com\"));\nstartActivity(browserIntent);\n```\n\n### How to Display HTML in Android TextView?\n\nIn android there is a lovely class `android.text.HTML` that processes HTML strings into displayable styled text. Currently android doesn’t support all HTML tags.\n\n`Html.formHtml()` method takes an `Html.TagHandler` and an `Html.ImageGetter` as arguments as well as the text to parse. We can parse null as for the Html.TagHandler but you’d need to implement your own Html.ImageGetter as there isn’t a default implementation. The Html.ImageGetter needs to run synchronously and if you’re downloading images from the web you’ll probably want to do that asynchronously. But in my example I am using the images from resources to make my ImageGetter implementation simpler.\n\n```java\nString htmlText = \"\u003chtml\u003e\u003cbody\u003e....\u003c/body\u003e\u003c/html\u003e\";\nTextView htmlTextView = (TextView)findViewById(R.id.html_text);\nhtmlTextView.setText(Html.fromHtml(htmlText, new ImageGetter(), null));\n```\n\n### How to display Android Toast?\n\nToast is a notification message that pop up, display a certain amount of time, and automatically fades in and out, most people just use it for debugging purpose. Below is the code snippets to create a Toast message\n\n```java\n//display in short period of time\nToast.makeText(getApplicationContext(), \"msg msg\", Toast.LENGTH_SHORT).show();\n\n//display in long period of time\nToast.makeText(getApplicationContext(), \"msg msg\", Toast.LENGTH_LONG).show();\n```\n\n[Android custom toast example](/articles/android-toast-example/)\n\n### How to Pass data between Activities in android\n\nWe an pass values between the activities, by using Bundles. Use below code to send data from ActivityA\n\n```java\nString name=\"StackTips\";\nString url=\"http://stacktips.com\";\nIntent intent=new Intent(ActivityA.this, ActivityB.class);\nintent.putExtra(\"name\", name);\nintent.putExtra(\"url\", url);\nstartActivity(intent);  \n```\n\nNow, you can retrieve the data in ActivityB using below code\n\n```java\nBundle bundle = new Bundle();\nbundle = getIntent().getExtras();\nString name = bundle.getString(\"name\");\nString url = bundle.getString(\"url\");\n```\n"])</script>
1<script>self.__next_f.push([1,"167:T1543,"])</script>
1<script>self.__next_f.push([1,"\nThis article will help you to understand the basic concept of Garbage Collection and the process flow for reference counting garbage collection.\n\nIn the previous post, [An Overview of Garbage Collector](http://stacktips.com/2012/02/27/overview-of-garbage-collector/), we just discussed the strategies for avoiding garbage collection. However, there are times when garbage collection is actually desirable. Imagine a program that requires a significant amount of memory. Suppose the amount of memory required is very close to the amount of memory available for use by the Java virtual machine. The performance of such a program is going to depend on the ability of the garbage collector to find and reclaim as much unused storage as possible.\n\nHow can we help out the garbage collector? Since the garbage collector collects only unreferenced objects it is necessary to eliminate all references to objects that are no longer needed. This can be done by assigning the value none to every variable that refers to an object that is no longer needed.\n\n## **Reference Counting Garbage Collection**\n\nThe difficulty in garbage collection is not the actual process of collecting the garbage–it is the problem of finding the garbage in the first place. An object is considered to be garbage when no references to that object exist. But how can we tell when no references to an object exist?\n\n[![reference counting garbage collection](/media/articles/440/reference-counitng-300x61.png)](http://stacktips.com)\n\nA simple expedient is to keep track in each object of the total number of references to that object. That is, we add a special field to each object called a reference count. The reference count field is not accessible to the Java program it is updated by the Java virtual machine itself. Consider the statement\n\n```java\nString state = “Alabama”;\n```\n\nThe above statement creates a new instance of the String class. Only a single variable, state, refers to the object. So, its reference count should be one. Now consider the following sequence of statements:\n\n```java\nString state = “Alabama”;\nString capital = state;\n```\n\nThis sequence creates a single String instance. Both state and capital refer to the same object. Therefore, its reference count should be two. Every time one reference variable is assigned to another, it is necessary to update several reference counts. Suppose p and q is both reference variables. The assignment\n\ncapital = state  \nwould be implemented by the Java virtual machine as follows:\n\n```java\nif(state != null){\n    state.refCount +=1;\n}\n```\n\nBut if state and capital is declared using as follows;\n\n```java\nString state = “Alabama”;\nString capital = “Alabama”;\ncapital = state;\n```\n\nThen in 1st line the reference count of both state and capital is one. But after state is assigned to capital, both are referred to the same object/memory location. So the reference count of state becomes 2 and capital becomes 0. So now capital is ready for garbage collector.\n\nThe costs of using reference counts are high. Every object requires the special reference count field, means an extra word of storage must be allocated in each object. Second, every time one reference is assigned to another, the reference counts must be adjusted. This increases significantly the time taken by assignment statements.\n\nThe advantage of using reference counts is that garbage is easily identified. When it becomes necessary to reclaim the storage from unused objects, the garbage collector needs only to examine the reference count fields of all the objects that have been created by the program. If the reference count is zero, the object is garbage.\n\nIt is not necessary to wait until there is insufficient memory before initiating the garbage collection process. We can reclaim memory used by an object immediately when its reference goes to zero.\n\n## Why reference counting doesn’t work?\n\nReference counting does not always work. It will fail to work whenever the data structure contains a cycle of references. Python does not prevent the creation of cyclic structures. Consider a circular, singly-linked list, the variable head refers to the head of the linked list and the last element of the linked list also refers to the head. So, the reference count on the first list element is two, whereas, the remaining list elements each has a reference count of one.\n\n[![reference counting garbage collection](/media/articles/440/referencecounting-fails-300x154.png)](http://stacktips.com \"reference counting garbage collection\")\n\nIf it happened to assign the value none to the head variable, then the reference count on the first list element has been decreased by one because the head variable no longer refers to it. But its reference count is not zero, because the tail of the list still refers to the head.\n\nWe now have a problem. The reference counts on all the lists elements are non-zero. Therefore, they are not considered to be garbage by a reference counting garbage collector. On the other hand, no external references to the linked-list elements remain. Therefore, the list elements are indeed garbage.\n\nReference counting will fail to work whenever the data structure contains a cycle of references, so reference counting by itself is not a suitable garbage collection scheme. However, it is a useful technique for dealing with simple objects that don’t refer to other objects, such as int and floats.\n"])</script>
1<script>self.__next_f.push([1,"168:Tf14,"])</script>
1<script>self.__next_f.push([1,"\nThis article will help you to understand the basic concept of Garbage Collection like dangling pointer, memory leak and strategies to avoid and reduce memory costs.\n\nObjects allocate memory at run-time for executing the programs. As long as a program contains a reference to some object instance, the virtual machine is required to ensure that the object exists. An un-referenced object is called garbage and the process of finding all the un-referenced objects and reclaiming the storage is called garbage collection.\n\n### Dangling pointer\n\nThe situation which arises when a program contains a reference to a destroyed object is called a dangling reference (or dangling pointer). It doesn’t allow the explicit destruction of objects. Languages like java, support the explicit destruction of objects typically require the program to keep track of all the objects it creates and to destroy them explicitly when they are no longer needed. If a program somehow loses track of an object it has created then that object cannot be destroyed. And if the object is never destroyed, the memory occupied by that object cannot be used again by the program.\n\n### Memory leak\n\nA program that loses track of objects before it destroys them suffers from a memory leak. If we run a program that has a memory leak for a very long time, it is quite possible that it will exhaust all the available memory and eventually fail because no new objects can be created.\n\n### Reduce, reuse, recycle\n\nThe slogan “reduce, reuse, recycle” prescribes three strategies for reducing the memory costs associated with waste objects. These strategies apply equally well to Java programs!\n\n### Reduce\n\nA program that does not create any object instances or arrays does not create garbage. Of course, a program that creates no objects is not very useful because it does nothing. A program that creates all the objects it needs at the beginning of its execution and uses the same objects until it terminates also does not create garbage. By reducing the number of objects a program creates dynamically during its execution, we can reduce or even eliminate the need for garbage collection.\n\n### Reuse\n\nSometimes, a Java program will create many objects which are used only once. For example, a program may create an object in the body of a loop that is used to hold temporary information that is only required for the particular iteration of the loop in which it is created. Consider the following:\n\n```java\nfor(int i=0; i    obj = new SomeClass(i);\n    System.out.priintln(obj.value);\n}\n```\n\nThis creates a million instances of the SomeClass class and prints them out. If the SomeClass class has a property, say value, we can reuse and a single object instance like this:\n\n```java\nobj = new SomeClass()\nfor(int i=0; i    obj.value = i;\nSystem.out.priintln(obj.value);\n}\n```\n\nClearly, by reusing a single object instance, we have dramatically reduced the amount of garbage produced. But it may not apply for all cases.\n\n### Recycle\n\nRecycling of objects is a somewhat more complex strategy for reducing the overhead associated with garbage collection. Instead leaving an unused object around for the garbage collector to find, it is put into a container of unused objects. When a new object is needed, the container is searched first to see if an unused one already exists. Because a container always refers to the objects it contains, those objects are never garbage collected.\n\nThe recycling strategy can indeed reduce garbage collection overhead. However, it puts the burden back on the programmer to explicitly put unused objects into the container to avoid memory leaks and to make sure objects put into the container are really unused to avoid dangling references. Because the recycling strategy undermines some of the benefits of garbage collection, it should be used with great c
1are.\n"])</script>
1<script>self.__next_f.push([1,"169:T127a,"])</script>
1<script>self.__next_f.push([1,"\n## What Is MDC?\n\nLogback's MDC (Mapped Diagnostic Context) allows you to enrich log messages with contextual information, such as a logged-in userId, making it easier to trace and debug logs across different components of an application.\n\nYou can programmatically add context information to your logs:\n\n```java\nMDC.put(\"userId\", \"user123\");\nlogger.info(\"Processing request\");\nMDC.remove(\"userId\");\n```\n\nAnything you `put` into MDC is available to every log statement on the current thread until you `remove` it — including log statements made deep inside other classes, as long as they run on the same thread.\n\n## Where MDC Actually Earns Its Keep\n\nPutting a value into MDC inside a one-off script doesn't really show why MDC matters — there's only one thread, one execution, nothing to distinguish. MDC's real value shows up once your application is handling multiple requests concurrently: each incoming HTTP request runs on its own thread, and MDC lets you tag every log line produced while handling that request with something that identifies it — a request ID, a userId, a tenant ID — so when you're staring at a wall of interleaved logs from dozens of simultaneous requests, you can filter down to just the ones that belong to the request you actually care about.\n\nThe cleanest way to do that in a Spring MVC app is with an interceptor: set the MDC value once, right when a request comes in, and clear it once the request finishes. Every log statement your controllers and services produce in between picks it up automatically, without you having to pass a request ID around as a method parameter everywhere.\n\n## Adding a Request ID with an Interceptor\n\n```java\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\nimport org.slf4j.MDC;\nimport org.springframework.web.servlet.HandlerInterceptor;\n\nimport java.util.UUID;\n\npublic class RequestLoggingInterceptor implements HandlerInterceptor {\n\n    private static final String REQUEST_ID = \"requestId\";\n\n    @Override\n    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {\n        MDC.put(REQUEST_ID, UUID.randomUUID().toString());\n        return true;\n    }\n\n    @Override\n    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {\n        MDC.remove(REQUEST_ID);\n    }\n}\n```\n\n`preHandle()` runs before your controller method, so that's where we generate a fresh ID and put it into MDC. `afterCompletion()` runs after the response has been sent, so that's where we clear it — otherwise, since threads get reused from a pool, the next unrelated request handled by the same thread could accidentally inherit the previous request's ID.\n\nRegister the interceptor so Spring actually uses it:\n\n```java\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.servlet.config.annotation.InterceptorRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\n\n@Configuration\npublic class WebConfig implements WebMvcConfigurer {\n\n    @Override\n    public void addInterceptors(InterceptorRegistry registry) {\n        registry.addInterceptor(new RequestLoggingInterceptor());\n    }\n}\n```\n\n## Including the Request ID in Your Logs\n\nAdd `%X{requestId}` to your log pattern to print whatever's currently stored in MDC under that key:\n\n```properties\nlogging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} [%X{requestId}] - %msg%n\n```\n\nNow, if two requests hit your app around the same time, their logs stay distinguishable even when interleaved:\n\n```text\n2026-08-19 10:22:14 [http-nio-8080-exec-1] INFO  c.s.hello_spring.WeatherController [a1b2c3d4-...] - Handling GET /weather\n2026-08-19 10:22:14 [http-nio-8080-exec-2] INFO  c.s.hello_spring.HelloController [f9e8d7c6-...] - Handling GET /hello\n2026-08-19 10:22:14 [http-nio-8080-exec-1] INFO  c.s.hello_spring.WeatherController [a1b2c3d4-...] - Returning forecast for New York\n2026-08-19 10:22:14 [http-nio-8080-exec-2] INFO  c.s.hello_spring.HelloController [f9e8d7c6-...] - Returning greeting\n```\n\nEven though the two requests' log lines are interleaved on the console, grepping for `a1b2c3d4` gives you every log line that belongs to that one `/weather` request, and nothing else.\n\n## Summary\n\nMDC lets you attach context — like a request ID or a userId — to every log line produced while handling a request, without threading that value through every method call by hand. Paired with an interceptor that sets it in `preHandle()` and clears it in `afterCompletion()`, it turns a wall of interleaved logs from concurrent requests into something you can actually filter and trace.\n"])</script>
1<script>self.__next_f.push([1,"d:[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"div\",null,{\"className\":\"mx-auto max-w-7xl px-4 py-14 sm:px-6\",\"children\":[[\"$\",\"h1\",null,{\"className\":\"font-display text-balance text-4xl font-medium tracking-tighter text-ink sm:text-5xl\",\"children\":\"Tutorials\"}],[\"$\",\"p\",null,{\"className\":\"mt-4 max-w-2xl text-lg leading-relaxed text-ink-muted\",\"children\":\"Step-by-step tutorials to master Java, Spring, Python, Android and Git concepts. From beginner-friendly guides to advanced techniques.\"}],[\"$\",\"div\",null,{\"className\":\"mt-8\",\"children\":[\"$\",\"$L15\",null,{\"articles\":[{\"id\":464,\"title\":\"Building Your First REST API with Spring Boot\",\"slug\":\"building-your-first-rest-api-with-spring-boot\",\"excerpt\":\"A hands-on guide to building your first REST endpoints in Spring Boot using @RestController and @GetMapping, and returning JSON from your API.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2026-08-17T00:00:00.000Z\",\"updatedDate\":\"2026-08-17T00:00:00.000Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-rest-api\",\"restcontroller-annotation\",\"getmapping-annotation\",\"json-response-spring-boot\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":9,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$16\"},{\"id\":463,\"title\":\"Setting Up Your First Spring Boot Project\",\"slug\":\"setting-up-your-first-spring-boot-project\",\"excerpt\":\"A step-by-step guide to bootstrapping your first Spring Boot project using Spring Initializr and IntelliJ IDEA, and running it for the first time.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2026-08-16T00:00:00.000Z\",\"updatedDate\":\"2026-08-16T00:00:00.000Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"spring-boot\"],\"tags\":[\"spring-initializr\",\"spring-boot-setup-intellij\",\"bootstrap-spring-boot-project\",\"running-spring-boot-application\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":3,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$17\"},{\"id\":445,\"title\":\"Configuration Management in Spring Boot\",\"slug\":\"configuration-management-in-spring-boot\",\"excerpt\":\"This chapter covers how Spring Boot loads configuration from properties files, YAML, environment variables, and command-line arguments, including @Value, @ConfigurationProperties, and profile-specific overrides.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-10-24T21:49:07.000Z\",\"updatedDate\":\"2025-09-16T23:05:42.216Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/post/None_configuration-management-in-spring-boot.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-application-properties\",\"spring-boot-yaml-configuration\",\"spring-value-annotation\",\"spring-profiles-configuration\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":7,\"seo\":{\"metaTitle\":\"Configuration Management in Spring Boot Explained\",\"metaDescription\":\"Learn how Spring Boot loads and prioritizes configuration from properties files, environment variables, and command-line arguments across environments.\",\"metaKeywords\":null},\"content\":\"$18\"},{\"id\":462,\"title\":\"Prerequisites for Spring Boot Development\",\"slug\":\"prerequisites-for-spring-boot-development\",\"excerpt\":\"A step-by-step guide that explains prerequisites for Spring Boot Development.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2024-10-19T21:57:03.000Z\",\"updatedDate\":\"2025-09-16T23:05:42.145Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-prerequisites\",\"maven-vs-gradle\",\"spring-boot-setup-intellij\",\"java-ide-for-spring-boot\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":2,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$19\"},{\"id\":390,\"title\":\"Java 17 Interview Questions and Answers\",\"slug\":\"java-17-interview-questions-and-answers\",\"excerpt\":\"A curated set of interview questions and answers on Java 17.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-10-03T22:59:19.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.878Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":true,\"thumbnail\":\"/media/posts/java-17-interview-questions-and-answers.jpeg\",\"topics\":[\"java\"],\"tags\":[\"java-17-interview-questions\",\"java-sealed-classes\",\"java-records\",\"java-pattern-matching-switch\",\"java-text-blocks\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$1a\"},{\"id\":422,\"title\":\"Spring, Spring Boot Interview Question Answers\",\"slug\":\"spring-boot-interview-questions-and-answers\",\"excerpt\":\"A curated set of interview questions and answers on spring, spring boot, JPA and Hibernate\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2024-09-29T21:32:58.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.595Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-interview-questions\",\"dependency-injection-spring\",\"jpa-hibernate-interview\",\"n-plus-one-query-problem\",\"resttemplate-vs-webclient\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$1b\"},{\"id\":353,\"title\":\"Most Popular Java Interview Questions and Answers\",\"slug\":\"most-popular-java-interview-questions-and-answers\",\"excerpt\":\"A comprehensive list of the most important and commonly asked Java interview questions and answers with detailed explanations.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-09-29T10:04:36.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.520Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-interview-questions\",\"java-default-methods-interface\",\"java-functional-interface\",\"stringbuilder-vs-stringbuffer\",\"java-serialization\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$1c\"},{\"id\":461,\"title\":\"Essential MongoDB Optimization Tips for Spring Boot Applications\",\"slug\":\"essential-mongodb-optimization-tips-for-spring-boot\",\"excerpt\":\"This article delves into some key optimization techniques and considerations to improve the overall application performance when dealing with MongoDB from Spring Boot.\",\"difficulty\":\"advanced\",\"publishedDate\":\"2024-07-28T00:04:02.000Z\",\"updatedDate\":\"2025-09-16T23:05:42.105Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":true,\"thumbnail\":\"/media/post/690_Essential_MongoDB_Optimization_Tips_for_Spring_Boot_Application-min.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"mongodb-indexing\",\"mongodb-optimization\",\"mongodb-performance\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"10 MongoDB Optimization Tips for Spring Boot Apps\",\"metaDescription\":\"Improve MongoDB performance in Spring Boot with tips on indexing, connection pooling, pagination, write concerns, projections, caching, and bulk operations.\",\"metaKeywords\":null},\"content\":\"$1d\"},{\"id\":460,\"title\":\"Introduction to Java Collections\",\"slug\":\"introduction-to-java-collections\",\"excerpt\":\"Java Collections API is a set of interfaces and implementations included in the Java standard library.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:43:39.000Z\",\"updatedDate\":\"2025-09-16T23:05:42.074Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-collections-framework\",\"java-list-set-map-interface\",\"java-util-collection\",\"java-collections-hierarchy\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$1e\"},{\"id\":459,\"title\":\"Hashtable in Java\",\"slug\":\"hashtable-in-java\",\"excerpt\":\"The Hashtable is a legacy implementation of HashMap. It provides a key-value store where the keys are hashed. HashMap performs better than Hashtable.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:34:17.000Z\",\"updatedDate\":\"2025-09-16T23:05:42.046Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-hashtable\",\"hashtable-vs-hashmap\",\"thread-safe-collections\",\"java-collections-framework\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":16,\"seo\":{\"metaTitle\":\"Hashtable in Java: Thread-Safe Key-Value Store Explained\",\"metaDescription\":\"Learn how Java's Hashtable works as a synchronized, thread-safe key-value store, why it disallows null values, and how it compares to HashMap.\",\"metaKeywords\":null},\"content\":\"$1f\"},{\"id\":458,\"title\":\"TreeMap in Java\",\"slug\":\"treemap-in-java\",\"excerpt\":\"The TreeMap implements the NavigableMap interface and the NavigableMap interface extends the SortedMap. It stores the items in a sorted order.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:33:54.000Z\",\"updatedDate\":\"2025-09-16T23:05:42.014Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-treemap-class\",\"navigablemap-sortedmap\",\"treemap-custom-comparator\",\"java-collections-sorted-map\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":15,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$20\"},{\"id\":457,\"title\":\"IdentityHashMap in Java\",\"slug\":\"identityhashmap-in-java\",\"excerpt\":\"The IdentityHashMap implements the Map interface. It compares the reference addresses of the keys instead of their content.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:31:59.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.945Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"identityhashmap-java\",\"java-reference-equality-map\",\"hashmap-vs-identityhashmap\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":14,\"seo\":{\"metaTitle\":\"IdentityHashMap in Java: How It Differs From HashMap\",\"metaDescription\":\"Learn how IdentityHashMap in Java uses reference equality instead of equals() to compare keys, with code examples comparing it to a standard HashMap.\",\"metaKeywords\":null},\"content\":\"$21\"},{\"id\":456,\"title\":\"LinkedHashMap in Java\",\"slug\":\"linkedhashmap-in-java\",\"excerpt\":\"The LinkedHashMap works very similar to HashMap but it maintains a doubly-linked list to maintain the insertion order of elements.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:30:48.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.904Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"linkedhashmap-java\",\"linkedhashmap-vs-hashmap\",\"access-order-linkedhashmap\",\"java-map-insertion-order\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":13,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$22\"},{\"id\":455,\"title\":\"HashMap in Java\",\"slug\":\"hashmap-in-java\",\"excerpt\":\"A HashMap uses key-value pairs to insert and access items.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:29:36.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.872Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-hashmap\",\"hashmap-iteration\",\"java-collections-framework\",\"key-value-store\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":12,\"seo\":{\"metaTitle\":\"HashMap in Java: Guide to Creating, Iterating \u0026 Using It\",\"metaDescription\":\"Learn how HashMap works in Java, including how to create, initialize, and iterate over key-value pairs using iterators, streams, and forEach.\",\"metaKeywords\":null},\"content\":\"$23\"},{\"id\":454,\"title\":\"ArrayDeque in Java\",\"slug\":\"arraydeque-in-java\",\"excerpt\":\"The ArrayDeque is a resizable array implementation of the `Deque` interface. It supports adding and removing elements from both ends of the deque (double-ended queue) efficie
1ntly.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:27:50.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.841Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-arraydeque\",\"java-deque-interface\",\"undo-redo-stack-java\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":11,\"seo\":{\"metaTitle\":\"ArrayDeque in Java: Guide with Undo/Redo Example\",\"metaDescription\":\"Learn how Java's ArrayDeque works as both a stack and queue, and see a practical undo/redo text editor example that uses two ArrayDeque instances.\",\"metaKeywords\":null},\"content\":\"$24\"},{\"id\":453,\"title\":\"DelayQueue in Java\",\"slug\":\"delayqueue\",\"excerpt\":\"DelayQueue in Java is a specialized implementation of a blocking queue that supports delayed elements\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:25:39.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.808Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-delayqueue\",\"java-delayed-interface\",\"blockingqueue-java\",\"delayed-task-scheduling-java\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":10,\"seo\":{\"metaTitle\":\"DelayQueue in Java: Delayed Task Scheduling Example\",\"metaDescription\":\"Learn how Java's DelayQueue works with the Delayed interface, and see a working example that schedules and processes delayed notifications.\",\"metaKeywords\":null},\"content\":\"$25\"},{\"id\":452,\"title\":\"PriorityQueue in Java\",\"slug\":\"priorityqueue-in-java\",\"excerpt\":\"PriorityQueue is a type of queue that stores elements in a way such that the element with the highest priority is always at the front of the queue\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:24:09.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.770Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"priorityqueue-java\",\"java-binary-heap\",\"priorityqueue-comparator\",\"java-collections-priorityqueue\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":9,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$26\"},{\"id\":451,\"title\":\"TreeSet in Java\",\"slug\":\"treeset-in-java\",\"excerpt\":\"A TreeSet in Java is a collection that implements the NavigableSet interface and uses a TreeMap internally to store elements.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:21:59.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.738Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"treeset-java\",\"navigableset\",\"sorted-collection-java\",\"java-collections-framework\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":8,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$27\"},{\"id\":450,\"title\":\"LinkedHashSet in Java\",\"slug\":\"linkedhashset-in-java\",\"excerpt\":\"A LinkedHashSet combines the behaviour of a hash table and a linked list. Elements are unique, while insertion order is preserved.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:20:23.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.703Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"linkedhashset-java\",\"linkedhashset-vs-hashset\",\"java-set-insertion-order\",\"unique-elements-java-collections\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":7,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$28\"},{\"id\":449,\"title\":\"HashSet in Java\",\"slug\":\"hashset-in-java\",\"excerpt\":\"The `HashSet` is a collection that uses a hash table for storage. Elements are stored by hashing and as a result, it only supports unique elements.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-24T05:19:20.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.671Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-hashset\",\"hashset-iteration\",\"java-collections-framework\",\"remove-duplicates-java\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":6,\"seo\":{\"metaTitle\":\"HashSet in Java: Create, Iterate, and Remove Elements\",\"metaDescription\":\"Learn how HashSet works in Java for storing unique elements, plus how to create, iterate, and remove items using iterators, streams, and predicates.\",\"metaKeywords\":null},\"content\":\"$29\"},{\"id\":448,\"title\":\"Stack in Java\",\"slug\":\"stack-in-java\",\"excerpt\":\"Stack extends Vector with five operations that allow a vector to be treated as a stack. It supports last-in, first-out (LIFO) operations.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-07T19:42:19.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.640Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-stack-class\",\"lifo-data-structure\",\"stack-push-pop-peek\",\"java-vector-collections\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":5,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$2a\"},{\"id\":447,\"title\":\"Vector in Java\",\"slug\":\"vector-in-java\",\"excerpt\":\"Vector is a legacy implementation of a list added to Java since version 1.0. It was later moved to the Java Collections Framework and retrofitted to implement the `List` interface.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-07T19:37:29.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.608Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"vector-class-java\",\"java-vector-vs-arraylist\",\"synchronized-collection-java\",\"java-legacy-collections\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":4,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$2b\"},{\"id\":446,\"title\":\"CopyOnWriteArrayList in Java\",\"slug\":\"copyonwritearraylist-in-java\",\"excerpt\":\"The CopyOnWriteArrayList is the thread-safe implementation of the List interface. It is very useful when we want to iterate over a list in a thread-safe way without explicit synchronization.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-07T19:35:52.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.579Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"how-tos\",\"code-snippet\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":3,\"seo\":{\"metaTitle\":\"CopyOnWriteArrayList in Java: Thread-Safe List Example\",\"metaDescription\":\"Learn how CopyOnWriteArrayList provides thread-safe iteration in Java without ConcurrentModificationException, plus when it's slower than ArrayList.\",\"metaKeywords\":null},\"content\":\"$2c\"},{\"id\":443,\"title\":\"LinkedList in Java\",\"slug\":\"linkedlist-in-java\",\"excerpt\":\"LinkedList uses a doubly linked list to store elements and it implements both the List and Queue interfaces.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-07T19:34:13.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.552Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"linkedlist-java\",\"linkedlist-vs-arraylist\",\"java-list-iterator\",\"java-deque-queue-example\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":2,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$2d\"},{\"id\":442,\"title\":\"ArrayList in Java\",\"slug\":\"arraylist-in-java\",\"excerpt\":\"ArrayList is similar to a regular array except that the size is dynamically adjusted as the number of items in the collection changes.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-07-07T19:30:12.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.526Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-arraylist\",\"synchronized-arraylist\",\"java-immutable-list\",\"arraylist-vs-array\"],\"course\":\"beginners-guide-to-java-collections\",\"displayOrder\":1,\"seo\":{\"metaTitle\":\"ArrayList in Java: Complete Guide with Examples\",\"metaDescription\":\"Learn how to create, iterate, and modify a Java ArrayList, understand its time complexity, and see why it isn't thread-safe with practical code examples.\",\"metaKeywords\":null},\"content\":\"$2e\"},{\"id\":441,\"title\":\"Static Variables, Methods, and Class\",\"slug\":\"static-keyowrd-in-java\",\"excerpt\":\"This article covers static keyword in Java and how static can be applied to a class, variables and on a method.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-06-29T09:58:05.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.499Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-static-keyword\",\"static-variables-methods\",\"static-nested-class-java\",\"java-static-vs-instance\"],\"course\":\"getting-started-with-java\",\"displayOrder\":21,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$2f\"},{\"id\":439,\"title\":\"Importing CSV Data into PostgreSQL using Spring Boot Batch\",\"slug\":\"importing-csv-data-into-postgresql-using-spring-boot-batch\",\"excerpt\":\"In this tutorial, we will build a Spring boot application that uses Spring Batch to import CSV content into Postgres SQL DB and use Flyway for database migration.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-05-21T05:54:28.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.440Z\",\"videoLink\":\"XBW3D1f6CAA\",\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/spring-batch-chunk-processing\",\"featured\":true,\"thumbnail\":\"/media/post/668_thumbnail.001-min.jpeg\",\"topics\":[\"spring-boot\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$30\"},{\"id\":438,\"title\":\"Digging into HTTP Clients in Spring: From RestTemplate to HTTP Interface\",\"slug\":\"rest-clients-in-spring\",\"excerpt\":\"This post explores different options available for making REST API calls from Spring and dives into the strengths and weaknesses of each.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2024-04-29T16:59:57.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.405Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/spring-rest-clients\",\"featured\":true,\"thumbnail\":\"/media/post/667_rest-clients-in-spring-framework.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-resttemplate\",\"spring-webclient\",\"spring-http-interface\",\"feign-client\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$31\"},{\"id\":437,\"title\":\"Using Flyway for Database Migration in Spring Boot\",\"slug\":\"using-flyway-for-database-migration-in-spring-boot\",\"excerpt\":\"A step-by-step guide to configure and use flyway for managing database migrations in spring boot application. This example uses Springboot3, MySQL8 \u0026 JPA.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2024-03-28T20:54:24.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.370Z\",\"videoLink\":\"3ts61KR6v5g\",\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/spring-jpa-flyway\",\"featured\":true,\"thumbnail\":\"/media/post/666_using-flyway-for-database-migration-in-springboot.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"flyway-spring-boot-migration\",\"flyway-mysql-setup\",\"ver
1sioned-vs-repeatable-migrations\",\"flyway-maven-plugin\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$32\"},{\"id\":436,\"title\":\"Understanding Spring Boot Project Structure\",\"slug\":\"understanding-spring-boot-project-structure\",\"excerpt\":\"This chapter covers, understanding the Spring Boot project structure.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-03-22T09:48:34.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.337Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/post/664_spring-boot-project-structure.jpeg\",\"topics\":[\"spring-boot\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":4,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$33\"},{\"id\":435,\"title\":\"Logging in Spring Boot\",\"slug\":\"logging-in-spring-boot\",\"excerpt\":\"In this chapter, we will learn about different logging options available in Spring Boot and understand about different log levels and configurations for your Spring Boot application.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-03-22T09:46:26.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.311Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/spring-boot-logging\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-logging\",\"slf4j-logback\",\"spring-boot-log-levels\",\"actuator-runtime-log-level\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":8,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$34\"},{\"id\":434,\"title\":\"Dependency Injection in Spring Boot\",\"slug\":\"dependency-injection-in-spring-boot\",\"excerpt\":\"This chapter covers how Depen
1dency Injection works in Spring Boot including @Autowired, field injection, constructor injection and setter method injection.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-03-22T09:35:19.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.280Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/spring-dependency-injection\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"spring-boot\"],\"tags\":[\"spring-dependency-injection\",\"spring-autowired-annotation\",\"constructor-vs-field-injection\",\"spring-bean-configuration\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":5,\"seo\":{\"metaTitle\":\"Dependency Injection in Spring Boot: Complete Guide\",\"metaDescription\":\"Understand Dependency Injection in Spring Boot, including bean registration, and the differences between field, constructor, and setter injection.\",\"metaKeywords\":null},\"content\":\"$35\"},{\"id\":433,\"title\":\"Testing Spring Boot Repository Using MongoDB Testcontainers\",\"slug\":\"testing-spring-boot-repository-using-mongodb-testcontainers\",\"excerpt\":\"In this article, we will use MongoDB Testcontainers to test spring boot Repository that uses MongoTemplate to search data from DB.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-03-10T00:36:15.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.244Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/testing-spring-boot-mongodb-testcontainer\",\"featured\":true,\"thumbnail\":\"/media/posts/testing-spring-boot-repository-using-mongodb-testcontainers.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"mongodb-testcontainers\",\"spring-boot-mongotemplate-testing\",\"testcontainers-junit5\",\"spring-data-mongodb-repository-test\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$36\"},{\"id\":432,\"title\":\"Choosing from Multiple Bean Implementations in Spring Boot\",\"slug\":\"choose-from-multiple-bean-types-springboot\",\"excerpt\":\"In this article we will explore what are the different approaches to inject beans conditionally when you have multiple implantation of an component or service.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2024-03-09T14:48:26.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.209Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/spring-boot-conditional-bean\",\"featured\":false,\"thumbnail\":\"/media/posts/choose-bean-from-multiple-bean-types-spring-boot.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-multiple-bean-implementations\",\"spring-qualifier-annotation\",\"spring-primary-annotation\",\"spring-conditional-bean-selection\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Choosing Between Multiple Bean Implementations in Spring Boot\",\"metaDescription\":\"Learn how to inject the right bean when multiple implementations of the same interface exist in Spring Boot, using @Qualifier, @Primary, and conditional beans.\",\"metaKeywords\":null},\"content\":\"$37\"},{\"id\":431,\"title\":\"Dynamic Scheduling in Quartz with Spring Boot Actuators\",\"slug\":\"dynamic-scheduling-in-quartz-with-spring-boot-actuators\",\"excerpt\":\"A step by step guide explains how to do the dynamic scheduling in quartz using custom spring boot actuators.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2024-02-26T22:43:54.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.172Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/quartz-scheduler\",\"featured\":false,\"thumbnail\":\"/media/posts/dynamic-scheduling-in-quartz-with-spring-boot-actuators.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"quartz-scheduler-java\",\"spring-boot-custom-actuator\",\"dynamic-cron-job-scheduling\",\"quartz-job-management\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Dynamic Job Scheduling in Quartz with Spring Boot Actuators\",\"metaDescription\":\"Learn how to dynamically start, stop, and update Quartz scheduler jobs at runtime using a custom Spring Boot actuator endpoint, with full code examples.\",\"metaKeywords\":null},\"content\":\"$38\"},{\"id\":430,\"title\":\"Working with Quartz Scheduler in Spring Boot\",\"slug\":\"working-with-quartz-scheduler-in-spring-boot\",\"excerpt\":\"A step by step guide that c
1overs different configuration of Quartz Scheduler and integration with Spring Boot application.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-02-22T22:43:58.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.139Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/quartz-scheduler\",\"featured\":true,\"thumbnail\":\"/media/posts/working-with-quartz-scheduler-in-spring-boot.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"quartz-scheduler\",\"spring-boot-cron-job\",\"job-scheduling-java\",\"interruptable-job-quartz\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$39\"},{\"id\":429,\"title\":\"Working with Spring Boot Actuators\",\"slug\":\"working-with-spring-boot-actuators\",\"excerpt\":\"In this chapter, we will explore the Spring Boot Actuators. The Actuator offers production-ready features such as monitoring and metrics to Spring Boot applications.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-02-18T20:43:21.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.102Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/posts/working-with-spring-boot-actuators.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-actuator\",\"custom-actuator-endpoint\",\"actuator-health-endpoint\",\"spring-boot-monitoring\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":23,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$3a\"},{\"id\":428,\"title\":\"Validating @ConfigurationProperties in Spring Boot\",\"slug\":\"validating-configurationproperties-in-spring-boot\",\"excerpt\":\"Article explains how to validate @ConfigurationProperties in Spring Boot Application Startup\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2024-02-18T02:45:30.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.067Z\",\"videoLink\":\"xMORu5AP67c\",\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/configuration-property-validation\",\"featured\":false,\"thumbnail\":\"/media/posts/validating-configurationproperties-in-spring-boot.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"configurationproperties-validation\",\"spring-boot-validated-annotation\",\"jsr-380-bean-validation\",\"configurationproperties-records\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$3b\"},{\"id\":380,\"title\":\"Task Execution and Scheduling in Spring Boot\",\"slug\":\"task-execution-and-scheduling-in-spring-boot\",\"excerpt\":\"Article covers everything you need to know about Spring Scheduler – including the annotations, examples, and other things to consider.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-02-14T17:05:32.000Z\",\"updatedDate\":\"2025-09-16T23:05:41.026Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/posts/Task_Scheduler_Spring_Boot.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-scheduled-annotation\",\"spring-boot-cron-expression\",\"fixedrate-vs-fixeddelay\",\"spring-task-scheduler\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$3c\"},{\"id\":400,\"title\":\"Working XML-Based REST API with Spring Boot\",\"slug\":\"handling-xml-request-and-response-in-spring-boot-rest\",\"excerpt\":\"This article explains how to handle XML requests and responses in Spring Boot REST APIs using jackson-dataformat-xml dependency.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2024-02-08T00:57:38.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.987Z\",\"videoLink\":\"O0W3X9hX5bU\",\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/spring-boot-movies-xml-api\",\"featured\":false,\"thumbnail\":\"/media/posts/Working_with_XML_in_Spring_Boot_REST.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-xml-rest-api\",\"jackson-dataformat-xml\",\"spring-boot-content-negotiation\",\"jacksonxmlrootelement-annotation\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Handling XML Requests and Responses in Spring Boot REST\",\"metaDescription\":\"Learn how to build an XML-based REST API in Spring Boot using jackson-dataformat-xml, content negotiation, and custom XML response wrapping.\",\"metaKeywords\":null},\"content\":\"$3d\"},{\"id\":398,\"title\":\"How to Validate the @PathVariable in Spring Boot?\",\"slug\":\"how-to-validate-the-pathvariable-in-spring-boot\",\"excerpt\":\"This article explains different options available to Validate the @PathVariable in Spring Boot such as using Spring Boot annotations, regular expression, and custom validator.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2024-01-29T12:57:24.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.920Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/posts/Validate_the_PathVariable_in_Spring_Boot.jpeg\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-pathvariable-validation\",\"spring-boot-custom-validator\",\"constraintvalidator-example\",\"spring-pattern-annotation-validation\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":11,\"seo\":{\"metaTitle\":\"How to Validate @PathVariable in Spring Boot\",\"metaDescription\":\"Learn how to validate @PathVariable in Spring Boot using @NotEmpty, @Pattern regex validation, a custom ConstraintValidator, and manual validation.\",\"metaKeywords\":null},\"content\":\"$3e\"},{\"id\":389,\"title\":\"Creating Parameterized Tests in JUnit 5\",\"slug\":\"parameterized-tests-in-junit-5\",\"excerpt\":\"Parameterized tests allow you to execute a single test multiple times using different parameters. This article explains the usage of each of these test sources using @ParameterizedTest annotation in Junit5.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2024-01-28T00:34:24.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.846Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/posts/parameterized-tests-in-junit-5.jpeg\",\"topics\":[\"junit5\"],\"tags\":[\"junit5-parameterized-test\",\"valuesource-junit\",\"methodsource-junit\",\"csvsource-junit\",\"junit5-testing\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$3f\"},{\"id\":427,\"title\":\"Testing Spring Boot REST API using Mockito and MockMvc\",\"slug\":\"testing-spring-boot-using-mockito-and-mockmvc\",\"excerpt\":\"Testing Spring Boot REST API using Mockito and MockMvc\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-01-27T16:20:41.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.822Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/02-testing-spring-boot\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"spring-boot\"],\"tags\":[\"mockmvc-spring-boot-testing\",\"mockito-unit-testing-java\",\"webmvctest-annotation\",\"spring-boot-rest-api-testing\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":24,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$40\"},{\"id\":426,\"title\":\"Order of Test Methods in JUnit5\",\"slug\":\"the-order-of-tests-in-junit5\",\"excerpt\":\"This article explains how to order the execution of test methods in Junit5. It explains different options such as order by DisplayName, MethodName, Random, OrderAnnotation or based on a custom order.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2024-01-26T15:52:16.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.743Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/posts/the-order-of-tests-in-junit5.jpeg\",\"topics\":[\"junit5\"],\"tags\":[\"junit5-testmethodorder\",\"junit5-order-annotation\",\"junit-test-execution-order\",\"custom-methodorderer-junit5\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$41\"},{\"id\":425,\"title\":\"Java Program to Find the Minimum Depth of Binary Tree\",\"slug\":\"java-program-to-find-the-minimum-depth-of-binary-tree\",\"excerpt\":\"Given a binary search tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-01-23T09:16:16.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.699Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/posts/java-program-to-find-the-minimum-depth-of-binary-tree.jpeg\",\"topics\":[\"java\"],\"tags\":[\"binary-search-tree-java\",\"minimum-depth-binary-tree\",\"leetcode-java-solution\",\"tree-traversal-bfs-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$42\"},{\"id\":424,\"title\":\"How to Convert Sorted List to Binary Search Tree\",\"slug\":\"how-to-convert-sorted-list-to-binary-search-tree\",\"excerpt\":\"Given a singly linked list where elements are sorted in ascending order, write a java program to convert it to a height-balanced Binary Search Tree (BST).\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2024-01-23T07:53:21.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.665Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/posts/how-to-convert-sorted-list-to-binary-search-tree.jpeg\",\"topics\":[\"java\"],\"tags\":[\"sorted-list-to-bst\",\"binary-search-tree-java\",\"linked-list-to-bst\",\"java-recursion-algorithm\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Convert a Sorted Linked List to a Balanced BST in Java\",\"metaDescription\":\"Learn how to convert a sorted singly linked list into a height-balanced Binary Search Tree in Java using a recursive slow/fast pointer approach.\",\"metaKeywords\":null},\"content\":\"$43\"},{\"id\":423,\"title\":\"Java program to Reverse Words in a String\",\"slug\":\"java-program-to-reverse-words-in-a-string\",\"excerpt\":\"Java program to Reverse Words in a String. Given an input string, reverse the string word by word. For example, given=s \\\"the sky is blue\\\", the program should return \\\"blue is sky the\\\". Leetcode problem in Java.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-01-23T07:25:24.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.627Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/posts/java-program-to-reverse-words-in-a-string.jpeg\",\"topics\":[\"java\"],\"tags\":[\"reverse-words-in-string-java\",\"leetcode-java-solution\",\"stringbuilder-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$44\"},{\"id\":413,\"title\":\"Working with Profiles in Maven\",\"slug\":\"working-with-profiles-in-maven\",\"excerpt\":\"Chapter 7- Working with Profiles in Maven, delves into managing profiles in Maven to customize the project’s build configuration for different environments or conditions.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-01-08T13:36:37.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.082Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"maven\"],\"tags\":[\"maven-profiles\",\"maven-pom-xml-profile-activation\",\"maven-build-environment-config\",\"mvn-command-line-profile\"],\"course\":\"maven-for-beginners\",\"displayOrder\":7,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$45\"},{\"id\":412,\"title\":\"Popular Maven Commands Cheat Sheet\",\"slug\":\"maven-commands-cheat-sheet\",\"excerpt\":\"Chapter 6, lists s
1ome of the most popular Maven commands with their use that every Java developer must know. Using these commands, you can easily build, test, and deploy your Java projects, and manage their dependencies and documentation.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-01-08T13:36:25.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.050Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"maven\"],\"tags\":[\"maven-commands-cheat-sheet\",\"mvn-clean-install-package\",\"maven-dependency-tree\",\"maven-archetype-generate\"],\"course\":\"maven-for-beginners\",\"displayOrder\":6,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$46\"},{\"id\":379,\"title\":\"Local, Central, and Remote Repository in Maven\",\"slug\":\"local-central-remote-maven-repository\",\"excerpt\":\"Chapter 5, Local, Central, and Remote Maven Repository, walks you through the various repository types and how they can be configured in the settings.xml file. It also covers the order maven attempts to resolve the dependency from different repositories.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-01-08T13:36:10.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.022Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"maven\"],\"tags\":[\"maven-local-repository\",\"maven-central-repository\",\"maven-remote-repository-settings-xml\",\"maven-dependency-resolution-order\"],\"course\":\"maven-for-beginners\",\"displayOrder\":5,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$47\"},{\"id\":378,\"title\":\"Dependency Management in Maven\",\"slug\":\"dependency-management-in-maven\",\"excerpt\":\"Chapter 4, Dependency Management in Maven, this chapter discusses one of the most important concepts of dependency management, direct and transitive dependencies, and discusses various maven scopes.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-01-08T13:35:57.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.988Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"maven\"],\"tags\":[\"maven-dependency-management\",\"maven-transitive-dependency\",\"maven-dependency-scope\",\"maven-pom-properties\"],\"course\":\"maven-for-beginners\",\"displayOrder\":4,\"seo\":{\"metaTitle\":\"Dependency Management in Maven: A Practical Guide\",\"metaDescription\":\"Learn how Maven manages direct and transitive dependencies, resolves version conflicts, and understand dependency scopes like compile, test, and runtime.\",\"metaKeywords\":null},\"content\":\"$48\"},{\"id\":411,\"title\":\"Creating Java Project using Maven Command Line\",\"slug\":\"creating-java-project-using-maven-commandline\",\"excerpt\":\"Chapter 3, Creating Java Project using Maven, walks you through a step-by-step process to create a Maven project using the Maven command line utility and discusses building and running Java applications. It also discusses briefly about the maven build life cycle.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-01-08T13:35:43.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.960Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"maven\"],\"tags\":[\"maven-archetype-generate\",\"maven-command-line-project\",\"maven-build-lifecycle\",\"maven-quickstart-archetype\"],\"course\":\"maven-for-beginners\",\"displayOrder\":3,\"seo\":{\"metaTitle\":\"Creating a Java Project Using Maven Command Line\",\"metaDescription\":\"Learn how to create, build, and run a Java project using the Maven command line with archetype:generate, and understand the Maven build lifecycle.\",\"metaKeywords\":null},\"content\":\"$49\"},{\"id\":410,\"title\":\"Installing and Configuring Maven\",\"slug\":\"installing-and-configuring-maven\",\"excerpt\":\"Chapter 2, Installing and Configuring Maven, discusses the prerequisites for using Maven, and guides through the Maven installation process. It also discusses briefly about the Maven ecosystem and the Apache Software License.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-01-08T13:35:28.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.913Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"maven\"],\"tags\":[\"install-maven-macos-homebrew\",\"install-maven-windows\",\"sdkman-install-java\",\"maven-environment-variables-setup\"],\"course\":\"maven-for-beginners\",\"displayOrder\":2,\"seo\":{\"metaTitle\":\"Installing and Configuring Maven on Windows and macOS\",\"metaDescription\":\"A complete guide to installing Java and Maven using SDKMan or Homebrew, configuring environment variables, and verifying your Maven installation.\",\"metaKeywords\":null},\"content\":\"$4a\"},{\"id\":409,\"title\":\"Introduction to Maven\",\"slug\":\"introduction-to-maven\",\"excerpt\":\"Chapter 1, Introduction to Maven, introduces Maven and discusses the overview of the features Maven offers and why to use the Maven build tool for your projects.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2024-01-08T13:35:19.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.871Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"maven\"],\"tags\":[\"maven-build-automation\",\"maven-pom-xml\",\"maven-gav-coordinates\",\"maven-dependency-management\"],\"course\":\"maven-for-beginners\",\"displayOrder\":1,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$4b\"},{\"id\":421,\"title\":\"Project Lombok-Is it Still Relevant in 2023?\",\"slug\":\"project-lombok-is-it-still-relevant-in-2023\",\"excerpt\":\"What is Project Lombok? Have you used this magical library? With the new Java Records feature, you might wonder if Lombok is still relevant. Let's weigh the pros and cons and see if this is suitable for you.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2023-12-03T22:07:03.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.532Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":true,\"thumbnail\":\"/media/posts/project-lombok-is-it-still-relevant-in-2023.jpeg\",\"topics\":[\"blog\"],\"tags\":[\"project-lombok-java\",\"lombok-vs-java-records\",\"lombok-annotations\",\"lombok-builder-pattern\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$4c\"},{\"id\":419,\"title\":\"7 Blogging Mistakes I Wish I Had Known Before I Started\",\"slug\":\"7-blogging-mistakes-i-wish-i-had-known-before\",\"excerpt\":\"This what I have learnt over the several years being a passive blogger. 7 Blogging Mistakes I Wish I Had Known Before.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2023-09-30T12:44:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.425Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/posts/7-blogging-mistakes-i-wish-i-had-known-before.jpeg\",\"topics\":[\"blog\"],\"tags\":[\"blogging-tips\",\"blogging-mistakes\",\"blog-seo\",\"content-consistency\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"7 Blogging Mistakes I Wish I Had Known Before Starting\",\"metaDescription\":\"A personal look at 7 common blogging mistakes around consistency, SEO, niche focus, and distribution that new bloggers should avoid learning the hard 
1way.\",\"metaKeywords\":null},\"content\":\"$4d\"},{\"id\":418,\"title\":\"Replace Embedded Tomcat Server with Jetty or Undertow in Spring Boot\",\"slug\":\"replace-tomcat-with-jetty-or-undertow-in-spring-boot\",\"excerpt\":\"This article explains how to replace the default embedded Tomcat server with Jetty or Undertow servers for your Spring Boot application.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2023-09-25T20:22:34.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.346Z\",\"videoLink\":\"1gEoiMVULt4\",\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/jetty-undertow-spring-boot\",\"featured\":false,\"thumbnail\":\"/media/articles/replace-tomcat-with-jetty.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-embedded-server\",\"jetty-vs-tomcat\",\"undertow-spring-boot\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$4e\"},{\"id\":204,\"title\":\"Implementing Singleton Design Pattern in Java\",\"slug\":\"singleton-design-pattern-in-java\",\"excerpt\":\"Master the concept of Singleton classes, Java Singleton Design Pattern, and its practical application. Explore real-world examples and ensure thread safety in your Singleton class.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2023-09-19T08:17:22.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.439Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"java-singleton-pattern\",\"thread-safe-singleton\",\"lazy-initialization-java\",\"singleton-serialization-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$4f\"},{\"id\":416,\"title\":\"Notes to Crack CLF-C01 AWS Certified Cloud Practitioner Exam on First Attempt\",\"slug\":\"crack-clfc01-aws-certified-cloud-practitioner-on-first-attempt\",\"excerpt\":\"Here are the notes that helped me to crack CLF-C01 AWS Certified Cloud Practitioner test in the first attempt.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2023-09-15T06:26:50.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.222Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/crack-clfc01-aws-certified-cloud-practitioner-in-first-attempt.jpeg\",\"topics\":[\"aws\"],\"tags\":[\"clf-c01-exam-notes\",\"aws-certified-cloud-practitioner\",\"aws-exam-preparation\",\"aws-services-overview\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Notes to Pass AWS CLF-C01 Cloud Practitioner Exam\",\"metaDescription\":\"Study notes covering AWS services, cloud computing concepts, and exam tips that helped pass the CLF-C01 AWS Certified Cloud Practitioner exam on the first try.\",\"metaKeywords\":null},\"content\":\"$50\"},{\"id\":415,\"title\":\"Introduction to Spring Boot Framework\",\"slug\":\"introduction-to-spring-boot-framework\",\"excerpt\":\"This tutorial covers the introduction to the Spring Boot framework, the key features the Spring Boot framework offers, and the Spring Boot Starter projects.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2023-09-09T15:38:03.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.162Z\",\"videoLink\":\"GX--xvYOlQ0\",\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/Getting_Started_with_Spring_Boot-A_Beginners_Guide.png\",\"topics\":[\"spring-boot\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":1,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$51\"},{\"id\":360,\"title\":\"How to Use Interceptor in Spring Boot Application\",\"slug\":\"how-to-use-interceptor-in-spring-boot\",\"excerpt\":\"Learn about Spring Boot Interceptors: Create Secure REST APIs with Real-Time Use Cases. Learn Filters vs. Interceptors, Implement \u0026 Register in Spring Boot, Define Execution Order, Set Path Patterns, and Check Basic Authentication.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2023-07-27T06:31:52.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.932Z\",\"videoLink\":\"DuMf8Nwb-9w\",\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/spring-interceptor\",\"featured\":false,\"thumbnail\":\"/media/articles/interceptors-in-spring-boot.jpg\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-handlerinterceptor\",\"spring-boot-interceptor-vs-filter\",\"webmvcconfigurer-addinterceptors\",\"spring-basic-authentication-interceptor\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":20,\"seo\":{\"metaTitle\":\"Spring Boot Interceptor Tutorial: Filters vs Interceptors\",\"metaDescription\":\"Learn how to implement HandlerInterceptor in Spring Boot, register it with WebMvcConfigurer, set path patterns, and add basic authentication checks.\",\"metaKeywords\":null},\"content\":\"$52\"},{\"id\":359,\"title\":\"How to Set Up MongoDB within a Docker Container\",\"slug\":\"how-to-set-up-mongodb-within-a-docker-container\",\"excerpt\":\"A step-by-step tutorial that c
1overs how to set up MongoDB within a Docker container effortlessly and expose the container port on your host machine.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2023-07-20T22:03:14.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.904Z\",\"videoLink\":\"VXurxAIh6BM\",\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"docker\"],\"tags\":[\"mongodb-docker-container\",\"mongodb-docker-compose\",\"docker-pull-mongo\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Set Up MongoDB in a Docker Container\",\"metaDescription\":\"A step-by-step guide to pulling the MongoDB image, running it in a Docker container, exposing the port, and starting or stopping it for local development.\",\"metaKeywords\":null},\"content\":\"$53\"},{\"id\":358,\"title\":\"How to Add Context Path to a Spring Boot Application\",\"slug\":\"add-context-path-to-a-spring-boot-application\",\"excerpt\":\"In this article, we will explore how to add a context path to your Spring Boot application.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2023-07-05T08:15:36.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.825Z\",\"videoLink\":\"7HqtH3L9erE\",\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/add-context-path-to-a-spring-boot-application.jpg\",\"topics\":[\"spring-boot\"],\"tags\":[\"servlet-context-path\",\"springboot-base-url\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Add a Context Path to a Spring Boot App\",\"metaDescription\":\"Learn how to set a custom context path in Spring Boot using server.servlet.context-path in application.properties or application.yaml.\",\"metaKeywords\":null},\"content\":\"$54\"},{\"id\":357,\"title\":\"How to Create and Customize Card Widget in Flutter\",\"slug\":\"create-and-customize-card-widget-in-flutter\",\"excerpt\":\"This article will explore how to create and customize a CardView in Flutter. In this tutorial, we will dive into the basics of creating a CardView and explore various customization options available in Flutter.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2023-07-03T20:43:38.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.746Z\",\"videoLink\":\"FfsddfvzH7E\",\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/thumbnail.002-small.jpeg\",\"topics\":[\"flutter\"],\"tags\":[\"flutter-card-widget\",\"flutter-cardview-customization\",\"flutter-fadeinimage\",\"flutter-material-design\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Create and Customize a Card Widget in Flutter\",\"metaDescription\":\"Learn how to create a CardView in Flutter and customize its shape, elevation, and content, following Material Design 3 guidelines.\",\"metaKeywords\":null},\"content\":\"$55\"},{\"id\":356,\"title\":\"How to Create and Customize the Floating Action Button in Flutter\",\"slug\":\"creating-floating-action-button-in-flutter\",\"excerpt\":\"The Floating Action Button represents the critical user action on that screen. In this article, we will discuss creating a Floating Action Button and various customization options available in flutter.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2023-06-18T18:13:40.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.689Z\",\"videoLink\":\"Kb7XLH6KYMI\",\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/Copy_of_Building_Multi-Select_GridView_in_Flutter_3.jpg\",\"topics\":[\"flutter\"],\"tags\":[\"flutter-floatingactionbutton\",\"flutter-fab-customization\",\"flutter-extended-fab\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Flutter Floating Action Button: Create and Customize\",\"metaDescription\":\"Learn how to create a Flutter FloatingActionButton and customize its color, shape, size, and icon, including extended, small, and large FAB variants.\",\"metaKeywords\":null},\"content\":\"$56\"},{\"id\":355,\"title\":\"How to Build a Multi-Select GridView Layout in Flutter - A Step-by-Step Guide\",\"slug\":\"how-to-build-a-multi-select-gridview-in-flutter\",\"excerpt\":\"This article will walk you through the process of creating a multi-select grid view in Flutter. In this example, we will create a page that displays a list of products in a two-column layout and allows users to select or deselect items.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2023-06-10T22:50:39.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.614Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/How_to_Build_a_Multi-Select_GridView_Layout_in_Flutter.jpeg\",\"topics\":[\"flutter\"],\"tags\":[\"flutter-gridview\",\"multi-select-gridview\",\"flutter-gridview-builder\",\"flutter-futurebuilder\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Build a Multi-Select GridView Layout in Flutter\",\"metaDescription\":\"Step-by-step guide to building a multi-select GridView in Flutter, fetching products from a REST API and toggling item selection with GestureDetector.\",\"metaKeywords\":null},\"content\":\"$57\"},{\"id\":354,\"title\":\"Calling HTTP Services with WebClient in Spring Boot\",\"slug\":\"what-is-webclient-how-to-use-webclient-in-java-springboot\",\"excerpt\":\"This post explains how to use WebClient to consume the REST APIs in Java SpringBoot.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2023-05-16T21:12:30.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.552Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"spring-boot\"],\"tags\":[\"webclient-spring-boot\",\"reactive-webclient-rest-api\",\"webclient-basic-authentication\",\"webclient-get-post-delete-example\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$58\"},{\"id\":352,\"title\":\"Most Popular Django Interview Questions and Answers\",\"slug\":\"most-popular-django-interview-questions-and-answers\",\"excerpt\":\"A comprehensive list of the most important and commonly asked Django interview questions and answers with detailed explanations.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2023-04-02T07:20:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.440Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"django\"],\"tags\":[\"django-interview-questions\",\"django-admin-permissions\",\"django-slug-field\",\"django-middleware\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$59\"},{\"id\":351,\"title\":\"Most Popular Git Interview Questions and Answers\",\"slug\":\"most-popular-git-interview-questions-and-answers\",\"excerpt\":\"A comprehensive list of the most important and commonly asked Git interview questions and answers with detailed explanations.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2023-04-02T07:16:32.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.412Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"git\"],\"tags\":[\"git-interview-questions\",\"git-fetch-vs-pull\",\"git-merge-conflict\",\"git-stash\",\"git-cherry-pick\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$5a\"},{\"id\":350,\"title\":\"Most Popular Android Interview Questions and Answers\",\"slug\":\"most-popular-android-interview-questions-and-answers\",\"excerpt\":\"A comprehensive list of the most important and commonly asked Android interview questions and answers with detailed explanations.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2023-04-02T06:53:28.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.359Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"interview-questions\",\"faqs\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$5b\"},{\"id\":349,\"title\":\"Difference between select_related and prefetch_related in Django?\",\"slug\":\"difference-between-select_related-and-prefetch_related\",\"excerpt\":\"This post explains how to use select_related and prefetch_related method in django to optimize the database queries when using complex relations.\",\"difficulty\":\"advance\",\"publishedDate\":\"2023-03-19T23:32:43.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.307Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":true,\"thumbnail\":\"/media/articles/Django_nhMFVrB.jpg\",\"topics\":[\"django\"],\"tags\":[\"django-select-related\",\"django-prefetch-related\",\"django-orm-optimization\",\"n-plus-one-query-problem\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"select_related vs prefetch_related in Django Explained\",\"metaDescription\":\"Understand the difference between Django's select_related and prefetch_related methods, with examples showing how each optimizes related-object queries.\",\"metaKeywords\":null},\"content\":\"$5c\"},{\"id\":348,\"title\":\"How to Handle Simple Form Submissions in Django?\",\"slug\":\"how-to-handle-simple-form-submissions-in-django\",\"excerpt\":\"This post explains how to create and handle forms in Django. It covers creating and handling standard forms and model forms.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2023-03-17T23:32:42.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.234Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/Django.jpg\",\"topics\":[\"django\"],\"tags\":[\"django-forms\",\"django-modelform\",\"django-form-validation\",\"csrf-token-django\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Handle Form Submissions in Django (Forms \u0026 ModelForms)\",\"metaDescription\":\"Learn how to create and handle standard Django forms and ModelForms, including validation, CSRF tokens, templates, and saving data to the database.\",\"metaKeywords\":null},\"content\":\"$5d\"},{\"id\":347,\"title\":\"How to Connect to Multiple Mongo Databases in SpringBoot\",\"slug\":\"how-to-connect-to-multiple-mongo-databases-in-springboot\",\"excerpt\":\"Step-by-Step Guide to the necessary configurations required for connecting Multiple MongoDB from Spring Boot application.\",\"difficulty\":\"advance\",\"publishedDate\":\"2023-03-03T12:15:07.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.198Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/spring-boot-tutorials/tree/main/multiple-mongo-databases\",\"featured\":false,\"thumbnail\":\"/media/posts/how-to-connect-to-multiple-mongo-databases-in-springboot.jpeg\",\"topics\":[\"spring-boot\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$5e\"},{\"id\":345,\"title\":\"Kafka Vs. ActiveMQ - Comparing Key Differences \u0026 Use Cases\",\"slug\":\"kafka-vs-activemq-key-differences\",\"excerpt\":\"Apache Kafka and ActiveMQ are both open-source message brokers, but they have some key differences in terms of their design, performance, and intended use cases.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2023-02-23T16:19:51.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.097Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/ActiveMQ-vs-Kafka.png\",\"topics\":[\"blog\"],\"tags\":[\"kafka-vs-activemq\",\"message-broker-comparison\",\"kafka-partitioning\",\"jms-vs-kafka\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$5f\"},{\"id\":346,\"title\":\"Performing MongoDB CRUD Operation in Spring Boot\",\"slug\":\"mongodb-crud-operation-in-spring-boot\",\"excerpt\":\"This blog explains how to use MongoDB with Java Spring Boot. We will create a simple CRUD API to interact with our Mongo database.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2023-02-02T20:22:43.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.144Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/thumbnail.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-mongodb-crud\",\"mongorepository-example\",\"spring-data-mongodb\",\"mongodb-spring-boot-tutorial\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":16,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$60\"},{\"id\":417,\"title\":\"How to Install Java for MacOS and Windows?\",\"slug\":\"how-to-install-java-for-macos-and-windows\",\"excerpt\":\"This post explains how to install Java on MacOS and Windows OS using SDKMan, Homebrew, and using the Windows installer.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-24T22:44:07.000Z\",\"updatedDate\":\"2025-09-16T23:05:40.304Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"install-java-macos\",\"sdkman-java\",\"install-openjdk-homebrew\",\"java-windows-installer\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Install Java on macOS and Windows\",\"metaDescription\":\"Step-by-step guide to installing Java on macOS using SDKMAN and Homebrew, and on Windows using the official installer, with version-check commands.\",\"metaKeywords\":null},\"content\":\"$61\"},{\"id\":382,\"title\":\"Introduction to Java\",\"slug\":\"introduction-to-java\",\"excerpt\":\"This is the beginning of the Java class. Here we will install the prerequisites for java development and get started with writing our first Java code!\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.016Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-installation-guide\",\"java-hello-world\",\"java-jdk-setup\",\"java-ide-setup\"],\"course\":\"getting-started-with-java\",\"displayOrder\":1,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$62\"},{\"id\":395,\"title\":\"Encapsulation in Java\",\"slug\":\"java-encapsulation\",\"excerpt\":\"Encapsulation is the principle of wrapping data inside an object to protect it from unwanted accesses or manipulation.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.474Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-encapsulation-example\",\"getter-setter-methods-java\",\"java-private-fields\",\"java-oop-principles\"],\"course\":\"getting-started-with-java\",\"displayOrder\":10,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$63\"},{\"id\":394,\"title\":\"Access Modifiers in Java\",\"slug\":\"java-instances-and-access-modifiers\",\"excerpt\":\"Creating a new object creates a new instance of that class. Learn about what that means, including the different access modifiers.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.445Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-access-modifiers\",\"public-private-protected-java\",\"java-class-instances\"],\"course\":\"getting-started-with-java\",\"displayOrder\":11,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$64\"},{\"id\":392,\"title\":\"Enums in Java\",\"slug\":\"java-enums\",\"excerpt\":\"Enums in Java are a group of constants that you can define. Learn how to define them, get their value, and iterate over them.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.342Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-enum-basics\",\"defining-enum-java\",\"iterating-enum-values-java\"],\"course\":\"getting-started-with-java\",\"displayOrder\":12,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$65\"},{\"id\":402,\"title\":\"Interfaces in Java\",\"slug\":\"java-interfaces\",\"excerpt\":\"Java interfaces are templates for classes to achieve abstraction and polymorphism similar to abstract classes.\",\"difficulty\":\"beginner\",\"publishedDate\
1":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.626Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-interface-example\",\"abstract-methods-java\",\"interface-vs-abstract-class-java\"],\"course\":\"getting-started-with-java\",\"displayOrder\":12,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$66\"},{\"id\":401,\"title\":\"Abstract Classes in Java\",\"slug\":\"java-abstract-classes\",\"excerpt\":\"Abstract classes are classes in Java that contain abstract methods and let children classes provide the implementation.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.589Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-abstract-classes\",\"abstract-method-java\",\"java-class-inheritance\",\"java-oop-basics\"],\"course\":\"getting-started-with-java\",\"displayOrder\":13,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$67\"},{\"id\":396,\"title\":\"Inheritance in Java\",\"slug\":\"java-inheritance\",\"excerpt\":\"Inheritance is the mechanism in which a class is able to access all of the properties and methods of a parent class.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.500Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-inheritance-example\",\"extends-keyword-java\",\"parent-child-class-java\"],\"course\":\"getting-started-with-java\",\"displayOrder\":14,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$68\"},{\"id\":397,\"title\":\"Java Polymorphism - Method Overloading, Method Overriding\",\"slug\":\"java-polymorphism\",\"excerpt\":\"Polymorphism is the concept that objects can take many forms, particularly when it is extending from a parent class.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.528Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"method-overloading-java\",\"method-overriding-java\",\"java-polymorphism-example\"],\"course\":\"getting-started-with-java\",\"displayOrder\":15,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$69\"},{\"id\":408,\"title\":\"Exceptions Handling in Java\",\"slug\":\"java-exceptions\",\"excerpt\":\"Learn how to gracefully handle and recover from critical exceptions in Java when they arise in your code.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.841Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-exception-handling\",\"try-catch-finally-java\",\"arithmeticexception-java\"],\"course\":\"getting-started-with-java\",\"displayOrder\":16,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$6a\"},{\"id\":404,\"title\":\"Working with Java Collections\",\"slug\":\"java-collections\",\"excerpt\":\"The Collections framework in Java defines numerous different data structures in which you can store, group, and retrieve objects.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.719Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-arraylist\",\"java-linkedlist\",\"java-hashmap-hashset\",\"java-collections-framework\"],\"course\":\"getting-started-with-java\",\"displayOrder\":17,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$6b\"},{\"id\":406,\"title\":\"Working With File System and IO in Java\",\"slug\":\"java-file-system-and-io\",\"excerpt\":\"Learn how to work with the file system in Java including how to open, read, write, and close a file.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.774Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-file-class\",\"read-write-file-java\",\"java-io-package\"],\"course\":\"getting-started-with-java\",\"displayOrder\":18,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$6c\"},{\"id\":405,\"title\":\"Working with Date, Time in Java\",\"slug\":\"java-date-work-with-moments-in-time\",\"excerpt\":\"Learn how to express dates and moments in time using Java's built-in date and time functions and variables.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.748Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-date-class\",\"java-time-package\",\"java-localdate-localdatetime\"],\"course\":\"getting-started-with-java\",\"displayOrder\":19,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$6d\"},{\"id\":385,\"title\":\"Perform Math Operations in Java\",\"slug\":\"java-math\",\"excerpt\":\"Learn about how to do arithmetic and work with the basic math operators and methods provided by Java.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.123Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-arithmetic-operators\",\"java-math-class\",\"java-math-methods\"],\"course\":\"getting-started-with-java\",\"displayOrder\":19,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$6e\"},{\"id\":383,\"title\":\"Overview of Java Syntax and Comments\",\"slug\":\"java-overview-syntax-and-comments\",\"excerpt\":\"Get an overview of Java in this lesson including the syntax and how to leave single and multi-line comments.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.057Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-syntax-basics\",\"java-comments\",\"hello-world-java\"],\"course\":\"getting-started-with-java\",\"displayOrder\":2,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$6f\"},{\"id\":407,\"title\":\"Regular Expressions in Java\",\"slug\":\"java-regular-expressions\",\"excerpt\":\"Learn how to use regular expressions search patterns to match text and do advanced find and replace operations.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.805Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"maven\"],\"tags\":[\"java-regex-pattern-matcher\",\"regular-expressions-java\",\"find-replace-regex-java\"],\"course\":\"getting-started-with-java\",\"displayOrder\":20,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$70\"},{\"id\":384,\"title\":\"Introduction to Java Variables and Types\",\"slug\":\"java-variables-and-types\",\"excerpt\":\"Variables and constants hold data and information. Learn how to declare, initialize, and reassign them in Java.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.089Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-primitive-data-types\",\"java-variable-declaration\",\"java-variable-naming-rules\",\"local-vs-instance-variables\"],\"course\":\"getting-started-with-java\",\"displayOrder\":3,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$71\"},{\"id\":388,\"title\":\"Working with Methods in Java\",\"slug\":\"java-methods\",\"excerpt\":\"Methods in Java allow you to reuse a code block and reduce code repetition which ensures cleaner and more modular code.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.255Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-methods-tutorial\",\"method-parameters-return-java\",\"code-reuse-java\"],\"course\":\"getting-started-with-java\",\"displayOrder\":4,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$72\"},{\"id\":391,\"title\":\"Working with Java Arrays\",\"slug\":\"java-arrays\",\"excerpt\":\"Arrays are a list of data in Java. In this lesson, learn how to create, add elements to, remove elements from, and iterate over arrays.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.307Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-array-basics\",\"java-array-sorting\",\"java-array-iteration\",\"java-arrays-tutorial\"],\"course\":\"getting-started-with-java\",\"displayOrder\":5,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$73\"},{\"id\":386,\"title\":\"Decision Making in Java using Ifs, Else Ifs, Switch\",\"slug\":\"java-ifs-else-ifs-switch\",\"excerpt\":\"Logic and conditionals are a fundamental part of Java and is how your program can make decisions on what to do.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.195Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-if-else-statement\",\"java-switch-case\",\"comparison-operators-java\"],\"course\":\"getting-started-with-java\",\"displayOrder\":6,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$74\"},{\"id\":387,\"title\":\"Loops in Java for, while and do-while\",\"slug\":\"java-loops\",\"excerpt\":\"Learn how to shorten and improve your co
1de by utilizing loops like for loops, while loops, and do while loops.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.225Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-for-loop\",\"java-while-loop\",\"do-while-loop-java\"],\"course\":\"getting-started-with-java\",\"displayOrder\":7,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$75\"},{\"id\":393,\"title\":\"Classes and Objects in Java\",\"slug\":\"java-classes-and-objects\",\"excerpt\":\"Java is an object-oriented programming language and because of this, classes and objects are a fundamental feature of the language.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.415Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-classes-and-objects\",\"java-constructors\",\"java-oop-fundamentals\",\"java-class-blueprint\"],\"course\":\"getting-started-with-java\",\"displayOrder\":8,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$76\"},{\"id\":403,\"title\":\"Working with Packages in Java\",\"slug\":\"java-packages\",\"excerpt\":\"Packages are the namespace conventions that Java follows to avoid naming collisions and organize files.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:39.692Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-package-keyword\",\"java-import-statement\",\"java-namespace-organization\"],\"course\":\"getting-started-with-java\",\"displayOrder\":9,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$77\"},{\"id\":361,\"title\":\"Python: Introduction to Python and Installation\",\"slug\":\"python-introduction-to-python\",\"excerpt\":\"This lesson will help you get started with all the tools you need to begin writing your very lines of Python! Python has an interesting and specific syntax. Learn all about it with this overview on the language.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.021Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-installation\",\"python-interpreter\",\"python-getting-started\",\"learn-python-basics\"],\"course\":\"getting-started-with-python\",\"displayOrder\":1,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$78\"},{\"id\":368,\"title\":\"Python: Working with Lists\",\"slug\":\"python-lists\",\"excerpt\":\"Learn about lists in Python which are collections that are ordered and changeable whenever you want.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.416Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-list-methods\",\"python-arrays\",\"python-data-structures\",\"python-list-operations\"],\"course\":\"getting-started-with-python\",\"displayOrder\":10,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$79\"},{\"id\":369,\"title\":\"Python: Working with Tuples\",\"slug\":\"python-tuples\",\"excerpt\":\"Learn how to use tuples in Python which are collections that are ordered, unchangeable, and immutable.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.487Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-tuple-methods\",\"python-immutable-sequence\",\"python-data-structures\"],\"course\":\"getting-started-with-python\",\"displayOrder\":11,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$7a\"},{\"id\":381,\"title\":\"Python: Exception Handling\",\"slug\":\"python-exceptions\",\"excerpt\":\"Learn how to gracefully handle and recover from exceptions and errors in Python when they arise in your code.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.964Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-exception-handling\",\"python-try-except-finally\",\"python-raise-exception\",\"python-else-block-exceptions\"],\"course\":\"getting-started-with-python\",\"displayOrder\":12,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$7b\"},{\"id\":373,\"title\":\"Python: Working with Files and Directories\",\"slug\":\"python-working-with-files-in-python\",\"excerpt\":\"Learn how to work with files in Python files and Directories including how to open, read, append, overwrite, write, and close a file.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.724Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-os-module\",\"python-file-io\",\"python-directory-operations\"],\"course\":\"getting-started-with-python\",\"displayOrder\":13,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$7c\"},{\"id\":374,\"title\":\"Python: Working with Date and Times\",\"slug\":\"python-working-with-date\",\"excerpt\":\"Learn how to express and work with dates and moments in time using Python's built-in date and time functionality.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.798Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-datetime-module\",\"python-date-time-formatting\",\"python-time-module\"],\"course\":\"getting-started-with-python\",\"displayOrder\":14,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$7d\"},{\"id\":377,\"title\":\"Python: Regular Expressions\",\"slug\":\"python-regular-expressions\",\"excerpt\":\"Learn how to use regular expressions search patterns in Python to match text and do advanced find and replace operations.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.929Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-re-module\",\"regex-python\",\"python-findall-search-split-sub\"],\"course\":\"getting-started-with-python\",\"displayOrder\":15,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$7e\"},{\"id\":363,\"title\":\"Python: Math Functions\",\"slug\":\"python-math\",\"excerpt\":\"Learn about how to do arithmetic and work with the basic math operators and functions provided by Python.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.139Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-arithmetic-operators\",\"python-math-module\",\"python-number-operations\"],\"course\":\"getting-started-with-python\",\"displayOrder\":16,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$7f\"},{\"id\":375,\"title\":\"Python: Serialising and Deserialising JSON\",\"slug\":\"python-serialising-and-deserialising-json\",\"excerpt\":\"JSON is the language of data transfer. Learn how to encode and decode JSON in Python using the json module.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.836Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-json-module\",\"json-loads-dumps\",\"python-json-parsing\"],\"course\":\"getting-started-with-python\",\"displayOrder\":17,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$80\"},{\"id\":376,\"title\":\"Python: Working with Mails\",\"slug\":\"python-working-with-mails\",\"excerpt\":\"Learn how to send text and HTML mail dynamically in Python using its built-in mail module and functions.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.887Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-smtplib\",\"send-email-python\",\"python-mime-html-email\"],\"course\":\"getting-started-with-python\",\"displayOrder\":18,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$81\"},{\"id\":362,\"title\":\"Python: Variables and Basic Data Types\",\"slug\":\"python-variables-and-types\",\"excerpt\":\"This lesson will go over variables and types, including how to declare them, initialize them, and what each kind is.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.098Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-data-types\",\"python-variable-declaration\",\"python-variable-naming-rules\"],\"course\":\"getting-started-with-python\",\"displayOrder\":2,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$82\"},{\"id\":372,\"title\":\"Python: Classes and Objects, Inheritance and Super\",\"slug\":\"python-classes-and-objects\",\"excerpt\":\"Class are blueprints to create objects which represent a collection of related properties and methods. Inheritance is an important concept of OOP. It is a process by which a class can inherit properties from another class.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.685Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-classes-and-objects\",\"python-inheritance-super\",\"python-constructor-init\",\"python-method-overriding\"],\"course\":\"getting-started-with-python\",\"displayOrder\":3,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$83\"},{\"id\":364,\"title\":\"Python: Conditional Statements Ifs, Elifs, Elses\",\"slug\":\"python-ifs-elifs-elses\",\"excerpt\":\"Logic and conditionals are a fundamental part of programming and is how your program can make decisions.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.207Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-if-elif-else\",\"python-conditional-statements\",\"python-control-flow\",\"python-decision-making\"],\"course\":\"getting-started-with-python\",\"displayOrder\":4,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$84\"},{\"id\":365,\"title\":\"Python: Working with Loops\",\"slug\":\"python-loops\",\"excerpt\":\"Learn about the two loops in Python, the for and while loop. Plus learn about the break and continue statements.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.243Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-for-loop\",\"python-while-loop\",\"python-break-continue\",\"python-iteration\"],\"course\":\"getting-started-with-python\",\"displayOrder\":5,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$85\"},{\"id\":366,\"title\":\"Python: Introduction to Functions\",\"slug\":\"python-functions\",\"excerpt\":\"Functions in Python are a great way to group together lines of code that aim to do a single task and make them reusable.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.315Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-functions-tutorial\",\"python-args-kwargs\",\"python-default-parameters\",\"python-function-recursion\"],\"course\":\"getting-started-with-python\",\"displayOrder\":6,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$86\"},{\"id\":367,\"title\":\"Python: Modules and Packages\",\"slug\":\"python-modules\",\"excerpt\":\"Modules in Python are a way to import external 
1code for you to use in your own code like third-party libraries.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.352Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-import-module\",\"python-packages\",\"python-custom-module\"],\"course\":\"getting-started-with-python\",\"displayOrder\":7,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$87\"},{\"id\":371,\"title\":\"Python: Working with Dictionaries\",\"slug\":\"python-dictionaries\",\"excerpt\":\"Learn about dictionaries in Python, which are key-value pair collections that are unordered, indexed and changable.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.605Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-dictionaries\",\"python-dict-methods\",\"python-key-value-pairs\",\"iterate-python-dictionary\"],\"course\":\"getting-started-with-python\",\"displayOrder\":8,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$88\"},{\"id\":370,\"title\":\"Python: Working with Sets\",\"slug\":\"python-sets\",\"excerpt\":\"Learn about sets in Python which are a collections of elements that are unordered and unindexed with no duplicates.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-09-17T17:01:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:38.528Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"python\"],\"tags\":[\"python-set-methods\",\"python-unique-elements\",\"python-data-structures\"],\"course\":\"getting-started-with-python\",\"displayOrder\":9,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$89\"},{\"id\":1,\"title\":\"Most Commonly Used Annotations in Spring Boot\",\"slug\":\"spring-boot-annotations\",\"excerpt\":\"Spring Boot annotations are a form of metadata that provides data about a program that is not a part of the program itself. Following are some of the most used annotations in spring boot.\",\"difficulty\":\"beginner\",\"publishedDate\":\"2022-04-17T00:24:10.000Z\",\"updatedDate\":\"2025-09-16T23:05:19.537Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":true,\"thumbnail\":\"/media/articles/1/thumbnail.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-annotations\",\"springbootapplication\",\"autowired-annotation\",\"component-vs-service-vs-repository\",\"spring-bean-annotation\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":6,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$8a\"},{\"id\":2,\"title\":\"Understanding Spring Boot Project Structure\",\"slug\":\"spring-boot-project-structure\",\"excerpt\":\"In this section we will discuss the project structure and various components of a Spring Boot project.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2022-04-16T23:31:17.000Z\",\"updatedDate\":\"2025-09-16T23:05:19.627Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/2/thumbnail.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-project-structure\",\"application-properties-file\",\"spring-boot-build-gradle\",\"spring-boot-static-content\",\"spring-boot-templates\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$8b\"},{\"id\":3,\"title\":\"Getting Started With Spring Boot\",\"slug\":\"getting-started-with-spring-boot\",\"excerpt\":\"This tutorial covers the introduction to the Spring Boot framework, the benefits and the Spring Boot starter project.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2022-04-16T09:59:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:19.713Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":true,\"thumbnail\":\"/media/articles/3/thumbnail.png\",\"topics\":[\"spring-boot\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$8c\"},{\"id\":13,\"title\":\"How to Change Spring Boot Default Port?\",\"slug\":\"how-to-change-spring-boot-default-port\",\"excerpt\":\"Spring Boot lets you run the same application more than once on a different port number. The default port used in Spring Boot is 8080.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2022-04-16T02:31:04.000Z\",\"updatedDate\":\"2025-09-16T23:05:19.802Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/4/thumbn
1ail.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-server-port\",\"application-properties-port\",\"spring-boot-random-port\",\"server-port-configuration\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Change the Spring Boot Default Port\",\"metaDescription\":\"Learn how to change the default 8080 port in Spring Boot using application.properties, application.yml, or command-line arguments, plus random ports.\",\"metaKeywords\":null},\"content\":\"$8d\"},{\"id\":14,\"title\":\"How to Consume REST API in Spring Boot Using RestTemplate?\",\"slug\":\"calling-rest-services-using-resttemplate\",\"excerpt\":\"RestTemplate is a synchronous HTTP client and is designed to consume REST API calls from Spring boot application.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2022-04-15T19:51:42.000Z\",\"updatedDate\":\"2025-09-16T23:05:19.845Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/5/thumbnail.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"resttemplate-example\",\"consume-rest-api-spring-boot\",\"resttemplate-vs-webclient\",\"spring-boot-http-client\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"RestTemplate Tutorial: Consume REST API in Spring Boot\",\"metaDescription\":\"Learn how to use RestTemplate to call REST APIs from a Spring Boot application, with setup steps and common HTTP methods explained.\",\"metaKeywords\":null},\"content\":\"$8e\"},{\"id\":15,\"title\":\"How to Execute Code on Spring Boot Application Startup?\",\"slug\":\"how-to-execute-code-on-spring-boot-application-startup\",\"excerpt\":\"Spring boot offers multiple options, for executing your co
1de during the application startup. This post covers some of the best practices recommended by the Spring developers.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2022-04-15T02:17:16.000Z\",\"updatedDate\":\"2025-09-16T23:05:19.919Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/6/thumbnail.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-postconstruct\",\"applicationrunner-commandlinerunner\",\"spring-boot-application-startup\",\"spring-boot-applicationreadyevent\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Execute Code on Spring Boot Application Startup\",\"metaDescription\":\"Compare three ways to run code at Spring Boot startup: @PostConstruct, ApplicationRunner/CommandLineRunner, and ApplicationReadyEvent, with examples.\",\"metaKeywords\":null},\"content\":\"$8f\"},{\"id\":16,\"title\":\"How to Configure Swagger2 in Spring Boot Application?\",\"slug\":\"how-to-configure-swagger2-in-spring-boot-application\",\"excerpt\":\"This tutorial explains how to configure Swagger2 and enable SwaggerUI in Spring Boot application.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2022-04-14T00:33:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.008Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/7/thumbnail.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"swagger2-spring-boot\",\"springfox-boot-starter\",\"enableswagger2\",\"swagger-ui-setup\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":22,\"seo\":{\"metaTitle\":\"How to Configure Swagger2 in a Spring Boot Application\",\"metaDescription\":\"Learn how to configure Swagger2 and enable Swagger UI in a Spring Boot app using the springfox-boot-starter dependency and @EnableSwagger2 annotation.\",\"metaKeywords\":null},\"content\":\"$90\"},{\"id\":17,\"title\":\"How Do I Clone a Specific Git Branch?\",\"slug\":\"how-do-i-clone-a-specific-git-branch\",\"excerpt\":\"The git clone is a command-line utility which is used to make a local copy of a remote repository. It accesses the repository through a remote URL.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2022-04-13T04:29:26.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.091Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/8/thumbnail.png\",\"topics\":[\"git\"],\"tags\":[\"git-clone-branch\",\"git-single-branch\",\"clone-remote-repository\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How Do I Clone a Specific Git Branch? Quick Guide\",\"metaDescription\":\"Learn how to clone a specific Git branch using the --single-branch flag, avoiding the overhead of downloading every branch in the repository.\",\"metaKeywords\":null},\"content\":\"\\nThe git clone is a command-line utility that is used to make a local copy of a remote repository. It accesses the repository through a remote URL. Usually, the original repository is located on a remote server, often from a Git service like GitHub, Bitbucket, or GitLab.\\n\\n##### To clone a repository\\n\\n```bash\\ngit clone \u003cremote_repo\u003e\\n```\\n\\nThe above command fetches all the branches and checking out one (default master). That may, for instance, mean that your repository has a 5kB documentation or wiki branch and 5GB data branch. And whenever you want to edit your front page, you may end up cloning 5GB of data.\\n\\n##### To clone a specific branch from repository\\n\\nWith Git 1.7.10 and later, add –single-branch to prevent fetching of all branches. Example:\\n\\n```bash\\ngit clone -b feature-001-branch --single-branch \u003cremote_repo\u003e\\n```\\n\"},{\"id\":18,\"title\":\"Git Diff – Inspecting and Comparing Changes in Git\",\"slug\":\"git-diff-inspecting-and-comparing-changes-in-git\",\"excerpt\":\"The git diff command helps you see, compare, and understand changes in your project before you can push your code to the server\",\"difficulty\":\"beginners\",\"publishedDate\":\"2022-04-12T01:33:31.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.133Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/9/thumbnail.png\",\"topics\":[\"git\"],\"tags\":[\"git-diff-command\",\"git-diff-staged\",\"git-compare-changes\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Git Diff: Inspecting and Comparing Changes in Git\",\"metaDescription\":\"Learn how to use the git diff command to inspect uncommitted changes, view staged changes, and compare files before pushing your co
1de.\",\"metaKeywords\":null},\"content\":\"$91\"},{\"id\":19,\"title\":\"How to Delete all Local Branches in Git?\",\"slug\":\"how-to-delete-all-local-branches-in-git\",\"excerpt\":\"Code snippet to delete all other local branches except master, develop or release/* in your local machine.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2022-04-12T01:14:26.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.212Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/10/thumbnail.png\",\"topics\":[\"git\"],\"tags\":[\"git-delete-local-branches\",\"git-branch-cleanup-script\",\"git-for-each-ref\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Delete All Local Branches in Git\",\"metaDescription\":\"A ready-to-use shell script to bulk delete local Git branches while keeping master, develop, and release/* branches intact.\",\"metaKeywords\":null},\"content\":\"\\nWhen working with a larger team and with a proper Git flow process, the number of local feature branches are grows in your local machine. Not that they do any harm to your project, but they can get quite confusing at times. This little code snippet will be able to delete all other local branches except master, develop or release/\\\\*.\\n\\nCreate a file named, `deleteLocalGitBranches.sh` and add the following code snippet.\\n\\n```bash\\n#!/bin/bash\\n# Move to master branch. Delete all other local branches except master, develop, release/* or project/*\\n\\n# Move to master branch\\ngit checkout master\\n\\n# Collect branches\\nbranches=()\\neval \\\"$(git for-each-ref --shell --format='branches+=(%(refname))' refs/heads/)\\\"\\n\\nfor branch in \\\"${branches[@]}\\\"; do\\n  old=\\\"refs/heads/\\\"\\n  branchName=${branch/$old/}\\n  if [[ \\\"$branchName\\\" != \\\"master\\\" \u0026\u0026 \\\"$branchName\\\" != \\\"develop\\\" \u0026\u0026  \\\"$branchName\\\" != \\\"release/\\\"* ]]; then\\n    git branch -D $branchName\\n  fi\\ndone\\n```\\n\\nNow run the shell script\\n\\n```bash\\n$ ./deleteLocalGitBranches.sh\\n```\\n\"},{\"id\":20,\"title\":\"Adding JSONP Support for Spring REST API\",\"slug\":\"spring-rest-and-jsonp-support\",\"excerpt\":\"In this example, we will learn how to add JSONP support to your Spring REST API. JSONP is a technique used to overcome the cross-domain restrictions imposed by browsers.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2020-01-04T08:38:54.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.311Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"spring\"],\"tags\":[\"spring-jsonp-support\",\"abstractjsonpresponsebodyadvice\",\"cross-origin-rest-api\",\"same-origin-policy\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$92\"},{\"id\":7,\"title\":\"How to Enable GZIP Compression in Spring Boot?\",\"slug\":\"enable-gzip-compression-for-spring-boot-response\",\"excerpt\":\"HTTP compression is a capability that can be built into web servers and web clients to improve transfer. This post explains how to enable gzip compression in spring boot.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2019-11-23T21:10:02.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.401Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/14/thumbnail.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"spring-boot-gzip-compression\",\"server-compression-properties\",\"http-response-compression\",\"spring-boot-performance-tuning\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Enable GZIP Compression in Spring Boot\",\"metaDescription\":\"Learn how to enable GZIP response compression in Spring Boot using application.properties, including mime types, size thresholds, and excluded agents.\",\"metaKeywords\":null},\"content\":\"$93\"},{\"id\":8,\"title\":\"Git Commands Cheat Sheet\",\"slug\":\"git-commands-cheat-sheet\",\"excerpt\":\"A list of some commonly used Git commands to get you going with Git. 1. Configuring Git To…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2018-10-24T08:47:27.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.500Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":true,\"thumbnail\":\"/media/articles/15/thumbnail.png\",\"topics\":[\"git\"],\"tags\":[\"git-commands-cheat-sheet\",\"git-branch-management\",\"git-stash-tutorial\",\"git-push-pull-basics\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Git Commands Cheat Sheet: Essential Commands List\",\"metaDescription\":\"A handy Git commands cheat sheet covering configuration, branching, diffs, stashing, and pushing/pulling changes to get you productive with Git fast.\",\"metaKeywords\":null},\"content\":\"$94\"},{\"id\":9,\"title\":\"Integrate Apache Tiles3 to Spring Boot Web MVC Application\",\"slug\":\"integrate-tiles3-to-spring-boot\",\"excerpt\":\"Spring Boot Web MVC configured to produce an executable WAR and ready for fully fledged 
1web application development. In this tutorial, we will see how to use Apache Tiles3 framework in your Spring Boot Web MVC application.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2018-10-23T04:20:25.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.590Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/16/thumbnail.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"apache-tiles3-spring-boot\",\"spring-boot-web-mvc\",\"tiles-view-resolver\",\"spring-mvc-executable-war\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$95\"},{\"id\":10,\"title\":\"Using H2 In-Memory Database in Spring Boot\",\"slug\":\"using-h2-in-memory-database-in-spring-boot\",\"excerpt\":\"In the course of this tutorial, we will see how to use the H2 in-memory database to perform the CRUD (create, read, update and delete) operation in Spring Boot.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2018-09-20T19:38:55.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.638Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/17/thumbnail.png\",\"topics\":[\"spring-boot\"],\"tags\":[\"h2-in-memory-database-spring-boot\",\"h2-console-configuration\",\"spring-boot-embedded-database\",\"h2-database-testing-java\"],\"course\":\"spring-boot-for-beginners\",\"displayOrder\":14,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$96\"},{\"id\":22,\"title\":\"Default Methods for Interfaces in Java8\",\"slug\":\"default-methods-for-interfaces-in-java8\",\"excerpt\":\"This example-driven tutorial outlines the usage of default methods for an interface in Java8. The Java Tutorials have been written for JDK 8.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2018-09-18T08:05:19.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.800Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/19/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"java8-default-methods\",\"interface-default-method-java\",\"java-diamond-problem\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Default Methods for Interfaces in Java 8 Explained\",\"metaDescription\":\"Learn how Java 8 default methods let interfaces provide method implementations, with a working example and how to resolve the diamond problem.\",\"metaKeywords\":null},\"content\":\"$97\"},{\"id\":23,\"title\":\"Create and Manage Git Branches from Command Line\",\"slug\":\"create-and-manage-git-branches\",\"excerpt\":\"List of useful git commands to help you create and manage git branches from your terminal. Be Smart!! Never go away from your terminal.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2018-09-14T17:15:10.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.847Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/20/thumbnail.png\",\"topics\":[\"git\"],\"tags\":[\"git-branch-commands\",\"git-checkout-branch\",\"git-branch-from-terminal\",\"delete-git-branch\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Create and Manage Git Branches from the Command Line\",\"metaDescription\":\"A handy list of git commands for creating, switching, pushing, and deleting branches straight from your terminal.\",\"metaKeywords\":null},\"content\":\"$98\"},{\"id\":24,\"title\":\"Java Method Chaining with Example\",\"slug\":\"method-chaining-in-java\",\"excerpt\":\"The term method chaining refers to both a design and a convention. Each method returns an object, allowing…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2018-09-11T18:17:20.000Z\",\"updatedDate\":\"2025-09-16T23:05:20.934Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/21/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"java-method-chaining\",\"fluent-interface-java\",\"builder-pattern-java\",\"setter-return-this\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$99\"},{\"id\":25,\"title\":\"Bean Mapping Frameworks to Convert DTO to Models in Java\",\"slug\":\"java-bean-mapping-frameworks\",\"excerpt\":\"This post lists the options available to convert DTO to a Model, or one Java object to another using mapping frameworks like ModelMapper, MapStruct, and Dozer.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2018-09-09T10:55:43.000Z\",\"updatedDate\":\"2025-09-16T23:05:21.024Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":true,\"thumbnail\":\"/media/articles/22/thumbnail.png\",\"topics\":[\"java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$9a\"},{\"id\":26,\"title\":\"API Gateways and Key Benefits to Consider\",\"slug\":\"api-gateways-and-key-benefits-to-consider\",\"excerpt\":\"With micro-services gaining more popularity among businesses in recent days, organizations are also finding it arduous to run such types of services. An API gateway can mitigate some of the underlying complexity for deploying services.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2018-08-07T04:02:28.000Z\",\"updatedDate\":\"2025-09-16T23:05:21.111Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/24/thumbnail.png\",\"topics\":[\"blog\"],\"tags\":[\"api-gateway\",\"microservices-architecture\",\"wso2-api-manager\",\"oauth2-api-security\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"API Gateways Explained: Key Benefits for Microservices\",\"metaDescription\":\"Understand what an API gateway does, why microservices architectures need one, and what to look for in platforms like WSO2, AWS, and Azure API Management.\",\"metaKeywords\":null},\"content\":\"$9b\"},{\"id\":11,\"title\":\"How to Generate a Valid RSS Feed for Your Laravel Application?\",\"slug\":\"how-to-generate-valid-rss-feed-for-your-laravel-application\",\"excerpt\":\"Feeds are one of the traditional and most effective ways to distribute your content to a wider audience.…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2017-05-18T17:54:52.000Z\",\"updatedDate\":\"2025-09-16T23:05:21.443Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"blog\"],\"tags\":[\"laravel\",\"rss-feed\",\"xml-feed\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Generate a Valid RSS Feed for Laravel\",\"metaDescription\":\"Learn how to add RSS and Atom feeds to a Laravel application using the roumen/feed package, with routes, config, and a FeedBuilder service.\",\"metaKeywords\":null},\"content\":\"$9c\"},{\"id\":31,\"title\":\"Convert Speech to Text in Android Application\",\"slug\":\"speech-to-text-in-android\",\"excerpt\":\"Many of the cool Android features are remained untouched by app developers. For example, Android SDK has the…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2017-01-30T13:32:23.000Z\",\"updatedDate\":\"2025-09-16T23:05:21.524Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/advance-android-tutorials/tree/master/android-texttospeech\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-speech-to-text\",\"recognizerintent\",\"voice-recognition-android\",\"offline-spee
1ch-recognition\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$9d\"},{\"id\":34,\"title\":\"How to Programmatically Get Application Version in Android?\",\"slug\":\"how-to-programmatically-get-application-version-in-android\",\"excerpt\":\"Use the following code snippet to, get Android application version from code. The PackageInfo class provides overall information…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-12-01T12:28:39.000Z\",\"updatedDate\":\"2025-09-16T23:05:21.720Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-app-version-code\",\"packageinfo-android\",\"get-versionname-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Get Application Version Programmatically in Android\",\"metaDescription\":\"Learn how to retrieve your Android app's version name and version code at runtime using the PackageInfo class, with a ready-to-use code snippet.\",\"metaKeywords\":null},\"content\":\"\\nUse the following code snippet to, get Android application version from code. The `PackageInfo` class provides overall information about the contents of a package. This corresponds to all of the information collected from `AndroidManifest.xml`.\\n\\n```java\\npublic String getAppVersion() {\\n        PackageInfo pInfo;\\n        try {\\n            pInfo = MyApp.getInstance().getPackageManager().getPackageInfo(MyApp.getInstance().getPackageName(), 0
1);\\n            return new StringBuilder(\\\"v\\\").append(pInfo.versionName)\\n                    .append(\\\" (\\\").append(pInfo.versionCode).append(\\\")\\\").toString();\\n        } catch (PackageManager.NameNotFoundException e) {\\n            e.printStackTrace();\\n        }\\n        return \\\"1.0.0\\\";\\n    }\\n```\\n\"},{\"id\":36,\"title\":\"How to Use Custom Chrome Tab in Android\",\"slug\":\"how-to-use-custom-chrome-tab-in-android\",\"excerpt\":\"Chrome Custom Tabs gives apps more control over their web experience and make transitions between native and web…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-10-24T08:45:18.000Z\",\"updatedDate\":\"2025-09-16T23:05:21.822Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$9e\"},{\"id\":50,\"title\":\"Java String Examples\",\"slug\":\"java-string-examples\",\"excerpt\":\"1. String Length and Trim Code snippet explains the usage of String class length and trim() method. The…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-09-11T18:31:05.000Z\",\"updatedDate\":\"2025-09-16T23:05:22.334Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/71/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"java-string-reverse\",\"string-equals-vs-equalsignorecase\",\"string-concatenation-java\",\"reverse-string-recursion\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$9f\"},{\"id\":53,\"title\":\"How to Disable Past Dates in Custom Calendar View Android\",\"slug\":\"disable-past-dates-in-custom-calendar-view-android\",\"excerpt\":\"Since then many people are asking questions like how to use Decorators and how to disable some dates in CustomCalendarView. In this post we will disable all the dates that are past.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-08-30T05:20:25.000Z\",\"updatedDate\":\"2025-09-16T23:05:22.458Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$a0\"},{\"id\":56,\"title\":\"How to Use Firebase Crash Reporting in Android\",\"slug\":\"how-to-use-firebase-crash-reporting-in-android\",\"excerpt\":\"Firebase crash reporting automatically logs the crashes and custom events. In this tutorial we will see how use Firebase Crash Reporting in Android.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-08-15T20:20:36.000Z\",\"updatedDate\":\"2025-09-16T23:05:22.625Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"firebase-crash-reporting-android\",\"firebasecrash-report\",\"firebase-android-setup\",\"google-services-json\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Use Firebase Crash Reporting in Android\",\"metaDescription\":\"Learn how to configure Firebase Crash Reporting in Android, add the SDK to your Gradle files, and log custom crashes and events with FirebaseCrash.\",\"metaKeywords\":null},\"content\":\"$a1\"},{\"id\":57,\"title\":\"Turn on and off Wi-Fi using Android API\",\"slug\":\"code-snippet-turn-on-and-off-wi-fi-using-android-api\",\"excerpt\":\"Use the following code snippets to turn on and off wifi on Android devices. Switch toggle = (Switch)…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-08-15T14:55:29.000Z\",\"updatedDate\":\"2025-09-16T23:05:22.687Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"code-snippet\",\"how-tos\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"\\nUse the following code snippets to turn on and off wifi on Android devices.\\n\\n```java\\npublic void toggleWiFi(boolean status) {\\n    WifiManager wifiManager = (WifiManager) this.get
1SystemService(Context.WIFI_SERVICE);\\n    if (status == true \u0026amp;\u0026amp; !wifiManager.isWifiEnabled()) {\\n        wifiManager.setWifiEnabled(true);\\n    } else if (status == false \u0026amp;\u0026amp; wifiManager.isWifiEnabled()) {\\n        wifiManager.setWifiEnabled(false);\\n    }\\n}\\n```\\n\\nFor changing wifi state, you need the following permissions in your manifest file.\\n\\n```xml\\n\u003cuses-permission android:name=\\\"android.permission.ACCESS_WIFI_STATE\\\"\u003e\u003c/uses-permission\u003e\\n\u003cuses-permission android:name=\\\"android.permission.CHANGE_WIFI_STATE\\\"\u003e\u003c/uses-permission\u003e\\n```\\n\"},{\"id\":58,\"title\":\"How to Add Click Listener to Android Switch\",\"slug\":\"how-to-add-click-listener-to-android-switch\",\"excerpt\":\"A Switch is a two-state toggle switch widget that can select between two options. Add Switch control to…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-08-15T14:48:59.000Z\",\"updatedDate\":\"2025-09-16T23:05:22.725Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-switch-widget\",\"oncheckedchangelistener\",\"android-compoundbutton\",\"toggle-switch-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Add a Click Listener to Android Switch Widget\",\"metaDescription\":\"Learn how to add a Switch widget to your Android layout and handle toggle events using setOnCheckedChangeListener with a working code example.\",\"metaKeywords\":null},\"content\":\"$a2\"},{\"id\":67,\"title\":\"Quick Settings Tile API Example in Android N\",\"slug\":\"quick-settings-tile-api-example-in-android-n\",\"excerpt\":\"Quick settings are undoubtedly one of the most popular features in Android devices. It provides a convenient way…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-08-10T09:33:27.000Z\",\"updatedDate\":\"2025-09-16T23:05:23.142Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/android-ui-tutorials/tree/master/android-quick-settings-tile-demo\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-quick-settings-tile\",\"tileservice-android\",\"android-n-features\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$a3\"},{\"id\":71,\"title\":\"How to Customize YouTubePlayer Controls in Android\",\"slug\":\"how-to-customize-youtubeplayer-controls-in-android\",\"excerpt\":\"The Android YouTubePlayer allows you to customize the playback control by setting one of the style defined in YouTubePlayer.PlayerStyle enum. You can apply style to YouTubePlayer by calling setPlayerStyle method.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-07-09T14:01:30.000Z\",\"updatedDate\":\"2025-09-16T23:05:23.350Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/android-ui-tutorials/tree/master/android-youtube-playerview-demo\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"youtubeplayer-custom-controls\",\"android-youtube-player-api\",\"youtubeplayerview-android\",\"android-video-playback-controls\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Customize YouTubePlayer Controls in Android\",\"metaDescription\":\"Learn how to build custom play, pause, and seek controls for the Android YouTubePlayer using CHROMELESS style and YouTubePlayerView.\",\"metaKeywords\":null},\"content\":\"$a4\"},{\"id\":72,\"title\":\"How to Send an Email with Attachment in Android\",\"slug\":\"how-to-send-an-email-with-attachment-in-android\",\"excerpt\":\"The following code snippet shows to send an email with image attachment in Android using Intent method.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-07-06T06:43:33.000Z\",\"updatedDate\":\"2025-09-16T23:05:23.463Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-send-email-intent\",\"email-attachment-android\",\"android-intent-action-send\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Send an Email with Attachment in Android\",\"metaDescription\":\"Learn how to send an email with an image attachment in Android using an Intent, with a simple sendEmail() code snippet you can drop into your app.\",\"metaKeywords\":null},\"content\":\"\\nThe following code snippet shows to send an email with image attachment in Android using the Intent method.\\n\\n```java\\npublic static void sendEmail(Context context, String subject, String message, String imagePath) {\\n    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);\\n    emailIntent.setType(\\\"plain/text\\\");\\n    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);\\n    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);\\n\\n    if (imagePath != null \u0026\u0026 imagePath.length() \u003e 0) {\\n        File file = urlToFile(imagePath);\\n        if (file != null \u0026\u0026 file.getAbsolutePath() != null)\\n            emailIntent.putExtra(Intent.EXTRA_STREAM, file.getAbsolutePath());\\n    }\\n\\n    context.startActivity(emailIntent);\\n}\\n```\\n\"},{\"id\":74,\"title\":\"Convert DP Unit to Equivalent Pixels in Android\",\"slug\":\"how-to-convert-dp-unit-to-equivalent-pixels-in-android\",\"excerpt\":\"The following code snippet shows how to converts dp unit to equivalent pixels, depending on device density. It returns a float value to represent px equivalent to dp depen
1ding on device density.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-07-06T06:32:16.000Z\",\"updatedDate\":\"2025-09-16T23:05:23.604Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"\\nThe following code snippet shows how to converts DP unit to equivalent pixels, depending on device density. It returns a float value to represent px equivalent to dp depending on device density.\\n\\n```java\\npublic static float convertDpToPixel(float dp, Context context){\\n    Resources resources = context.getResources();\\n    DisplayMetrics metrics = resources.getDisplayMetrics();\\n    float px = dp * (metrics.densityDpi / 160f);\\n    return px;\\n}\\n```\\n\"},{\"id\":76,\"title\":\"How to Generate Unique File Name When Saving a File in Java\",\"slug\":\"how-to-generate-unique-file-name-when-saving-a-file-in-java\",\"excerpt\":\"The following code snippet shows how to get unique file name when saving file in java. It first checks if already a file exist with the specified name, then it appends a number to end.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-07-06T05:45:37.000Z\",\"updatedDate\":\"2025-09-16T23:05:23.723Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/103/thumbnail.png\",\"topics\":[\"java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$a5\"},{\"id\":78,\"title\":\"How to Add an Event to Android Calendar\",\"slug\":\"how-to-add-an-event-to-android-calendar\",\"excerpt\":\"The following code snippet shows how to add event in Android calendar using intent method.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-07-04T12:39:52.000Z\",\"updatedDate\":\"2025-09-16T23:05:23.813Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-calendar-intent\",\"calendarcontract-events\",\"add-calendar-event-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Add an Event to Android Calendar Using Intent\",\"metaDescription\":\"Learn how to add an event to the Android calendar with a simple Intent.ACTION_INSERT code snippet, including setting event title and description.\",\"metaKeywords\":null},\"content\":\"\\nThe following code snippet shows how to add event in Android calendar using intent method.\\n\\n```java\\nIntent intent = new Intent(Intent.ACTION_INSERT);\\nintent.setData(CalendarContract.Events.CONTENT_URI)\\nintent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, eventDate.getTimeInMillis())\\nintent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, eventDate.getTimeInMillis() + 60 * 60 * 1000)\\nintent.putExtra(CalendarContract.Events.TITLE, title)\\nintent.putExtra(CalendarContract.Events.DESCRIPTION, description)\\nintent.putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);\\ncontext.startActivity(intent);\\n\\nToast.makeText(context, \\\"Event added to calendar, Toast.LENGTH_SHORT).show();\\n```\\n\"},{\"id\":79,\"title\":\"How to Determine Android Screen Size Width and Height\",\"slug\":\"how-to-determine-android-screen-size-width-and-height\",\"excerpt\":\"The following code snippet shows how to determine the screen size dimensions in width and height of the Android device your application is running on.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-07-04T12:24:42.000Z\",\"updatedDate\":\"2025-09-16T23:05:23.846Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-screen-size\",\"android-display-getsize\",\"android-screen-width-height\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Determine Android Screen Size (Width and Height)\",\"metaDescription\":\"A quick code snippet to get the screen width and height of an Android device at runtime using WindowManager and Display.getSize().\",\"metaKeywords\":null},\"content\":\"\\nThe following code snippet shows how to determine the screen size dimensions in width and height of the Android device your application is running on.\\n\\n```java\\nDisplay display = mActivity.getWindowManager().getDefaultDisplay();\\nPoint size = new Point();\\ndisplay.getSize(size);\\nint width = size.x;\\nint height = size.y;\\n\\nLog.e(\\\"Width : \\\" + width);\\nLog.e(\\\"Height : \\\" + height);\\n```\\n\"},{\"id\":80,\"title\":\"How to Trust All Certificates for HttpURLConnection in Android\",\"slug\":\"how-to-trust-all-certificates-for-httpurlconnection-in-android\",\"excerpt\":\"The following code snippet will help you to disables the SSL certificate checking for new instances of HttpsURLConnection in Android. You can use this code for testing purpose only and remove when moving to production.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-07-04T11:54:52.000Z\",\"updatedDate\":\"2025-09-16T23:05:23.930Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"httpsurlconnection-trust-all-certificates\",\"android-ssl-certificate-bypass\",\"x509trustmanager-android\",\"disable-ssl-verification-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Trust All Certificates for HttpsURLConnection in Android\",\"metaDescription\":\"See how to disable SSL certificate checking for HttpsURLConnection in Android using a custom X509TrustManager, intended for testing environments only.\",\"metaKeywords\":null},\"content\":\"$a6\"},{\"id\":87,\"title\":\"YouTube Android Player API and YouTubePlayerView Example\",\"slug\":\"youtube-android-player-api-example\",\"excerpt\":\"The YouTube Player API for Android provides a ready to use a fragment and an embedded view to play YouTube videos. The API provides methods to customize and control the video playback. You can play, pause, or seek video to specific play time\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-07-01T22:43:30.000Z\",\"updatedDate\":\"2025-09-16T23:05:24.222Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/android-ui-tutorials/tree/master/android-youtube-playerview-demo\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$a7\"},{\"id\":88,\"title\":\"How to Enable Deep Links for App Content in Android\",\"slug\":\"how-to-enable-deep-links-for-app-content-in-android\",\"excerpt\":\"Enable deep links for App content in Android, you need to fist add intent filters for the relevant activities in your application manifest. The intent filters allow deep linking to the content in any of your activities.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-06-13T18:58:48.000Z\",\"updatedDate\":\"2025-09-16T23:05:24.254Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$a8\"},{\"id\":90,\"title\":\"How to Programmatically Take a Screenshot in Android?\",\"slug\":\"how-to-programmatically-take-a-screenshot-in-android\",\"excerpt\":\"The following code snippet will help you to take a screenshot programmatically in Android. First you need to add the write file permission to save the captured screenshot.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-06-13T18:24
1:35.000Z\",\"updatedDate\":\"2025-09-16T23:05:24.327Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-programmatic-screenshot\",\"android-bitmap-capture\",\"android-drawing-cache\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Programmatically Take a Screenshot in Android\",\"metaDescription\":\"Learn how to capture a screenshot programmatically in Android by drawing the activity view to a bitmap and saving it as a JPEG file.\",\"metaKeywords\":null},\"content\":\"$a9\"},{\"id\":91,\"title\":\"How to Save Android Application’s  Activity State\",\"slug\":\"how-to-save-android-applications-activity-state\",\"excerpt\":\"The Activity class provides two methods onSaveInstanceState() and onRestoreInstanceState(), for saving and restoring activity state. The onSaveInstanceState( )…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-06-13T18:06:12.000Z\",\"updatedDate\":\"2025-09-16T23:05:24.405Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-onsaveinstancestate\",\"android-activity-state\",\"android-bundle-save-restore\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Save Android Activity State (onSaveInstanceState)\",\"metaDescription\":\"Learn how to save and restore an Android Activity's UI state using onSaveInstanceState() and onRestoreInstanceState() with a Bundle example.\",\"metaKeywords\":null},\"content\":\"$aa\"},{\"id\":102,\"title\":\"Restrict EditText Min and Max Value Input Range in Android\",\"slug\":\"restrict-edittext-min-and-max-value-input-range-using-android-inputfilter\",\"excerpt\":\"Using Android LengthFilter, AllCaps and CustomInputFilter example. This tutorial explains how to restrict min max input range using custom InputFilter.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2016-06-08T20:38:54.000Z\",\"updatedDate\":\"2025-09-16T23:05:24.921Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-inputfilter\",\"edittext-input-validation\",\"android-lengthfilter\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$ab\"},{\"id\":105,\"title\":\"Upload Bitmap Image Using HTTP Multipart in Xamarin Android\",\"slug\":\"upload-bitmap-image-to-server-using-http-multipart-in-xamarin-android\",\"excerpt\":\"In this post, we will take a look at what are the API’s Xamarin Android facilitates to support multi part upload. For the sake of simplicity, in this example we will upload an bitmap image to server.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-12-01T11:25:39.000Z\",\"updatedDate\":\"2025-09-16T23:05:25.110Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$ac\"},{\"id\":110,\"title\":\"Configure POJOs with Java Collection Attributes in Spring\",\"slug\":\"configure-pojos-with-java-collection-attributes-in-spring\",\"excerpt\":\"In Spring java collection types can be configured using set of built-in XML tags such as , , and . In this example, we will discuss how to configure the the List collection.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-17T11:13:30.000Z\",\"updatedDate\":\"2025-09-16T23:05:25.291Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/142/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-xml-bean-configuration\",\"spring-ioc-collection-list\",\"spring-pojo-list-property\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Configure POJOs with Java Collection Attributes in Spring\",\"metaDescription\":\"Learn how to configure Spring POJOs that contain Java collection attributes like List using XML-based bean configuration, with a working example.\",\"metaKeywords\":null},\"content\":\"$ad\"},{\"id\":111,\"title\":\"Query Database Using JdbcTemplate in Spring\",\"slug\":\"query-database-using-jdbctemplate-in-spring\",\"excerpt\":\"In this tutorial, we will focus on how to query data database. A JDBC query operation involves the following tasks.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-17T11:04:22.000Z\",\"updatedDate\":\"2025-09-16T23:05:25.335Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/143/thumbn
1ail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-jdbctemplate\",\"rowcallbackhandler-rowmapper\",\"jdbc-query-database\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$ae\"},{\"id\":112,\"title\":\"Batch Update Operation Using Spring JdbcTemplate\",\"slug\":\"batch-update-operation-using-spring-jdbctemplate\",\"excerpt\":\"In our previous example, we have discussed how to use JdbcTemplate to access the MySQL database and perform insert and delete operation. In this tutorial, we will focus on how to insert list of cars into database.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-15T22:17:45.000Z\",\"updatedDate\":\"2025-09-16T23:05:25.412Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/144/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-jdbctemplate\",\"batchupdate-method\",\"batchpreparedstatementsetter\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Batch Update Using Spring JdbcTemplate: batchUpdate()\",\"metaDescription\":\"Learn how to perform efficient batch insert operations in Spring using JdbcTemplate's batchUpdate() method and BatchPreparedStatementSetter, with example code.\",\"metaKeywords\":null},\"content\":\"$af\"},{\"id\":113,\"title\":\"Spring Constructor Injection Using constructor-arg\",\"slug\":\"spring-constructor-injection-using-constructor-arg\",\"excerpt\":\"In our previous example, we have seen how to create POJO Instances from the IoC Container. In this tutorial, we will examine how to create a POJO instance or bean in the Spring IoC container by invoking its constructor.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-15T06:14:47.000Z\",\"updatedDate\":\"2025-09-16T23:05:25.496Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/145/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-constructor-injection\",\"constructor-arg-xml\",\"spring-ioc-container\",\"spring-bean-configuration\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$b0\"},{\"id\":115,\"title\":\"Java Spring JDBC Using JdbcTemplate Example\",\"slug\":\"java-spring-jdbc-using-jdbctemplate-example\",\"excerpt\":\"There are various data access technologies to perform persistence operations in Java enterprise applications. Spring JdbcTemplate is a class that takes care of all the boilerplate code required for creating a database connection and closing the resources.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-12T21:51:54.000Z\",\"updatedDate\":\"2025-09-16T23:05:25.613Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/147/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-jdbctemplate\",\"spring-datasource-configuration\",\"jdbc-crud-example\",\"java-dao-pattern\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$b1\"},{\"id\":116,\"title\":\"Introduction to Spring JDBC\",\"slug\":\"introduction-to-spring-jdbc\",\"excerpt\":\"There are various data access technologies to perform persistence operations in Java enterprise applications. JDBC is among the most popular one. Spring provides data access operations performed with JDBC..\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-12T21:36:17.000Z\",\"updatedDate\":\"2025-09-16T23:05:25.699Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/148/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-jdbc-template\",\"spring-jdbc-datasource\",\"jdbctemplate-tutorial\",\"spring-data-access-jdbc\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$b2\"},{\"id\":118,\"title\":\"OpenSource Custom ListView ScrollView Libraries in Android\",\"slug\":\"opensource-custom-listview-scrollview-implementation-libraries-in-android\",\"excerpt\":\"# Custom ListView ScrollView Implementation – Android 1 Pinned section listview Easy to use ListView with pinned sections…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-08T20:44:04.000Z\",\"updatedDate\":\"2025-09-16T23:05:25.774Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$b3\"},{\"id\":119,\"title\":\"How to Customize POJO Initialization and Destruction in Spring Core\",\"slug\":\"how-to-customize-pojo-initialization-and-destruction-in-spring-core\",\"excerpt\":\"Spring POJOs are initialized and managed by Spring IoC Container. Sometimes, you may 
1need perform some initialization code before a POJO is used.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-07T22:17:33.000Z\",\"updatedDate\":\"2025-09-16T23:05:25.894Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/153/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-bean-lifecycle\",\"init-method-destroy-method\",\"spring-ioc-container\",\"spring-pojo-initialization\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Customize POJO Initialization and Destruction in Spring\",\"metaDescription\":\"Learn how Spring manages POJO lifecycle callbacks using init-method and destroy-method attributes to run custom startup and shutdown logic.\",\"metaKeywords\":null},\"content\":\"$b4\"},{\"id\":120,\"title\":\"Spring Internationalization or i18n Locales Using Properties Files\",\"slug\":\"spring-internationalization-or-i18n-locales-using-properties-files\",\"excerpt\":\"The string message for different locale are stored in separate properties files. These properties files are also called as resource bundles. Spring application context can resolve text messages for target locales by keys.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-07T21:46:43.000Z\",\"updatedDate\":\"2025-09-16T23:05:25.939Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/154/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-internationalization\",\"spring-i18n-messagesource\",\"resourcebundlemessagesource\",\"locale-properties-files\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$b5\"},{\"id\":122,\"title\":\"How to Initialize Bean by Reading Data from .properties File in Spring\",\"slug\":\"how-to-initialize-bean-by-reading-data-from-properties-file-in-spring\",\"excerpt\":\"In our previous tutorial, we have seen how to create and manage POJOs With Spring IoC container using XML configuration and @Configuration and @Bean Annotations. In this example, we will examine how to initialize spring POJO by reading data from external resources such as property file.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-06T06:13:26.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.068Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/156/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-properties-file\",\"property-sources-placeholder-configurer\",\"spring-bean-configuration\",\"spring-ioc-container\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Initialize Spring Bean from a Properties File\",\"metaDescription\":\"Learn how to use Spring's PropertySourcesPlaceholderConfigurer to initialize a bean's properties by reading values from an external .properties file.\",\"metaKeywords\":null},\"content\":\"$b6\"},{\"id\":123,\"title\":\"Spring Bean Scope Using XML Configuration and @Scope Annotation\",\"slug\":\"how-to-set-bean-scope-using-xml-configuration-and-scope-annotation\",\"excerpt\":\"When you declare a POJO instance or bean in the configuration file, you are actually defining a template for bean creation, not an actual bean instance.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-02T19:03:24.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.131Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/157/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-bean-scope\",\"spring-scope-annotation\",\"singleton-vs-prototype-bean\",\"spring-xml-configuration\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Spring Bean Scope: XML Config and @Scope Annotation\",\"metaDescription\":\"Understand Spring bean scopes like singleton, prototype, request, and session, and learn to set them using XML configuration or the @Scope annotation.\",\"metaKeywords\":null},\"content\":\"$b7\"},{\"id\":124,\"title\":\"Spring Bean Configuration using @Configuration and @Bean Annotations\",\"slug\":\"bean-configuration-using-configuration-and-bean-annotations\",\"excerpt\":\"In this tutorial we will examine how to configuring the Spring POJO for the Spring IoC container using @Configuration and @Bean annotation.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-10-02T06:30:48.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.209Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/158/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-configuration-annotation\",\"spring-bean-annotation\",\"annotationconfigapplicationcontext\",\"java-based-spring-config\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Spring Bean Configuration with @Configuration and @Bean\",\"metaDescription\":\"Learn how to configure Spring beans in Java using @Configuration and @Bean annotations instead of XML, and load them with AnnotationConfigAp
1plicationContext.\",\"metaKeywords\":null},\"content\":\"$b8\"},{\"id\":125,\"title\":\"Create and Manage POJOs with Spring IoC Container\",\"slug\":\"create-and-manage-pojos-with-spring-ioc-container\",\"excerpt\":\"In this tutorial, we will examine how to design a POJO class and configure POJO instance values for the Spring IoC container in an XML file. Next, instantiate the Spring IoC container to access to the POJO instance values defined in an XML file.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-09-29T22:30:35.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.299Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/159/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-ioc-container\",\"spring-xml-bean-configuration\",\"spring-constructor-injection\",\"spring-setter-injection\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Create and Manage POJOs with Spring IoC Container\",\"metaDescription\":\"Learn how to design a POJO class and configure its values using Spring's IoC container in an XML file, with a complete working example.\",\"metaKeywords\":null},\"content\":\"$b9\"},{\"id\":126,\"title\":\"How Spring Controller Request Mapping works in Spring MVC\",\"slug\":\"how-spring-controller-request-mapping-works-in-spring-mvc\",\"excerpt\":\"In this tutorial, we will discuss how Spring controller request mapping works in Spring MVC and different type of request mapping mechanisms.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2015-09-24T10:13:41.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.387Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/161/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-requestmapping\",\"spring-mvc-controller\",\"dispatcher-servlet\",\"spring-controller-mapping\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Spring Controller Request Mapping in Spring MVC Explained\",\"metaDescription\":\"Learn how @RequestMapping works in Spring MVC, covering handler-level, controller-class-level, and HTTP method-based request mapping with examples.\",\"metaKeywords\":null},\"content\":\"$ba\"},{\"id\":45,\"title\":\"Creating Spring MVC HelloWorld Using Maven in Eclipse Tomcat\",\"slug\":\"creating-spring-mvc-helloworld-using-maven-in-eclipse-tomcat\",\"excerpt\":\"In the course of this tutorial, we will learn how to create your first Spring MVC application using eclipse IDE using Maven build type.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-09-24T08:30:03.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.441Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/162/thumbnail.png\",\"topics\":[\"spring\"],\"tags\":[\"spring-mvc-helloworld\",\"how-tos\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$bb\"},{\"id\":46,\"title\":\"Introduction to Spring MVC and Dispatcher Servlet\",\"slug\":\"introduction-to-spring-mvc-and-dispatcher-servlet\",\"excerpt\":\"Spring is a model-view-controller (MVC) framework for Java web application. Spring is build on the powerful Spring IoC container and makes extensive use of the container features to simplify the project configuration.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-09-22T17:06:01.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.520Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/163/thumbnail.png\",\"topics\":[\"spring\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$bc\"},{\"id\":47,\"title\":\"How to Create Bitmap Blur Effect in Android Using RenderScript\",\"slug\":\"how-to-create-bitmap-blur-effect-in-android-using-renderscript\",\"excerpt\":\"Android RenderScript framework API can be used for performing computationally intensive tasks at high performance. In this tutorial we will take a look into how to create Bitmap blur effect in using Android RenderScript.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-09-21T17:13:03.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.598Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-renderscript\",\"bitmap-blur-effect\",\"scriptintrinsicblur\",\"android-image-processing\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Bitmap Blur Effect in Android Using RenderScript\",\"metaDescription\":\"Learn how to create a Gaussian blur effect on a Bitmap in Android using RenderScript's ScriptIntrinsicBlur, with Gradle setup and full code examples.\",\"metaKeywords\":null},\"content\":\"$bd\"},{\"id\":129,\"title\":\"Custom Calendar View Library in Android\",\"slug\":\"custom-calendar-view-l
1ibrary-in-android\",\"excerpt\":\"The CustomCalendarView provides an easy and customizable option to create a Calendar. It displays the days of a month in a grid layout and allows navigating between months.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-09-15T00:31:06.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.787Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":true,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-custom-calendar-view\",\"android-calendarview-library\",\"android-calendar-decorators\",\"jitpack-android-library\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Custom Calendar View Library for Android\",\"metaDescription\":\"Learn how to add and customize the CustomCalendarView library in Android, including day decorators, custom typefaces, and month navigation.\",\"metaKeywords\":null},\"content\":\"$be\"},{\"id\":130,\"title\":\"How to Customize Android Keyboard Actions and Other Hacks\",\"slug\":\"android-keyboard-hacks-hide-keyboard-and-customize-actions\",\"excerpt\":\"This post explains the various code hacks used for controlling the appearance and behavior of the Android keyboard. Hacks include hide Keyboard, customize keyboard actions and setting input type.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-08-04T20:29:30.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.821Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"hide-soft-keyboard\",\"android-inputtype\",\"oneditoractionlistener\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Keyboard Hacks: Hide and Customize Actions\",\"metaDescription\":\"Learn how to control Android soft keyboard behavior, including setting input types, hiding the keyboard programmatically, and customizing IME action buttons.\",\"metaKeywords\":null},\"content\":\"$bf\"},{\"id\":132,\"title\":\"How to Create Custom Layout in Android by Extending ViewGroup Class\",\"slug\":\"how-to-create-custom-layout-in-android-by-extending-viewgroup-class\",\"excerpt\":\"A ViewGroup in Android a special view that can contain other Views. A ViewGroup can contain one or multiple child.This post will help you to deal with creating a custom Layout manager class TagLayout that will be used to display the list of tags as shown in the following screenshot.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-08-03T15:40:57.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.888Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-custom-viewgroup\",\"android-onmeasure-onlayout\",\"custom-layout-manager-android\",\"android-taglayout\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Custom Layout in Android by Extending ViewGroup\",\"metaDescription\":\"Learn how to build a custom Android layout manager by extending ViewGroup, overriding onMeasure() and onLayout() to create a tag-style TagLayout.\",\"metaKeywords\":null},\"content\":\"$c0\"},{\"id\":133,\"title\":\"How to Monitor TextView Changes in Android\",\"slug\":\"how-to-monitor-textview-changes-in-android\",\"excerpt\":\"In this tutorial we will see how to monitor the text changes in Android TextView or EditText. Some form based applications needs to continuously monitor for the text changes to perform the front end form validations. This can be achieved by implementing the android.text.TextWatcher interface.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-07-31T09:14:36.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.919Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-textwatcher\",\"edittext-text-change-listener\",\"android-character-counter\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Monitor TextView Changes in Android\",\"metaDescription\":\"Learn how to use Android's TextWatcher interface to monitor text changes in a TextView or EditText, with a live character counter example.\",\"metaKeywords\":null},\"content\":\"$c1\"},{\"id\":134,\"title\":\"How to create a background service in Android\",\"slug\":\"how-to-create-a-background-service-in-android\",\"excerpt\":\"To create a background service, first you need to add the service into your manifest file. Then, create a class that extends service. Finally, in your activity start the service.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-07-30T22:14:07.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.954Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-background-service\",\"android-service-lifecycle\",\"startservice-stopservice\",\"android-ibinder\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Create a Backgroun
1d Service in Android\",\"metaDescription\":\"Learn how to create an Android background service: declare it in the manifest, extend the Service class, and start or stop it from an Activity.\",\"metaKeywords\":null},\"content\":\"\\nTo create a background service, first you need to add the service into your manifest file. Then, create a class that extends service. Finally, in your activity start the service.\\n\\n1. First add the following service declaration in your application manifest file.\\n\\n```xml\\n\u003cservice android:enabled=\\\"true\\\" android:name=\\\".MyService\\\"\u003e\\n\u003c/service\u003e\\n```\\n\\n2. Create a new class MyService that extends Service class.\\n\\n```java\\npublic class MyService extends Service {\\n  @Override\\n  public void onCreate() {\\n  }\\n\\n  @Override\\n  public void onStart(Intent intent, int startId) {\\n    //do something\\n  }\\n\\n  @Override\\n  public IBinder onBind(Intent intent) {\\n    return null;\\n  }\\n}\\n```\\n\\n3. To start the service and stop the service:\\n\\n```java\\npublic class MyActivity extends Activity {\\n  @Override\\n  public void onCreate() {\\n    …\\n    startService(new Intent(this, MyService.class);\\n  }\\n\\n  @Override\\n  public void onStop() {\\n    …\\n    stopService(new Intent(this, MyService.class));\\n  }\\n}\\n```\\n\"},{\"id\":135,\"title\":\"How to access accelerometer in Android\",\"slug\":\"how-to-access-accelerometer-in-android\",\"excerpt\":\"The following code snippet will help you with the basic understanding of how to set up the Android accelerometer and get values from it. To use the accelerometer (or any sensor in general) your class should implement the SensorEventListener interface.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-07-30T22:07:29.000Z\",\"updatedDate\":\"2025-09-16T23:05:26.985Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-accelerometer\",\"sensoreventlistener\",\"android-sensormanager\",\"android-sensors\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Access the Accelerometer in Android\",\"metaDescription\":\"Learn how to set up the Android accelerometer sensor using SensorManager and SensorEventListener to read live x, y, and z axis values in your app.\",\"metaKeywords\":null},\"content\":\"\\nThe following code snippet will help you with the basic understanding of how to set up the Android accelerometer and get values from it.\\n\\nTo use the accelerometer (or any sensor in general) your class should implement the `SensorEventListener` interface, or you could do anonymous inner classes for them. To access the accelerometer you will need to get the `SystemManager` from the system and get a sensors list from that.\\n\\n```java\\nmyManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);\\n// this will return a list of Sensor\\nsensors = myManager.getSensorList(Sensor.TYPE_ACCELEROMETER);\\n```\\n\\nFrom the sensors list then select the first element, this should be the accelerometer sensor.  \\nThe parameter of the event listener is a SensorEvent. From this event you can access the x, y, and z values of the accelerometer and do with them what you want.\\n\\n```java\\ncalculateSomething(event.values[0], event.values[1], event.values[2]);\\n```\\n\"},{\"id\":136,\"title\":\"How to add zoom controls to Android MapView\",\"slug\":\"how-to-add-zoom-controls-to-android-mapview\",\"excerpt\":\"The following code snippet shows how to add zoom controls to Android MapView. We can achieve this by calling setBuiltInZoomControls(boolean) method.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-07-30T22:02:46.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.015Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-mapview\",\"setbuiltinzoomcontrols\",\"google-maps-android-v1\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Add Zoom Controls to Android MapView\",\"metaDescription\":\"Learn how to add zoom controls to an Android MapView using the setBuiltInZoomControls method, with a quick, complete code and XML layout example.\",\"metaKeywords\":null},\"content\":\"\\nThe following code snippet shows how to add zoom controls to Android MapView. We can achieve this by calling `setBuiltInZoomControls(boolean)` method.\\n\\n```java\\nMapView map = (MapView)findViewById(R.id.mapview);\\nmap.setBuiltInZoomControls(true);\\n```\\n\\nThe above code snippet will add the zoom controls to the bottom-center of the `MapView`. The zoom controls only show up when you touch the screen, so you have to make sure that the map is clickable.\\n\\n```xml\\n\u003ccom.google.android.maps.MapView\\n       android:layout_width=\\\"fill_parent\\\"\\n       android:layout_height=\\\"fill_parent\\\"\\n       android:id=\\\"@+id/mapview\\\"\\n       android:clickable=\\\"true\\\"\\n       android:apiKey=\\\"your key\\\"\u003e\\n\u003c/com.google.android.maps.MapView\u003e\\n```\\n\"},{\"id\":137,\"title\":\"Upload image to a web service using HttpURLConnection\",\"slug\":\"upload-image-to-a-web-service-using-httpurlconnection\",\"excerpt\":\"The following code snippet can be used to upload an image to web service in Android. After getting a Bitmap object from the camera or other source, you can compress the create an HttpURLConnection and attach the image to the request body.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-07-30T21:53:33.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.044Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"httpurlconnection-image-upload\",\"android-bitmap-upload\",\"upload-image-web-service-android\",\"java-http-post-image\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"\\nThe following code snippet can be used to upload an image to web service in Android. After getting a Bitmap object from the camera or other source, you can compress the create an HttpURLConnection and attach the image to the request body.\\n\\n```java\\ntry {\\n    URL url = new URL(SERVER_POST_URL);\\n    HttpURLConnection c = (HttpURLConnection) url.openConnection();\\n    c.setDoInput(true);\\n    c.setRequestMethod(\\\"POST\\\");\\n    c.setDoOutput(true);\\n    c.connect();\\n\\n    OutputStream output = c.getOutputStream();\\n    bitmap.compress(CompressFormat.JPEG, 50, output);\\n    output.close();\\n\\n    Scanner result = new Scanner(c.getInputStream());\\n    String response = result.nextLine();\\n    Log.e(\\\"ImageUploader\\\", \\\"Error uploading image: \\\" + response);\\n\\n    result.close();\\n} catch (IOException e) {\\n        Log.e(\\\"ImageUploader\\\", \\\"Error uploading image\\\", e);\\n}\\n```\\n\"},{\"id\":138,\"title\":\"Performing Stress Test in Android Using  Monkey Application 
1Exerciser\",\"slug\":\"performing-stress-test-in-android-using-monkey-application-exerciser\",\"excerpt\":\"The Monkey is a tool you run on your device to generate a random system level userr events. It generates the specified number of events without any user interaction. This is generally helpful for performing stress test. This tool generates the random events from set of commands and collect the crashes or memory reports.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-07-24T08:28:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.074Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$c2\"},{\"id\":139,\"title\":\"AlertDialog and DialogFragment Example  in Xamarin Android\",\"slug\":\"alertdialog-and-dialogfragment-example-in-xamarin-android\",\"excerpt\":\"This example explains how to create AlertDialog and DialogFragment in Xamarin Android. Android supports several different ways to create a dialog such as AlertDialog and FragmentDialog.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-07-13T15:53:55.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.103Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"alertdialog\",\"dialog-fragment\",\"xamarin-dialogs\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"AlertDialog and DialogFragment Example in Xamarin Android\",\"metaDescription\":\"Learn how to create AlertDialog and DialogFragment in Xamarin.Android, with code examples for OnCreateDialog and OnCreateView implementations.\",\"metaKeywords\":null},\"content\":\"$c3\"},{\"id\":140,\"title\":\"Android CardView Example\",\"slug\":\"android-cardview-example\",\"excerpt\":\"The recent release of Android support library (v7:21.0.+) has introduced two new user interface widget: RecyclerView and CardView…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-07-01T13:30:50.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.135Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-cardview\",\"android-cardview-support\",\"android-recyclerview\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android CardView Example with Support Library\",\"metaDescription\":\"Learn how to use Android CardView from the v7 support library, including layout XML, dependency setup, and customizing corner radius and background color.\",\"metaKeywords\":null},\"content\":\"$c4\"},{\"id\":141,\"title\":\"Using Custom Activity Transition in GridView Image Gallery\",\"slug\":\"using-custom-activity-transition-in-gridview-image-gallery\",\"excerpt\":\"In this example, we will see how to create custom window animation that makes sense to user. We will extend our previous GridView example, to create custom bitmap scale animation when user clicks on a thumbnail in GridView.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-06-27T09:34:15.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.198Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-gridview-image-gallery\",\"custom-activity-transition-android\",\"android-window-animation\",\"gridview-thumbnail-zoom-animation\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$c5\"},{\"id\":142,\"title\":\"Download and Display Image in Android GridView\",\"slug\":\"download-and-display-image-in-android-gridview\",\"excerpt\":\"This example is an improved version of my previous example Android GridView Example. Instead of using static images…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-06-26T20:33:19.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.230Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-gridview-example\",\"picasso-image-loading\",\"android-asynctask-json\",\"android-gridview-adapter\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Download and Display Images in Android GridView\",\"metaDescription\":\"Learn how to download images from a server and display them in an Android GridView using AsyncTask, JSON parsing, and Picasso for image loading.\",\"metaKeywords\":null},\"content\":\"$c6\"},{\"id\":143,\"title\":\"ListView Header Parallax with Sticky Vie
1w in Android\",\"slug\":\"listview-header-parallax-with-sticky-view-in-android\",\"excerpt\":\"A quick Android example with code snippet to demonstrate ListView parallax effect with sticky header. In our previous tutorial, we saw Creating ListView Header Parallax Animation, now in this example we will go little further and make the list header parallax animation with an view stick to top when list is scrolled.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-06-23T22:25:58.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.301Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"listview-sticky-header\",\"listview-parallax-sticky-view\",\"android-onscrolllistener\",\"sticky-listview-header-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$c7\"},{\"id\":144,\"title\":\"ListView Header Parallax in Android\",\"slug\":\"listview-header-parallax-in-android\",\"excerpt\":\"A quick Android example with code snippet to demonstrate ListView header with parallax effect. You need to follow…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-06-17T17:42:32.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.335Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"listview-parallax-header\",\"android-onscrolllistener\",\"listview-addheaderview\",\"parallax-scroll-effect-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$c8\"},{\"id\":149,\"title\":\"Insertion sort example in Java\",\"slug\":\"insertion-sort-example-in-java\",\"excerpt\":\"Code snippet to sort array using insertion sort algorithm in java.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-06-16T22:25:29.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.535Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/191/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"insertion-sort-java\",\"java-sorting-algorithm-example\",\"sort-array-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Insertion Sort Example in Java\",\"metaDescription\":\"See a simple Java code example that implements the insertion sort algorithm to sort an array of integers, with step-by-step output at each pass.\",\"metaKeywords\":null},\"content\":\"\\nCode snippet to sort array using insertion sort algorithm in java.\\n\\n```java\\npublic class InsertionSortExample {\\n    static int step = 1;\\n\\n    public static void main(String[] args) {\\n\\n        int[] array = { 17, 21, 191, 3, 23, 45, 34, 9, 1 };\\n\\n        int n = array.length;\\n        for (int j = 1; j \u003c n; j++) {\\n            int key = array[j];\\n            int i = j - 1;\\n            while ((i \u003e -1) \u0026\u0026 (array[i] \u003e key)) {\\n                array[i + 1] = array[i];\\n                i--;\\n            }\\n            array[i + 1] = key;\\n            printNumbers(array);\\n\\n            System.out.println(\\\"n\\\");\\n        }\\n    }\\n\\n    private static void printNumbers(int[] input) {\\n        System.out.println(\\\"--- step \\\" + step + \\\" ----\\\");\\n        step++;\\n\\n        for (int i = 0; i \u003c input.length; i++) {\\n            System.out.print(input[i] + \\\", \\\");\\n        }\\n    }\\n}\\n```\\n\\n**Output**  \\n[![Insertion sort example in Java](/media/articles/191/Insertion-sort-example-in-Java-620x359.png)](http://stacktips.com)\\n\"},{\"id\":145,\"title\":\"Linear / Sequential Search Example in Java\",\"slug\":\"linear-or-sequential-search-in-java\",\"excerpt\":\"Quick Java code snippet to show Linear / Sequential Search.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-06-16T22:25:29.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.405Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/189/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"linear-search-java\",\"sequential-search-algorithm\",\"java-array-search-example\",\"java-scanner
1-input\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$c9\"},{\"id\":148,\"title\":\"Sort Array Ascending or Descending using Comparator in Java\",\"slug\":\"sort-objects-in-java-using-comparator\",\"excerpt\":\"Quick Java code snippet to sort Array ascending or descending using comparator in Java.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-06-16T22:25:29.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.485Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/190/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"java-comparator-example\",\"sort-array-objects-java\",\"arrays-sort-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$ca\"},{\"id\":151,\"title\":\"LinearLayout Manager Tutorial in Xamarin Android\",\"slug\":\"linearlayout-manager-tutorial-in-xamarin-android\",\"excerpt\":\"A LinearLayout manager is a most basic type of layout manager, that organizes its child views either horizontally or…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-06-08T22:07:36.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.707Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"linearlayout-orientation\",\"android-layout-weight-gravity\",\"xamarin-android-login-layout\",\"layout-gravity-vs-gravity\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$cb\"},{\"id\":152,\"title\":\"A Quick Introduction to View, ViewGroups and Layout Managers in Xamarin Android\",\"slug\":\"a-quick-introduction-to-view-viewgroups-and-layout-managers-in-xamarin-android\",\"excerpt\":\"Views and ViewGroups Everything that you see in an Android app is a View; buttons, labels, text boxes,…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-06-08T21:52:51.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.752Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-view-viewgroup\",\"xamarin-android-layout\",\"android-layout-managers\",\"declarative-vs-programmatic-ui\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Views, ViewGroups \u0026 Layout Managers in Xamarin Android\",\"metaDescription\":\"Learn the basics of Views, ViewGroups, and layout managers in Xamarin.Android, including Linear, Relative, Table, Frame, and Grid layouts, with examples.\",\"metaKeywords\":null},\"content\":\"$cc\"},{\"id\":153,\"title\":\"Xamarin Mobile Application Development for Android – Second Edition Announced\",\"slug\":\"xamarin-mobile-application-development-for-android-second-edition-announced\",\"excerpt\":\"Book titled “Xamarin Mobile Application Development for Android” – Second Edition is announced and is available to pre-order. This book is…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-06-02T16:46:50.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.808Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"blog\"],\"tags\":[\"xamarin-android-book\",\"xamarin-mobile-development\",\"xamarin-android-second-edition\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$cd\"},{\"id\":154,\"title\":\"SharedPreferences Example in Xamarin Android\",\"slug\":\"shared-preferences-example-in-xamarin-android\",\"excerpt\":\"Shared preferences are persistence key/value data pairs, used to store primitive data pairs such as bool, float, int, string and long. The data saved into android preference are persisted across different user sessions and is private to the application it is created. Any other application cannot access to it.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-05-29T00:11:14.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.836Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"sharedpreferences-xamarin\",\"android-key-value-storage\",\"isharedpreferenceseditor\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$ce\"},{\"id\":155,\"title\":\"Android Dialog Fragment Example\",\"slug\":\"android-dialog-fragment-example\",\"excerpt\":\"Dialog is like any other window that pops up in front of current window, used to show some short message, taking user input or to accept users decision. Unl
1ike Toast, a dialog is generally used where user attention is mandate.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-03-27T23:40:03.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.867Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"dialogfragment\",\"oncreatedialog\",\"android-alertdialog\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android DialogFragment Example: Create and Dismiss\",\"metaDescription\":\"Learn how to create an Android DialogFragment using onCreateView and onCreateDialog, display it from an Activity, and dismiss it on button click.\",\"metaKeywords\":null},\"content\":\"$cf\"},{\"id\":146,\"title\":\"Consuming REST Web Service and Deserializing Response Using Json.NET in Xamarin Android\",\"slug\":\"consuming-rest-web-service-in-xamarin-android\",\"excerpt\":\"Consuming data from web services is the most common task and very integral part to most of the full-fledged mobile application. In this tutorial we will take a look into various key concepts and steps for consuming web service methods from Xamarin Android application.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-03-10T13:09:45.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.957Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"json-net-deserialization\",\"xamarin-httpclient\",\"async-await-csharp\",\"consume-rest-api-xamarin\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Consume REST Web Services in Xamarin Android with Json.NET\",\"metaDescription\":\"Learn how to call a REST API and deserialize the JSON response using Json.NET in a Xamarin Android application, step by step.\",\"metaKeywords\":null},\"content\":\"$d0\"},{\"id\":147,\"title\":\"Android TextWatcher Example\",\"slug\":\"android-textwatcher-example\",\"excerpt\":\"In this tutorial we will show you how to use TextWatcher in Android with example. TextWatcher is used to keep watch on the EditText content while user inputs the data. It allows you to keep track on each character when entered on EditText.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-02-19T02:07:14.000Z\",\"updatedDate\":\"2025-09-16T23:05:27.989Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-textwatcher\",\"addTextChangedListener\",\"edittext-input-validation\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android TextWatcher Example: Track EditText Changes\",\"metaDescription\":\"Learn how to use TextWatcher in Android to monitor EditText input in real time with addTextChangedListener, illustrated with a password field example.\",\"metaKeywords\":null},\"content\":\"$d1\"},{\"id\":59,\"title\":\"Introduction to JSON\",\"slug\":\"introduction-to-json-basics\",\"excerpt\":\"JSON (JavaScript Object Notation) is one of the most popular and widely accepted data exchange format originally specified by Douglas Crockford. JSON is widely accepted in the softwares that includes client-server architecture for exchanging data between client and server.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-02-19T01:57:39.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.017Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"blog\"],\"tags\":[\"json-vs-xml\",\"json-syntax\",\"json-intro\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$d2\"},{\"id\":81,\"title\":\"Android ScrollView Example\",\"slug\":\"android-scrollview-example\",\"excerpt\":\"In this tutorial we will show you, how to use Android ScrollView component and create a simple example using various ScrollView properties. ScrollView is a special kind of layout, designed to hold view larger than its actual size. When the Views size goes beyond the ScrollView size, it automatically adds scroll bars and can be scrolled vertically.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-02-12T22:59:56.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.046Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-scrollview\",\"fillviewport\",\"vertical-scrolling-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android ScrollView Example: Vertical Scrolling Layout\",\"metaDescription\":\"Learn how to use Android ScrollView to display content larger than the screen, including fillViewport, layout rules, and a complete XML example.\",\"metaKeywords\":null},\"content\":\"$d3\"},{\"id\":157,\"title\":\"Xamarin Android WebView Tutorial\",\"slug\":\"xamarin-android-webview-tutorial\",\"excerpt\":\"In the course of this tutorial, we will take a look into using WebView in Xamarin.Android. This tutorial loads simple webpage on WebView and using WebViewClient.WebView is an android UI component that displays webpages.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-30T11:38:59.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.123Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"xamarin-webview\",\"
1webviewclient-example\",\"load-html-in-webview\",\"xamarin-android-tutorial\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$d4\"},{\"id\":158,\"title\":\"Android LinearLayout Example\",\"slug\":\"android-linearlayout-example\",\"excerpt\":\"The LinearLayout is the most basic layout manager provided by Android. The LinearLayout organizes the child views either horizontally or vertically based on the specified orientation property. The value for orientation property can be either horizontal or vertical.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-27T22:50:20.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.193Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"linearlayout\",\"android-layout-orientation\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android LinearLayout Example with Weight Property\",\"metaDescription\":\"Learn how to use Android LinearLayout to arrange views horizontally or vertically, nest layouts, and distribute space evenly using layout_weight.\",\"metaKeywords\":null},\"content\":\"$d5\"},{\"id\":159,\"title\":\"Android TextView Example\",\"slug\":\"android-textview-example\",\"excerpt\":\"In this tutorial, we will take a look into the Android TextView widget and various TextView properties. TextView is used to display text on an Android screen. TextView is like a dummy label and doesn't allow editing text input.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-27T22:45:56.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.221Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-textview\",\"textview-attributes\",\"android-text-styling\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android TextView Example: Key Properties Explained\",\"metaDescription\":\"Learn the most useful Android TextView properties like textColor, ellipsize, autoLink, and shadow effects, with a complete XML example.\",\"metaKeywords\":null},\"content\":\"$d6\"},{\"id\":160,\"title\":\"Android Lollipop Swipe to Refresh Example\",\"slug\":\"android-lollipop-swipe-to-refresh-example\",\"excerpt\":\"The Swipe to refresh layout is used to indicate user while the content of a screen is being updated. It was earlier introduced in Android 4.4 Kitkat, and was named as SwipeRefreshLayout. Visually it was represented just below ActionBar.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-27T17:27:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.315Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"swiperefreshlayout\",\"pull-to-refresh\",\"material-design\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android SwipeRefreshLayout Example (Lollipop Material Design)\",\"metaDescription\":\"Learn how to implement SwipeRefreshLayout in Android to add pull-to-refresh functionality to a ListView, complete with JSON feed loading and full source code.\",\"metaKeywords\":null},\"content\":\"$d7\"},{\"id\":161,\"title\":\"Android RelativeLayout Example\",\"slug\":\"android-relativelayout-example\",\"excerpt\":\"Over the course of this tutorial, we will take a look into Android RelativeLayout and its properties. RelativeLayout is one among the most used layout after LinearLayout. It allows its child views to position relative to each other or relative to the container or another container. For example, if we have to build a complex layout as shown in the image below, this can be achieved with ease by using RelativeLayout.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-27T14:39:43.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.347Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-tablelayout\",\"tablelayout-tablerow\",\"android-table-example\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android TableLayout Example: Rows and Columns\",\"metaDescription\":\"Learn how to use Android TableLayout and TableRow to display data in rows and columns, with a complete XML example showing Android version data.\",\"metaKeywords\":null},\"content\":\"$d8\"},{\"id\":162,\"title\":\"Android Table Layout Example\",\"slug\":\"android-table-layout-example\",\"excerpt\":\"The TableLayout layout is an extension of LinearLayout. As the name indicates, TableLayout is used to display child Vie
1w elements in rows and columns. The concept of TableLayout works something similar to an HTML table. If you can recall the HTML table, TableLayout can be explained as tag and TableRow is like a element. You can use any view as table cell element.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-27T11:41:17.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.380Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-tablelayout\",\"tablelayout-tablerow\",\"android-table-example\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android TableLayout Example: Display Rows and Columns\",\"metaDescription\":\"Learn how to use Android TableLayout and TableRow to arrange views in rows and columns, with a full XML example listing Android version releases.\",\"metaKeywords\":null},\"content\":\"$d9\"},{\"id\":163,\"title\":\"Android FrameLayout Example\",\"slug\":\"android-framelayout-example\",\"excerpt\":\"Over the course of this tutorial, we will take a look into Android FrameLayout and creating layout through xml and from code programmatically. FrameLayout is one of the useful layout provided by android system, which allows User Interface widgets to be overlapped with each other.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-26T23:32:05.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.409Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"framelayout\",\"framelayout-xml\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android FrameLayout Example: XML and Programmatic\",\"metaDescription\":\"Learn how to create an Android FrameLayout to overlap views, with both XML layout and programmatic Java examples for stacking images and text.\",\"metaKeywords\":null},\"content\":\"$da\"},{\"id\":164,\"title\":\"Android Lollipop Toolbar Example\",\"slug\":\"android-lollipop-toolbar-example\",\"excerpt\":\"Toolbar is a complete replacement to Android ActionBar. It provides greater control to customize its appearance unlike old ActionBar. Using Toolbar, application developer can now, show multiple toolbars on the screen, spanning only part of the width, etc.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-25T13:14:34.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.443Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-toolbar\",\"actionbar-replacement\",\"appcompat-toolbar\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Toolbar Example: Replace ActionBar with Toolbar\",\"metaDescription\":\"Learn how to use Android's Toolbar widget as a replacement for ActionBar, including AppCompat setup, XML layout, and activity code examples.\",\"metaKeywords\":null},\"content\":\"$db\"},{\"id\":166,\"title\":\"Strategy Design Pattern in Java\",\"slug\":\"strategy-design-pattern-in-java\",\"excerpt\":\"The Strategy design pattern belongs to the behavioral family of pattern that deals with change the behavior of a class by changing the internal algorithm at runtime without modifying the class itself. This allows extensibility and loose coupling of objects.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-20T00:55:22.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.545Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"strategy-design-pattern-java\",\"behavioral-design-patterns\",\"sorting-strategy-example\",\"gang-of-four-patterns\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$dc\"},{\"id\":167,\"title\":\"State Design Pattern in Java\",\"slug\":\"state-design-pattern-in-java\",\"excerpt\":\"Over the course of this article, we will examine State design pattern in java with help of realtime examples. The State design pattern belongs to the behavioral family of pattern that deals with the runtime object behavior based on the current state. The definition of State Design Pattern as per the original Gang of Four book is; “Allows an object to alter its behavior when its internal state changes. The object will appear to change its class”.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-19T15:17:28.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.625Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"state-design-pattern-java\",\"behavioral-design-patterns\",\"gang-of-four
1-patterns\",\"java-state-machine-example\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$dd\"},{\"id\":168,\"title\":\"Template Method Design Pattern in Java\",\"slug\":\"template-method-design-pattern-in-java\",\"excerpt\":\"Over the course of this article, we will examine the Template Method design pattern in java with help…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-16T00:47:12.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.702Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"template-method-design-pattern\",\"behavioral-design-patterns\",\"java-abstract-class-example\",\"gang-of-four-patterns\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$de\"},{\"id\":169,\"title\":\"Brief introduction to Software Design Patterns\",\"slug\":\"brief-introduction-to-design-patterns\",\"excerpt\":\"What are Design Patterns? Patterns exist everywhere in the world. In culinary, art, medicine, law, mathematics, music, dancing…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-13T00:39:13.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.746Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"gang-of-four-design-patterns\",\"creational-design-patterns\",\"structural-design-patterns\",\"behavioral-design-patterns\",\"software-design-principles\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Software Design Patterns: A Brief Introduction\",\"metaDescription\":\"Understand what software design patterns are, why they matter, and how the Gang of Four's creational, structural, and behavioral patterns solve recurring problems.\",\"metaKeywords\":null},\"content\":\"$df\"},{\"id\":174,\"title\":\"Stepping Into My First Java Program “Hello World!”\",\"slug\":\"stepping-into-my-first-java-program-hello-world\",\"excerpt\":\"Before begin writing your first Java program, you need to have your development environment ready. For writing and…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2015-01-10T15:08:56.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.817Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-hello-world-program\",\"first-java-program\",\"java-main-method\",\"java-source-code-comments\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$e0\"},{\"id\":175,\"title\":\"JSON Feed Reader Application in Xamarin Android\",\"slug\":\"json-feed-reader-application-in-xamarin-android\",\"excerpt\":\"This is an sample JSON feed reader application developed in Xamarin.Android platform. This app will fetch the recent posts…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-12-24T04:58:19.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.885Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"xamarin-android-json-feed\",\"urlimageviewhelper\",\"xamarin-listview-example\",\"async-image-caching-xamarin\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"\\n[![JSON Feed Reader Application in Xamarin.Android](/media/articles/232/JSON-Feed-Reader-Application-in-Xamarin.Android.png)](http://stacktips.com)This is an sample JSON feed reader application developed in Xamarin.Android platform. This app will fetch the recent posts from stacktips.com and display list of posts along with post title, thumbnail, description on screen.\\n\\nFeatures\\n\\n1.  Download latest data asynchronously from server\\n2.  Display feeds title, thumbnail on list view\\n3.  Download and cache images using [UrlImageViewHelper](http://components.xamarin.com/gettingstarted/urlimageviewhelper) component\\n4.  Allow user to read feed details\\n\\nAll the source code used in this example, are open source. You may grab a copy of the project source code from the download link provided.\\n\\n[Browse Code](https://github.com/npanigrahy/Xamarin.Android-Examples/tree/master/JsonFeedParser) [Download Zip](https://github.com/npanigrahy/Xamarin.Android-Examples/archive/master.zip)\\n\"},{\"id\":176,\"title\":\"ListView Example in Xamarin.Android\",\"slug\":\"listview-example-in-xamarin-android\",\"excerpt\":\"This post will walk 
1you through crating a custom ListView in Xamarin.Android using list adapter. ListView is one…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-12-23T05:21:17.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.919Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"xamarin-android-listview\",\"xamarin-baseadapter-example\",\"custom-listview-adapter-xamarin\",\"listview-itemclick-xamarin\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$e1\"},{\"id\":177,\"title\":\"Using SQLite.NET ORM in Xamarin Application\",\"slug\":\"using-sqlite-net-orm-in-xamarin-application\",\"excerpt\":\"ORM stands for Object Relational Mapping. SQLite.NET ORM is an light weight and open source library that allows…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-12-19T20:07:43.000Z\",\"updatedDate\":\"2025-09-16T23:05:28.948Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"sqlite-net-orm-xamarin\",\"xamarin-sqlite-crud\",\"sqliteconnection-xamarin\",\"xamarin-cross-platform-database\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$e2\"},{\"id\":178,\"title\":\"Data Storage Options in Xamarin\",\"slug\":\"data-storage-options-in-xamarin\",\"excerpt\":\"Most of the commercial mobile application uses local storage for large data processing and to improve efficiency. While…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-12-19T20:01:37.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.018Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"xamarin-data-storage\",\"sqlite-net-xamarin\",\"shared-preferences-vs-nsuserdefaults\",\"mobile-app-local-storage\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Data Storage Options in Xamarin: A Complete Overview\",\"metaDescription\":\"Explore the key data storage options in Xamarin apps, including key-value preferences, text files, SQLite databases, and image file caching.\",\"metaKeywords\":null},\"content\":\"$e3\"},{\"id\":179,\"title\":\"Xamarin Learning Resources\",\"slug\":\"xamarin-learning-resources\",\"excerpt\":\"Xamarin is a San Francisco, California based software company which provides commercial software development tools that leverage the…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-12-13T05:28:56.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.047Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"xamarin-learning-resources\",\"xamarin-forms-books\",\"xamarin-android-development\",\"xamarin-ios-development\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$e4\"},{\"id\":180,\"title\":\"Asynchronous Image Loading in Xamarin Android\",\"slug\":\"asynchronous-image-loading-xamarin-android\",\"excerpt\":\"This tutorial explains how to download image asynchronously in Xamarin.Android. In this example, we will downloading image using…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-12-11T13:37:33.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.123Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"xamarin-android\",\"async-image-download\",\"webclient-download-async\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Asynchronous Image Loading in Xamarin.Android\",\"metaDescription\":\"Learn how to download and display images asynchronously in Xamarin.Android using System.Net.WebClient, with a progress indicator and cancel support.\",\"metaKeywords\":null},\"content\":\"$e5\"},{\"id\":181,\"title\":\"A Step-By-Step Guide On iOS8 Beta Testing Using TestFlight\",\"slug\":\"a-step-by-step-guide-on-ios8-beta-testing-using-testflight\",\"excerpt\":\"Building a fine quality mobile app is something that involves a great deal of dedication and hard work.…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-11-25T10:24:43.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.151Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/242/thumbnail.png\",\"topics\":[\"blog\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$e6\"},{\"id\":182,\"title\":\"Android Login Screen Using Xamarin\",\"slug\":\"android-login-screen-using-xamarin\",\"excerpt\":\"In this tutorial we will see “How to create a login screen using Xamarin.Android”. This example assumes, you…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-11-12T10:23:31.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.223Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"xamarin-android\",\"android-login-screen\",\"xamarin-tutorial\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Login Screen Using Xamarin: Step-by-Step Tutorial\",\"metaDescription\":\"Learn how to build a login screen in Xamarin.Android using EditText fields and a login button, with full AXML layout and C# activity code.\",\"metaKeywords\":null},\"content\":\"$e7\"},{\"id\":183,\"title\":\"Creating a Splash Screen in Android Using Xamarin\",\"slug\":\"creating-a-splash-screen-in-android-using-xamarin\",\"excerpt\":\"In this article, we take a look into creating a splash screen in Android using Xamarin. A splash…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-11-12T09:02:17.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.298Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"xamarin-android-splash-screen\",\"android-splash-activity\",\"xamarin-nohistory-activity\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Creating a Splash Screen in Android Using Xamarin\",\"metaDescription\":\"Learn how to build a splash screen in Xamarin Android using a custom activity theme, windowBackgroun
1d drawable, and the NoHistory activity attribute.\",\"metaKeywords\":null},\"content\":\"$e8\"},{\"id\":185,\"title\":\"Interface Segregation Principle\",\"slug\":\"interface-segregation-principle\",\"excerpt\":\"This article explains the interface segregation principle and its uses. Interface segregation is a design principle that deals…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-11-06T15:25:18.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.329Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"interface-segregation-principle\",\"solid-design-principles\",\"java-interface-design\",\"fat-interface-antipattern\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$e9\"},{\"id\":186,\"title\":\"How to Use Picasso Image Loader Library in Android\",\"slug\":\"how-to-use-picasso-library-in-android\",\"excerpt\":\"This this tutorial, we will take a look into how to use Picasso library in android. Picasso is open source and one of the widely used image downloader library in Android. It is created and maintained by Square. It is among the powerful image download and caching library for android.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-11-05T13:00:57.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.405Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"picasso-image-loading-android\",\"picasso-load-image-imageview\",\"picasso-placeholder-error\",\"android-image-caching-library\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Use Picasso Image Loading Library in Android\",\"metaDescription\":\"Learn how to use the Picasso library in Android to load images from a URL, add placeholders and error fallbacks, and resize or transform images.\",\"metaKeywords\":null},\"content\":\"$ea\"},{\"id\":187,\"title\":\"Factory Method Design Pattern in Java\",\"slug\":\"factory-method-design-pattern-java\",\"excerpt\":\"Over the course of this article, we will examine one of the most commonly used patterns, the Factory method pattern in java.. The Factory design pattern provides a way to use an instance as an object factory. The factory can return an instance of one of several possible classes in a class hierarchy, depending on the data provided to it.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-11-04T05:25:55.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.437Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"factory-method-design-pattern\",\"java-creational-design-patterns\",\"simple-factory-vs-factory-method\",\"abstract-factory-pattern-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Factory Method Design Pattern in Java Explained\",\"metaDescription\":\"Learn the Factory Method design pattern in Java with a practical example comparing simple factory and factory method approaches to object creation.\",\"metaKeywords\":null},\"content\":\"$eb\"},{\"id\":188,\"title\":\"Builder Design Pattern In Java\",\"slug\":\"builder-design-pattern-java\",\"excerpt\":\"Over the course of this article, we will examine Builder design pattern in Java. Builder design pattern belongs to the creational family of pattern, that control the object instantiation process. Builder design pattern simplifies the object instantiation process for complex objects.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-11-03T10:40:11.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.506Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"builder-design-pattern\",\"creational-design-pattern-java\",\"java-design-patterns\",\"gang-of-four-builder-pattern\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Builder Design Pattern in Java Explained with Example\",\"metaDescription\":\"Learn how the Builder design pattern simplifies constructing complex Java objects step by step, with a practical cafe meal-ordering example.\",\"metaKeywords\":null},\"content\":\"$ec\"},{\"id\":189,\"title\":\"Prototype Design Pattern In Java\",\"slug\":\"prototype-design-pattern-java\",\"excerpt\":\"Prototype design pattern belongs to the structural family of pattern. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-10-30T18:32:33.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.541Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"prototype-design-pattern-java\",\"java-cloneable-interface\",\"creational-design-patterns-java\",\"object-cloning-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$ed\"},{\"id\":190,\"title\":\"Adapter Design Pattern In Java\",\"slug\":\"adapter-design-pattern-in-java\",\"excerpt\":\"Over the course of this article, we will examine Adapter design pattern in Java. Java Adapter design pattern allows two incompatible classes to work together by convert
1ing the interface of one class into an interface expected by the clients.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-10-28T19:07:04.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.582Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"adapter-design-pattern\",\"java-structural-patterns\",\"gang-of-four-patterns\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Adapter Design Pattern in Java: Explained with Example\",\"metaDescription\":\"Understand the Adapter design pattern in Java with real-world analogies and a complete object adapter code example using a bank account use case.\",\"metaKeywords\":null},\"content\":\"$ee\"},{\"id\":191,\"title\":\"Observer Design Pattern In Java\",\"slug\":\"observer-design-pattern-in-java\",\"excerpt\":\"Observer design pattern defines one-to-many dependency between objects in which one object changes state, all its dependents are notified. Observer design pattern sometimes called as publisher-subscriber design pattern in networked models.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-10-24T14:18:07.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.633Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"design-pattern\"],\"tags\":[\"observer-design-pattern-java\",\"publisher-subscriber-pattern\",\"java-behavioral-design-patterns\",\"observer-pattern-example\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$ef\"},{\"id\":192,\"title\":\"How to Use TestFairy Command Line Upload Script\",\"slug\":\"testfairy-command-line-upload-script\",\"excerpt\":\"TestFairy is an android application beta testing and deployment platform. Read TestFairy platform features and detailed description here.…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-10-02T02:30:37.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.671Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/256/thumbnail.png\",\"topics\":[\"blog\"],\"tags\":[\"testfairy-command-line-uploader\",\"android-apk-signing-keystore\",\"ci-cd-android-build-upload\",\"testfairy-jenkins-integration\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$f0\"},{\"id\":193,\"title\":\"Android RecyclerView Example\",\"slug\":\"android-recyclerview-example\",\"excerpt\":\"Google’s upcoming operating system named Android L looks very promising. It is highly focused on rich user experience and what they called it as material design. In this example we will take a look at the new UI widget called RecyclerView.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-23T19:50:27.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.714Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/android-ui-tutorials/tree/master/android-recyclerview-demo\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-recyclerview\",\"recyclerview-cardview\",\"recyclerview-click-listener\",\"recyclerview-adapter\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android RecyclerView Example with CardView\",\"metaDescription\":\"Learn how to implement Android RecyclerView with CardView, build a custom adapter, load images with Picasso, and handle item click events.\",\"metaKeywords\":null},\"content\":\"$f1\"},{\"id\":194,\"title\":\"Android Service Interview Questions\",\"slug\":\"android-service-interview-questions\",\"excerpt\":\"In this post you will find set of interview questions and answers on Android Service, IntentService and AlarmService\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-23T01:30:53.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.785Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"interview-questions\",\"android-faqs\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Service Interview Questions and Answers\",\"metaDescription\":\"Prepare for Android interviews with common questions on Service, IntentService, and AlarmManager, covering lifecycle, bound vs unbound, and key differences.\",\"metaKeywords\":null},\"content\":\"$f2\"},{\"id\":195,\"title\":\"Android Interview Question Answers For Freshers\",\"slug\":\"android-interview-questions\",\"excerpt\":\"Here in this post, you will find compiled set of android interview questions and answers. These questions are…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-21T11:43:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.817Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"interview-questions\",\"activity-lifecycle\",\"android-data-persistence\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Interview Questions for Freshers\",\"metaDescription\":\"A compiled set of Android interview questions and answers for freshers, covering activity lifecycle, ANR, context types, nine-patch images, and data storage.\",\"metaKeywords\":null},\"content\":\"$f3\"},{\"id\":196,\"title\":\"Repeat Alarm Example In Android Using AlarmManager\",\"slug\":\"repeat-alarm-example-in-android\",\"excerpt\":\"In this tutorial we will learn how to create a repeat alarm example in android using AlarmManager class. AlarmManager is a class in Android which is used access device alarm service. This allow your application to execute certain piece of code on a given sc
1heduled time. This can run outside the lifetime of your application.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-17T00:08:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.847Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-alarmmanager\",\"repeating-alarm-android\",\"android-scheduled-tasks\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$f4\"},{\"id\":197,\"title\":\"How To Create Excel File In Android\",\"slug\":\"how-to-create-excel-file-in-android\",\"excerpt\":\"In this tutorial, we will explain how to create an Excel file in Android using Java for the Excel library.\",\"difficulty\":\"intermediate\",\"publishedDate\":\"2014-09-16T05:35:39.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.923Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-excel-file\",\"jexcelapi-android\",\"export-data-to-excel-android\",\"writablesheet-jxl\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Create an Excel File in Android Using Java\",\"metaDescription\":\"Learn how to export SQLite data to an Excel file in Android using the Java for Excel (JExcelApi) library, with a complete code walkthrough.\",\"metaKeywords\":null},\"content\":\"$f5\"},{\"id\":198,\"title\":\"Android Third Party Libraries and SDK’s\",\"slug\":\"android-third-party-libraries-sdks\",\"excerpt\":\"Over past few years, the age of mobile development become an fiercely-competitive world of serious money making business.…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-15T17:04:35.000Z\",\"updatedDate\":\"2025-09-16T23:05:29.993Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-open-source-libraries\",\"okhttp-volley-retrofit\",\"android-orm-libraries\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Popular Android Third-Party Libraries and SDKs\",\"metaDescription\":\"Discover popular Android open-source libraries for networking, image loading, databases, and more, including OkHttp, Retrofit, Picasso, and GreenDAO.\",\"metaKeywords\":null},\"content\":\"$f6\"},{\"id\":199,\"title\":\"Creating a Background Service in Android Using IntentService\",\"slug\":\"creating-a-background-service-in-android\",\"excerpt\":\"In this tutorial we will take a look into one of most important and commonly used Android concept called IntentService. This post explains steps involved in creating a background service in Android using IntentService.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-15T00:30:28.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.057Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-intentservice\",\"background-service-android\",\"resultreceiver-android\",\"android-networking-tutorial\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android IntentService Tutorial: Background Service Guide\",\"metaDescription\":\"Learn how to create a background service in Android using IntentService, pass data with ResultReceiver, and update your activity UI with real examples.\",\"metaKeywords\":null},\"content\":\"$f7\"},{\"id\":106,\"title\":\"Android Networking Tutorial\",\"slug\":\"android-networking-tutorial\",\"excerpt\":\"In this android networking tutorial we will create a sample application that illustrates how to perform network operations in android.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-13T03:00:04.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.129Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-httpurlconnection\",\"apache-httpclient-android\",\"android-asynctask-networking\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Networking Tutorial: HttpClient vs HttpURLConnection\",\"metaDescription\":\"Learn how to perform network operations in Android using Apache HttpClient and HttpURLConnection, download JSON data, and follow networking best practices.\",\"metaKeywords\":null},\"content\":\"$f8\"},{\"id\":184,\"title\":\"Count line word and characters in file\",\"slug\":\"count-line-word-characters-file\",\"excerpt\":\"In this example we’ll see how to count line, word and characters in file. package com.javatechig; import java.io.BufferedReader;…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-11T02:43:45.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.217Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"how-tos\",\"code-snippet\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Count Lines, Words, and Characters in a File Using Java\",\"metaDescription\":\"A Java example using BufferedReader and LineNumberReader to count the total lines, words, and characters in a text file.\",\"metaKeywords\":null},\"content\":\"$f9\"},{\"id\":200,\"title\":\"How to delete and rename a file in java\",\"slug\":\"how-to-delete-and-rename-a-file-in-java\",\"excerpt\":\"This post provides sample program explaining how to delete and rename a file in java Rename file in Java…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-10T07:32:49.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.249Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-file-rename\",\"java-file-delete\",\"java-io-file-class\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Delete and Rename a File in Java\",\"metaDescription\":\"Learn how to rename and delete files in Java using the File class's renameTo() and delete() methods, with complete working examples.\",\"metaKeywords\":null},\"content\":\"$fa\"},{\"id\":201,\"title\":\"Copy file from one folder to another in java\",\"slug\":\"copy-file-one-folder-another-java\",\"excerpt\":\"This example explains how to Copy file from one folder to another in java. package com.javatechig; import java.io.File;…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-10T03:22:58.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.284Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"code-snippet\",\"how-tos\",\"java-file\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Copy a File from One Folder to Another in Java\",\"metaDescription\":\"A simple Java example showing how to copy a file from one folder to another using FileChannel, with complete working code.\",\"metaKeywords\":null},\"content\":\"$fb\"},{\"id\":202,\"title\":\"Copying the Contents of One text file to Another in Java\",\"slug\":\"copying-contents-one-text-file-another-java\",\"excerpt\":\"In this example, we will see a sample program to copying the contents of one text file to another in Java.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-09T08:16:58.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.333Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-inputstream-outputstream\",\"copy-text-file-java\",\"java-file-read-write\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Copy Contents of One Text File to Another in Java\",\"metaDescription\":\"A step-by-step Java example that shows how to copy the contents of one text file into another using InputStream and OutputStream.\",\"metaKeywords\":null},\"content\":\"$fc\"}
1,{\"id\":203,\"title\":\"How to Create a Text File in Java\",\"slug\":\"how-to-create-a-text-file-in-java\",\"excerpt\":\"In this article we will see the sample code to create a text file in java.In this example, we’ll use the PrintWriter class.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-09-09T03:11:17.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.379Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-printwriter\",\"create-text-file-java\",\"java-file-io\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Create a Text File in Java Using PrintWriter\",\"metaDescription\":\"Learn how to create and write to a text file in Java with the PrintWriter class, including UTF-8 encoding and proper exception handling.\",\"metaKeywords\":null},\"content\":\"\\nIn this article we will see how to create a text file in java. In this example, we’ll use the [`PrintWriter`](http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html) class.\\n\\n```java\\npackage com.javatechig;\\n\\nimport java.io.FileNotFoundException;\\nimport java.io.PrintWriter;\\nimport java.io.UnsupportedEncodingException;\\n\\npublic class CreateTextFile {\\n\\n    public static void main(String[] args) {\\n        PrintWriter writer = null;\\n        try {\\n            /* Create a new file with UTF-8 encoding */\\n            writer = new PrintWriter(\\\"file1.txt\\\", \\\"UTF-8\\\");\\n\\n            /* Write content to file */\\n            writer.println(\\\"Hello, this is a binary file.\\\");\\n            writer.println(\\\"Put your file contents here...\\\");\\n\\n            writer.close();\\n            System.out.println(\\\"New File Created!\\\");\\n        } catch (FileNotFoundException e) {\\n            e.printStackTrace();\\n        } catch (UnsupportedEncodingException e) {\\n            e.printStackTrace();\\n        }\\n\\n    }\\n}\\n```\\n\"},{\"id\":205,\"title\":\"TestFairy – Android App Beta Testing and Deployment Platform\",\"slug\":\"testfairy-android-app-beta-testing-platform\",\"excerpt\":\"TestFairy makes Android beta testing painless. This satisfies all the wish-list to stand out as an best alternative for TestFlight. In this post we’ll see TestFairy features, advance reporting and TestFairy command line uploader script\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-08-25T04:49:20.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.486Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"blog\"],\"tags\":[\"testfairy-android-beta-testing\",\"android-crash-reporting-tools\",\"android-app-distribution\",\"beta-testing-platforms-comparison\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$fd\"},{\"id\":206,\"title\":\"Android Service Example\",\"slug\":\"android-service-example\",\"excerpt\":\"In this tutorial we will learn how to create a service, and service lifecycle methods. A service is a application component used to perform long running tasks in background. A service can run in the background indefinitely, even if component that started the service is destroyed\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-08-25T04:10:17.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.534Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-service-lifecycle\",\"bound-vs-unbound-service\",\"startservice-onstartcommand\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Service Example: Lifecycle and Implementation\",\"metaDescription\":\"Learn how Android Service works, including bound vs unbound services, lifecycle methods like onStartCommand, and a complete working code example.\",\"metaKeywords\":null},\"content\":\"$fe\"},{\"id\":207,\"title\":\"Android Notification Example Using NotificationCompat\",\"slug\":\"android-notification-example-using-notificationcompat\",\"excerpt\":\"In this example, we will learn how to create Android n
1otification using NotificationCompat class available in the Android Support library. This class supports big style notification with backward compatibility.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-08-10T15:47:40.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.598Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"notificationcompat-builder\",\"android-notification-example\",\"big-style-notification\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Notification Example Using NotificationCompat\",\"metaDescription\":\"Learn how to create backward-compatible Android notifications with NotificationCompat.Builder, including big-style notifications and a working code example.\",\"metaKeywords\":null},\"content\":\"$ff\"},{\"id\":208,\"title\":\"Android Studio Shortcuts for Mac OS X Users\",\"slug\":\"android-studio-shortcuts-for-mac-os-x-users\",\"excerpt\":\"Android Studio brings tons of keyboard shortcuts that helps developers to keep hands more on keyboard rather than relying much on the mouse. The lesser you use mouse, results in faster development. Well, let us see some of the shortcuts for android studio for Mac user.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-08-06T04:34:53.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.635Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-studio-shortcuts\",\"mac-keyboard-shortcuts\",\"android-studio-productivity\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Studio Keyboard Shortcuts for Mac OS X\",\"metaDescription\":\"A handy reference of Android Studio keyboard shortcuts for Mac users, covering code navigation, search, build, refactoring, and more.\",\"metaKeywords\":null},\"content\":\"$100\"},{\"id\":209,\"title\":\"Android Studio Project Structure\",\"slug\":\"android-studio-project-structure\",\"excerpt\":\"Android Studio is an IDE based on IntelliJ IDEA that uses gradle build system. In this tutorial we will see Android Studio Project Structure in detailed vs eclipse ADT project structure.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-08-05T16:04:54.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.706Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-studio-project-structure\",\"gradle-build-variants\",\"eclipse-vs-android-studio\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Studio Project Structure Explained\",\"metaDescription\":\"Understand the Android Studio project structure, including Gradle build variants, modules, and folders, compared to the traditional Eclipse ADT layout.\",\"metaKeywords\":null},\"content\":\"$101\"},{\"id\":211,\"title\":\"Invoke Method Using Java Reflection\",\"slug\":\"invokeing-method-using-java-reflection\",\"excerpt\":\"Java provides reflection API to do introspection of an object and modify its behavior on the run time. The class Class in the Java API forms the basis to identify the object class and its internal structure of that particular Class. The below three functions are important to get the class behavior. In this articles we will see, how to invoke a method dynamically at runtime.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-07-09T02:46:04.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.804Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$102\"},{\"id\":212,\"title\":\"Bamboo Continuous Integration for Android\",\"slug\":\"bamboo-continuous-integration-for-android\",\"excerpt\":\"Here in this tutorial, we’ll show you the importance of continuous integration tools in software development process and steps to configure Bamboo for building android code.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-07-04T07:18:26.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.845Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"blog\"],\"tags\":[\"bamboo-ci-cd\",\"android-continuous-integration\",\"apk-signing-jarsigner\",\"zipalign-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Bamboo Continuous Integration for Android Builds\",\"metaDescription\":\"Learn how to set up Atlassian Bamboo CI for Android projects, from checking out source code to building, signing, and zipaligning your APK.\",\"metaKeywords\":null},\"content\":\"$103\"}
1,{\"id\":213,\"title\":\"Covariant return type example in java\",\"slug\":\"covariant-return-type-example-in-java\",\"excerpt\":\"The covariant return type allows narrowing down return type of the overridden method. This feature will help to avoid down casting on the client side. It allows programmer to program without the need of type checking and down casting. The covariant return type always works only for non-primitive return types.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-07-03T10:41:48.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.902Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"covariant-return-type-java\",\"method-overriding-java\",\"java-clone-method-override\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Covariant Return Type in Java Explained with Example\",\"metaDescription\":\"Understand how covariant return types in Java let overridden methods return a narrower subclass type, avoiding downcasting, with a clone() example.\",\"metaKeywords\":null},\"content\":\"$104\"},{\"id\":214,\"title\":\"Running Infinite TimerTask in Java Servlet\",\"slug\":\"running-infinite-timertask-in-java-servlet\",\"excerpt\":\"This example will show you how to run Running Infinite TimerTask in Java Servlet. For achieving this we can initialise TimerTask inside ServletContextListener and schedule it for a certain time period. ServletContextListener is used to, make your code run before your web application started. For more understanding on ServletContextListener, refer my post on ServletContextListener Example in Servlet.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-07-02T07:32:03.000Z\",\"updatedDate\":\"2025-09-16T23:05:30.942Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/285/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"java-timertask\",\"servletcontextlistener\",\"java-timer-schedule\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$105\"},{\"id\":215,\"title\":\"ServletContextListener Example in Servlet\",\"slug\":\"servletcontextlistener-example-in-servlet\",\"excerpt\":\"This example explains how to use ServletContextListener in Servlets. ServletContextListener is used to, make your code run before your web application started. Below use case examples will help for more understanding.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-07-02T07:18:56.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.018Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/286/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"servletcontextlistener-example\",\"servlet-lifecycle\",\"java-web-app-listener\",\"tomcat-servlet\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$106\"},{\"id\":216,\"title\":\"How to set JAVA_HOME Environment Variable MacOS\",\"slug\":\"set-java_home-environment-variable-mac-os-x\",\"excerpt\":\"In this tutorial, we show you how to set $JAVA_HOME environment variable on your Mac OS X\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-06-23T09:30:35.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.061Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/287/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"java-home-mac\",\"set-environment-variable-macos\",\"bash-profile-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"\\nIn this tutorial, we show you how to set $JAVA\\\\_HOME environment variable on your Mac OS X.\\n\\n## Mac OSX 10.5.x or later\\n\\nOpen the Terminal program present in your (this is in your Ap
1plications/Utilities folder by default). Follow the below steps.\\n\\n### Step-1 Open and edit .bash\\\\_profile file\\n\\n```bash\\nopen -e .bash_profile\\n```\\n\\n### Step-2 Save the below line\\n\\n```bash\\nexport JAVA_HOME=$(/usr/libexec/java_home\\n```\\n\\n### Step-3 Refresh the file using below command\\n\\n```bash\\n$ source .bash_profile\\n```\\n\\n### Step-4 Check if the JAVA\\\\_HOME is set properly\\n\\n```bash\\n$ echo$JAVA_HOME\\n/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home\\n```\\n\\n## **For Older Mac OS X**\\n\\nFor older Mac OS X, you have to use the full path of installation directory as it /usr/libexec/java\\\\_home doesn’t exists.\\n\\n```bash\\n$ open -e .bash_profile\\n$ exportJAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home\\n$ source .bash_profile\\n\\n$ echo$JAVA_HOME\\n/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home\\n```\\n\"},{\"id\":220,\"title\":\"Setting ANDROID_HOME Environmental Variable on Mac\",\"slug\":\"setting-android_home-environmental-variable-on-mac\",\"excerpt\":\"In this tutorial, we will show you how to set ANDROID_HOME Environmental Variable on Mac OS X. Setting ANDROID_HOME environmental variable on mavericks Mac OS X Lion (10.7.5)\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-06-23T09:11:27.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.102Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-home-mac\",\"android-sdk-path-setup\",\"bash-profile-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$107\"},{\"id\":223,\"title\":\"Android Versions and API Levels\",\"slug\":\"android-versions-and-api-levels\",\"excerpt\":\"API Level is an integer value that indicates the Android framework API release versions for Android platform. Each revision made is assigned with a new incremental API Level value.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-31T11:21:19.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.294Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-api-level\",\"android-version-history\",\"android-sdk-versions\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Versions and API Levels Explained (Full Chart)\",\"metaDescription\":\"A complete reference table mapping Android platform versions to their API levels and VERSION_CODE names, from Android 1.0 through Android 5.0 Lollipop.\",\"metaKeywords\":null},\"content\":\"$108\"},{\"id\":224,\"title\":\"Progress Notification in Android Example\",\"slug\":\"progress-notification-in-android-example\",\"excerpt\":\"In this example we’ll show you how to display progress notification in android using NotificationManager class. For the sake of simplicity the below example shows an simple AsyncTask that does the background operation and update the progress bar displayed on android notification area.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-30T02:24:47.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.331Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-progress-notification\",\"notificationmanager-android\",\"android-asynctask-example\",\"android-notification-progressbar\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$109\"},{\"id\":225,\"title\":\"How to Use Hindi Font in Android Application\",\"slug\":\"how-to-use-hindi-font-in-android-application\",\"excerpt\":\"In this example we’ll show you how to support hindi, bangala, marathi fonts in Android application. Android phone doesn’t support Devanagari fonts. However if you want to use hindi, tamil, bangali or other Devanagari fonts in your Android Application you have an alternative of using external fonts.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-23T05:17:02.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.402Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"custom-font-android-textview\",\"hindi-font-android\",\"typeface-createfromasset\",\"devanagari-font-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Use Hindi Font in an Android Application\",\"metaDescription\":\"Learn how to add Hindi, Marathi, and other Devanagari fonts to a TextView in Android using a custom .ttf asset and Typeface.createFromAsset().\",\"metaKeywords\":null},\"content\":\"$10a\"},{\"id\":228,\"title\":\"Selection Sort Example In Data Structure\",\"slug\":\"selection-sort-example-data-structure\",\"excerpt\":\"A selection sort is slightly more complicated. but relatively easy to understand and to code. It is one of the slow sorting technique. Given an unsorted array of integer values, a selection sort visits each element of the array, in turn.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-22T11:19:28.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.433Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/299/thumbn
1ail.png\",\"topics\":[\"data-structures\"],\"tags\":[\"selection-sort-algorithm\",\"selection-sort-c-program\",\"sorting-algorithms\",\"data-structure-sorting\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$10b\"},{\"id\":229,\"title\":\"Bubble Sort Example In Data Structure\",\"slug\":\"bubble-sort-example-data-structure\",\"excerpt\":\"In this example, we will see Bubble sort algorithm with example. In bubble sort we’ll compare each element of list to the element that follows it. If the current element is greater than the element at next location, then they are in the wrong order, and we’ll swap them.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-22T11:09:32.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.472Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/300/thumbnail.png\",\"topics\":[\"data-structure\"],\"tags\":[\"bubble-sort-algorithm\",\"sorting-algorithm-example\",\"data-structures-basics\",\"bubble-sort-in-c\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Bubble Sort Algorithm Explained with Example\",\"metaDescription\":\"Learn how the bubble sort algorithm works step by step, including how elements are compared and swapped, plus its time complexity and pseudocode.\",\"metaKeywords\":null},\"content\":\"$10c\"},{\"id\":230,\"title\":\"Insertion Sort Example In Data Structure\",\"slug\":\"insertion-sort-example-in-data-structure\",\"excerpt\":\"In this example, we will see Insertion sort algorithm with example. An insertion sort is quite simple to understand and simple to implement. An insertion sort visits each element of the array, in turn. As it visits a particular element, it scans the array from the beginning to end to determines where in that segment of the array the current value belongs.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-22T10:47:29.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.517Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/301/thumbnail.png\",\"topics\":[\"data-structure\"],\"tags\":[\"insertion-sort-algorithm\",\"insertion-sort-data-structure\",\"insertion-sort-in-c\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Insertion Sort Example in Data Structure\",\"metaDescription\":\"Understand how the insertion sort algorithm works in data structures, with a step-by-step explanation, pseudocode, and a working C code example.\",\"metaKeywords\":null},\"content\":\"$10d\"},{\"id\":231,\"title\":\"Sorting Methods In Data Structures\",\"slug\":\"sorting-methods-in-data-structures\",\"excerpt\":\"Sorting is the problem of taking an arbitrary permutation of n items and rearranging them into the total order. Sorting algorithms are used in all kinds of applications and are necessary for instance, if we plan to use efficient searching algorithms like Binary Search or Interpolation Search since these require their data to be sorted.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-22T05:18
1:42.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.564Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/302/thumbnail.png\",\"topics\":[\"data-structures\"],\"tags\":[\"sorting-algorithms\",\"data-structures\",\"internal-vs-external-sorting\",\"algorithm-complexity\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$10e\"},{\"id\":233,\"title\":\"Sequential Search Algorithm in Data Structure\",\"slug\":\"sequential-search-algorithm-in-data-structure\",\"excerpt\":\"Sequential Search is the most natural searching method. In this method, the searching begins with searching every element of the list till the required record is found. It makes no demands on the ordering of records. It takes considerably amount of time and is slower.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-21T21:07:26.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.652Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/304/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"sequential-search-algorithm\",\"linear-search-c-program\",\"data-structure-searching\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$10f\"},{\"id\":234,\"title\":\"Searching Methods in Data Structure\",\"slug\":\"searching-methods-in-data-structure\",\"excerpt\":\"Searching methods are designed to take advantage of the file organisation and optimize the search for a particular record or to establish its absence. The file organisation and searching method chosen can make a substantial difference to an application’s performance.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-21T20:07:38.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.700Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/305/thumbnail.png\",\"topics\":[\"data-structures\"],\"tags\":[\"linear-search-algorithm\",\"binary-search-algorithm\",\"hash-table-search\",\"big-o-notation\",\"data-structure-searching\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$110\"},{\"id\":238,\"title\":\"Universal Image Loader Library in Android\",\"slug\":\"universal-image-loader-library-in-android\",\"excerpt\":\"Universal Image Loader is an smart and powerful library that helps in loading, caching and displaying images on Android. This means, using this library you can download remote images and display on ImageView.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-14T04:48:51.000Z\",\"updatedDate\":\"2025-09-16T23:05:31.934Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"universal-image-loader-android\",\"android-imageview-caching\",\"async-image-loading-android\",\"android-image-cache-library\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$111\"},{\"id\":242,\"title\":\"Android SQLite Database Tutorial\",\"slug\":\"android-sqlite-database-tutorial\",\"excerpt\":\"This tutorial describes how to use SQLite database in Android applications. It also demonstrates how to create new table, insert records, and modify records with example\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-07T13:25:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.053Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"sqliteopenhelper\",\"android-sqlite-crud\",\"android-todo-app\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android SQLite Database Tutorial: CRUD with a TODO App\",\"metaDescription\":\"Learn how to use SQLite in Android with SQLiteOpenHelper, building a complete TODO app that creates, reads, updates, and deletes database records.\",\"metaKeywords\":null},\"content\":\"$112\"},{\"id\":243,\"title\":\"Action Bar Tabs Example in Xamarin\",\"slug\":\"action-bar-tabs-example-in-xamarin\",\"excerpt\":\"This example explains “How to create Action Bar Tabs in Xamarin.Android”. This example uses Fragment in combination with…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-07T07:50:37.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.121Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"actionbar\",\"xamarin-tab-navigation\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Action Bar Tabs Example in Xamarin.Android\",\"metaDescription\":\"Learn how to add Action Bar tabs in Xamarin.Android using fragments, with a full code example for tab navigation and dynamic fragment switching.\",\"metaKeywords\":null},\"content\":\"$113\"},{\"id\":244,\"title\":\"ShareActionProvider Example in Xamarin.Android\",\"slug\":\"shareactionprovider-example-in-xamarin-android\",\"excerpt\":\"This example explains how to implement “s
1hare action in your action bar using ShareActionProvider class”. ActionProvider is made available since Android 4.0 (API Level 14). An ActionProvider, once attached to a menu item in the action bar, handles both the appearance and behavior of that item\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-05-05T08:24:29.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.187Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"shareactionprovider-android\",\"android-action-bar-share\",\"xamarin-android-menu\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$114\"},{\"id\":245,\"title\":\"How to Apply Shadow Effect on Android TextView\",\"slug\":\"how-to-apply-shadow-effect-on-android-textview\",\"excerpt\":\"This example explains how to apply Shadow Effect on Android TextView. You can apply Shadow Effect on Android TextView in two ways. Either we do it pragmatically or we can change in the xml layout.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-04-09T09:03:55.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.234Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-textview-shadow\",\"setshadowlayer\",\"android-textview-styling\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Apply Shadow Effect on Android TextView\",\"metaDescription\":\"Learn two ways to apply a shadow effect on Android TextView: via XML layout attributes or programmatically using the setShadowLayer() method.\",\"metaKeywords\":null},\"content\":\"$115\"},{\"id\":246,\"title\":\"Create and Manage a New Branch in Git\",\"slug\":\"create-and-manage-new-branch-in-git\",\"excerpt\":\"Useful git commands for creating and managing new branch in git.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-04-08T12:42:14.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.291Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/316/thumbnail.png\",\"topics\":[\"git\"],\"tags\":[\"git-branch-commands\",\"git-push-origin\",\"manage-git-branch\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Git Branch Commands: Create, Push, and Switch Branches\",\"metaDescription\":\"Useful git commands for creating a new branch, pushing it to a remote repository, and switching between branches during development.\",\"metaKeywords\":null},\"content\":\"$116\"},{\"id\":218,\"title\":\"If-then and if-then-else Statements in Java\",\"slug\":\"if-then-and-if-then-else-statements-in-java\",\"excerpt\":\"If-else statement in java is used for conditional checks for decision making. You can have multiple hierarchies of if-else statements. Once any of the if or else-if condition satisfies it executes the block of statements corresponding to it\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-04-06T09:45:18.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.499Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/319/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"java-if-else-statement\",\"java-conditional-statements\",\"if-else-if-example-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"If-Then and If-Then-Else Statements in Java Explained\",\"metaDescription\":\"Learn how if, else-if, and else statements work in Java for conditional decision making, with a step-by-step example comparing two numbers.\",\"metaKeywords\":null},\"content\":\"$117\"},{\"id\":248,\"title\":\"Switch-Case statement in Java\",\"slug\":\"switch-case-statement-in-java\",\"excerpt\":\"Switch case is another alternative for if-else statements. Switch case statement compares value in the object in the expression with the expressions associated with each case. A switch works only with primitive types like byte, short, char, and int and enumerated data types\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-03-20T01:11:21.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.547Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/321/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"java-switch-case-statement\",\"switch-case-string-java\",\"java-control-flow\",\"jdk7-string-switch\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$118\"},{\"id\":249,\"title\":\"YouTubePlayerView Example in Android Using YouTube API\",\"slug\":\"youtubeplayerview-example-in-android-using-youtube-api\",\"excerpt\":\"In this tutorial we’ll see how to use YouTube Player API in android. YouTube player API provided and embedded view that supports with various playback controls.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-03-12T22:37:45.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.621Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"youtubeplayerview-android\",\"youtube-data-api-v3\",\"youtube-android-player-api\",\"embed-youtube-video-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$119\"},{\"id\":250,\"title\":\"How to Remove Duplicate in ArrayList using Comparator\",\"slug\":\"how-to-remove-duplicate-in-arraylist-using-comparator\",\"excerpt\":\"This example shows how to remove duplicate from ArrayList using Comparator. The easiest way to remove duplicate is by passing the List to an Set. We will use Comparator to remove duplicate elements. Once you have the Set you can again pass it back to ArrayList.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-03-11T12:03:36.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.693Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"java-remove-duplicates-comparator\",\"java-treeset-comparator\",\"arraylist-deduplication-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Remove Duplicates from a Java ArrayList Using Comparator\",\"metaDescription\":\"Learn how to remove duplicate objects from a Java ArrayList by convert
1ing it to a TreeSet with a custom Comparator, with a full working example.\",\"metaKeywords\":null},\"content\":\"$11a\"},{\"id\":4,\"title\":\"Basic Java Language Constructs\",\"slug\":\"basic-java-language-constructs\",\"excerpt\":\"Java keywords There are over 50 reserved keywords in Java programming language. Keywords are the language construct has…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-03-10T19:46:58.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.723Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-keywords\",\"java-data-types\",\"java-comments\",\"java-interfaces-basics\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Basic Java Language Constructs: Keywords, Data Types\",\"metaDescription\":\"A beginner's overview of core Java language constructs, covering keywords, comments, data types, literals, classes, interfaces, and arrays.\",\"metaKeywords\":null},\"content\":\"$11b\"},{\"id\":252,\"title\":\"Introduction to Java, JVM and Writing Your Fist Java Program\",\"slug\":\"introduction-to-java-jvm\",\"excerpt\":\"Java is a high level, English like, object-oriented programming language with tons of APIS (application programming interface) for developing applications. Java is a platform independent language with support for performing complex computation, graphics, server and mobile application development. Java language syntax looks pretty much like C and C++, however there are some differences such as absence of pointers, allows writing object-oriented code. Learning Java is easy for\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-03-10T17:04:23.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.815Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-virtual-machine-jvm\",\"java-hello-world-program\",\"java-compilation-process\",\"jvm-bytecode-basics\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$11c\"},{\"id\":253,\"title\":\"How to Remove Duplicate Values From Java ArrayList\",\"slug\":\"how-to-remove-duplicate-values-from-java-arraylist\",\"excerpt\":\"This example shows how to remove duplicate from ArrayList. The easiest way to remove duplicate is by passing the List to an Set. As set doesn’t support duplicates it will omit the duplicate values. Once you have the Set you can again pass it back to ArrayList.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-03-06T13:47:21.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.842Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"java-arraylist-remove-duplicates\",\"java-hashset-vs-linkedhashset\",\"java-preserve-order-deduplication\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Remove Duplicate Values from a Java ArrayList\",\"metaDescription\":\"Learn how to remove duplicate values from a Java ArrayList using HashSet, and how to preserve insertion order instead with LinkedHashSet.\",\"metaKeywords\":null},\"content\":\"$11d\"},{\"id\":254,\"title\":\"Java Collection Complete Tutorial with Examples\",\"slug\":\"java-collection-complete-tutorial-and-examples\",\"excerpt\":\"In this tutorial we’ll see the core collection interface available in java and their behavior. Examples in each section will show you the implementation and usage of various collection interfaces.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-02-22T23:37:56.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.898Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-hashset-treeset-linkedhashset\",\"java-arraylist-linkedlist\",\"java-collection-examples\",\"java-set-list-interface\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$11e\"},{\"id\":255,\"title\":\"Java Exception Tutorial\",\"slug\":\"java-exceptions-tutorial\",\"excerpt\":\"Exception is an event during program execution that prevents the program from continuing normally.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-02-22T15:20:12.000Z\",\"updatedDate\":\"2025-09-16T23:05:32.930Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/332/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"checked-vs-unchecked-exceptions-java\",\"java-exception-hierarchy\",\"try-catch-finally-java\",\"java-error-handling\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$11f\"},{\"id\":256,\"title\":\"How to Start One Activity From Another in Xamarin Android\",\"slug\":\"how-to-start-one-activity-from-another-in-xamarin-android\",\"excerpt\":\"In this example we’ll look at how to create multiple activities and communicate between them. In this example we will create two activities and pass data between them.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-02-21T23:56:56.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.012Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"xamarin-android-startactivity\",\"xamarin-intent-putextra\",\"startactivityforresult-xamarin\",\"passing-data-between-activities\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Start One Activity From Another in Xamarin.Android\",\"metaDescription\":\"Learn how to start an activity from another in Xamarin.Android, pass data with Intent extras, and receive results back using StartActivityForResult.\",\"metaKeywords\":null},\"content\":\"$120\"},{\"id\":226,\"title\":\"Calculating factorial of number in Java\",\"slug\":\"java-programming-calculating-factorial
1-of-number\",\"excerpt\":\"This example below accepts number from user and calculates factorial using while loop and prints it.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-02-17T14:59:49.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.043Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"factorial-program-java\",\"java-while-loop\",\"java-scanner-input\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"\\nThis example below accepts number from user and calculates factorial using while loop and prints it.\\n\\n```java\\nimport java.util.Scanner;\\n\\npublic class Factorial {\\n\\n    public static void main(String[] args) {\\n        int number;\\n                int factorial = 1;\\n\\n        Scanner input = new Scanner(System.in);\\n\\n        //accept input from user\\n        System.out.println(\\\"Enter A Number :\\\");\\n        number = input.nextInt();\\n\\n        int i = 1;\\n\\n        // while loops\\n        while (i \u003c= number) {\\n            factorial = factorial * i;\\n            i++;\\n        }\\n\\n        System.out.println(\\\"Factorial is = \\\" + factorial);\\n    }\\n}\\n```\\n\\n### Output\\n\\n```text\\nEnter A Number :\\n6\\nFactorial is = 720\\n```\\n\"},{\"id\":239,\"title\":\"Drawing a pyramid using loops in Java\",\"slug\":\"java-programming-drawing-a-pyramid-using-loops\",\"excerpt\":\"Below example prints star like pyramid structure using loop in java.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-02-17T14:51:34.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.111Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"pyramid-pattern-java\",\"nested-for-loop-java\",\"star-pattern-program-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"\\nBelow example prints star like pyramid structure using loop in java.\\n\\n```java\\n public class Pyramid {\\n    // void main\\n    public static void main(String[] args) {\\n        int depth = 10;\\n        int s = depth, m;\\n\\n        for (int i = 1; i \u003c = depth; i++) {\\n            m = s;\\n            while (s \u003e 0) {\\n                System.out.print(\\\" \\\");\\n                s--;\\n            }\\n            for (int j = 1; j \u003c = i; j++) {\\n                System.out.print(\\\"* \\\");\\n            }\\n            System.out.print(\\\"\\\\n\\\");\\n            s = m - 1;\\n        }\\n    }\\n}\\n```\\n\\nOutput\\n\\n```text\\n          *\\n         * *\\n        * * *\\n       * * * *\\n      * * * * *\\n     * * * * * *\\n    * * * * * * *\\n   * * * * * * * *\\n  * * * * * * * * *\\n * * * * * * * * * *\\n```\\n\"},{\"id\":240,\"title\":\"Java Constructor Tutorial and Examples\",\"slug\":\"java-constructor-tutorial\",\"excerpt\":\"This is a tutorial explains how constructor works in Java. Constructor is an block of code which is executed before Object creation. Unlike methods constructors are getting called automatically.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-02-17T13:40:23.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.141Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-constructor-example\",\"constructor-overloading-java\",\"java-default-constructor\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$121\"},{\"id\":257,\"title\":\"CountDownLatch and Java Concurrency Example\",\"slug\":\"countdownlatch-and-java-concurrency-example\",\"excerpt\":\"CountDownLatch is one of the most usesful Java concept that helps tracking multiple threads execution. This is useful when you want one or more threads to wait until a set of operations being performed in other threads completes.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-02-16T23:18:18.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.170Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"countdownlatch-example\",\"java-concurrency-threads\",\"multithreading-synchronization-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"CountDownLatch in Java: Concurrency Example Explained\",\"metaDescription\":\"Learn how Java's CountDownLatch coordinates multiple threads, letting a main thread wait until worker threads finish, with a practical example.\",\"metaKeywords\":null},\"content\":\"$122\"},{\"id\":171,\"title\":\"Android Popup Menu Example\",\"slug\":\"android-popup-menu-example\",\"excerpt\":\"In example explains how to create Popup menu in android. Popup menu is used to display the global actions. Popup menu is an overflow menu like Spinner actions. PopupMenu is available from API level 11 (Android 3.0).\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-01-18T11:47:43.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.227Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-popupmenu\",\"popupmenu-example\",\"android-overflow-menu\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android PopupMenu Example: Show an Overflow Menu\",\"metaDescription\":\"Learn how to create and show a PopupMenu in Android, define menu items in XML, and handle item click events with a complete working example.\",\"metaKeywords\":null},\"content\":\"$123\"},{\"id\":172,\"title\":\"Share File to Dropbox in Android Example\",\"slug\":\"share-file-to-dropbox-in-android-example\",\"excerpt\":\"In this example we will see how to use Dropbox API to share Share file to Dropbox in from your native Android application.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-01-18T06:10:20.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.259Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"dropbox-sdk-android\",\"android-file-upload-dropbox\",\"dropbox-api-integration\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$124\"},{\"id\":258,\"title\":\"How to Drag a View in Android\",\"slug\":\"how-to-drag-a-view-in-android\",\"excerpt\":\"In this example we will see how to drag and ImageView in android on touch drag event.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-01-16T22:20:25.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.292Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-drag-view\",\"android-ontouchlistener\",\"drag-imageview-android\",\"android-motionevent\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Drag a View in Android\",\"metaDescription\":\"Learn how to make an ImageView draggable in Android by handling touch events with OnTouchListener and updating its layout margins.\",\"metaKeywords\":null},\"content\":\"$125\"},{\"id\":5,\"title\":\"How to Create an Android ListView with Section Header\",\"slug\":\"listview-with-section-header-in-android\",\"excerpt\":\"In this example we will show how to create a ListView with section header.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-01-16T11:36:46.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.324Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-listview-section-header\",\"baseadapter-getviewtypecount\",\"android-multiple-view-types-listview\",\"custom-adapter-section-list\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$126\"}
1,{\"id\":259,\"title\":\"Java TreeSet Example\",\"slug\":\"java-treeset-example\",\"excerpt\":\"In the following example, we will see how to use TreeSet Collection in java. This example includes, How to create an TreeSet, How to display element of Treeset, Adding data to TreeSet and Deleting data from TreeSet.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-01-15T21:11:45.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.355Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-treeset-example\",\"treeset-vs-treemap\",\"natural-ordering-java\",\"java-collections-tutorial\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$127\"},{\"id\":260,\"title\":\"ActionBar with Custom View Example in Android\",\"slug\":\"actionbar-with-custom-view-example-in-android\",\"excerpt\":\"In this example we will see how to customize ActionBar with Custom View in Android.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-01-15T13:46:39.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.420Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"actionbar-customview\",\"android-actionbar\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"ActionBar with Custom View Example in Android\",\"metaDescription\":\"Learn how to customize the Android ActionBar with a custom layout using setCustomView(), including XML layout and Activity code examples.\",\"metaKeywords\":null},\"content\":\"$128\"},{\"id\":261,\"title\":\"Edittext Validation in Android Example\",\"slug\":\"edittext-validation-in-android-example\",\"excerpt\":\"This tutorial show you how to use EditText user interface widget in android and write validation for the inputs. In this example we will create an simple Signup form as attached in the screenshot below.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-01-15T13:00:06.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.453Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-edittext-validation\",\"android-email-regex-validation\",\"android-signup-form\",\"edittext-set-error\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"EditText Validation in Android: Signup Form Example\",\"metaDescription\":\"Learn how to validate EditText input in Android with a simple signup form example covering email regex validation and password length checks.\",\"metaKeywords\":null},\"content\":\"$129\"},{\"id\":262,\"title\":\"How to convert UNIX date to String\",\"slug\":\"how-to-convert-unix-date-to-string\",\"excerpt\":\"In this post we will see how to convert unix date to human readable format, how to use SimpleDateFormat class for date conversion.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-01-14T08:27:53.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.497Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"unix-timestamp-to-date-java\",\"simpledateformat-java\",\"java-date-conversion\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Convert a UNIX Date to String in Java\",\"metaDescription\":\"Learn how to convert a UNIX timestamp to a human-readable date string in Java using SimpleDateFormat and Calendar with a working code example.\",\"metaKeywords\":null},\"content\":\"$12a\"},{\"id\":263,\"title\":\"Anatomy of Xamarin.Android Application\",\"slug\":\"anatomy-of-xamarin-android-application\",\"excerpt\":\"This tutorial explains the basic building blocks of Xamarin.Android application. 1. Activity Unlike other platform applications, Android application…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-01-07T08:42:50.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.530Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"activity-lifecycle\",\"android-intents\",\"android-content-providers\",\"android-broadcast-receivers\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Anatomy of a Xamarin.Android Application\",\"metaDescription\":\"Explore the core building blocks of a Xamarin.Android app, including Activities, Intents, the AndroidManifest, Services, Content Providers, and Broadcast Receivers.\",\"metaKeywords\":null},\"content\":\"$12b\"},{\"id\":264,\"title\":\"Creating HelloWorld Program in Xamarin.Android\",\"slug\":\"creating-helloworld-program-in-xamarin-android\",\"excerpt\":\"This tutorial explains step by step approach to create and deploy a Xamarin.Android application. For the sake of…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2014-01-07T08:39:20.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.585Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"xamarin\"],\"tags\":[\"xamarin-android-helloworld\",\"xamarin-android-project-structure\",\"xamarin-button-click-toast\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Creating a Hello World App in Xamarin.Android\",\"metaDescription\":\"A step-by-step guide to building your first Xamarin.Android app, covering project structure, layout XML, and handling a button click with a Toast.\",\"metaKeywords\":null},\"content\":\"$12c\"},{\"id\":265,\"title\":\"Android Input Dialog Example\",\"slug\":\"android-input-dialog-example\",\"excerpt\":\"In this tutorial we show you how to create input dialog in android with code sample. A dialog is a small window that prompts the user to make a decision or enter additional information.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-12-23T22:34:06.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.624Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-input-dialog\",\"alertdialog-edittext\",\"android-user-input-prompt\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Input Dialog Example with EditText\",\"metaDescription\":\"Learn how to build an Android input dialog using AlertDialog with a custom EditText layout to capture and display user text input.\",\"metaKeywords\":null},\"content\":\"$12d\"},{\"id\":266,\"title\":\"Android CheckBox Example\",\"slug\":\"android-checkbox-example\",\"excerpt\":\"In this tutorial we show you how to create checkbox in android with code sample. This example creates three checkbox and handles users input.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-12-22T21:50:05.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.692Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-checkbox\",\"checkbox-listener\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android CheckBox Example: Handle Click Events\",\"metaDescription\":\"Learn how to add checkboxes to an Android layout and handle user selection with a click listener, using a simple three-checkbox example.\",\"metaKeywords\":null},\"content\":\"$12e\"}
1,{\"id\":219,\"title\":\"Android Custom Dialog Example\",\"slug\":\"android-custom-dialog-example\",\"excerpt\":\"In this tutorial we show you how to create custom dialog in android. A dialog is a small window that prompts the user to make a decision or enter additional information.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-12-22T21:33:50.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.724Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-dialog\",\"custom-dialog-layout\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Custom Dialog Example with Custom Layout\",\"metaDescription\":\"Learn how to build a custom Android dialog using the Dialog class, attach a custom XML layout, and handle button clicks to show and dismiss it.\",\"metaKeywords\":null},\"content\":\"$12f\"},{\"id\":267,\"title\":\"Caching Bitmaps and Managing Bitmap Memory in Android- Official Video\",\"slug\":\"caching-bitmaps-and-managing-bitmap-memory-in-android-official-video\",\"excerpt\":\"Applications are enriched with graphics and images. But when your app have to load a number of bitmap, memory allocation will get complicated. Here is the official video lessons on caching bitmaps and managing bitmap memory in android.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-11-10T22:18:37.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.789Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-bitmap-caching\",\"bitmap-memory-management\",\"android-lrucache\",\"out-of-memory-android-images\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Caching Bitmaps and Managing Bitmap Memory in Android\",\"metaDescription\":\"Watch this official video guide on caching bitmaps and managing bitmap memory in Android to avoid out-of-memory crashes when loading images.\",\"metaKeywords\":null},\"content\":\"\\nApplications are enriched with graphics and images. But when your app have to load a number of bitmap, memory allocation will get complicated. Here is the official video lessons on caching bitmaps and managing bitmap memory in android. Here you will find below two points explained in detailed with a sample demo.\\n\\n**1. [Caching Bitmaps](http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html),** in this section you can learn how to use a memory and disk bitmap cache to improve the responsiveness and fluidity of your User Interface when loading multiple bitmaps.\\n\\n**2. [Managing Bitmap Memory](http://developer.android.com/training/displaying-bitmaps/manage-memory.html),** this section you will see more on how to facilitate garbage collection and reuse bitmaps more effectively.\\n\\nIn this video tutorial you will also get an overview of, how to speed up bitmap loading and reduce garbage collection by reusing existing bitmaps.\\n\\n{{\u003c youtube rsQet4nBVi8 \u003e}}\\n\"},{\"id\":268,\"title\":\"Android ImageView Example\",\"slug\":\"android-imageview-example\",\"excerpt\":\"ImageView is one of the UI widget that is used to display images in your Application. ImageView is comes with different configuration options to support different scaleTypes.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-11-10T21:12:54.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.818Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-imageview\",\"imageview-scaletype\",\"android-setimageresource\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android ImageView Example: ScaleTypes and Usage\",\"metaDescription\":\"Learn how to use Android ImageView with different scaleType options, set images dynamically with setImageResource(), and handle click events.\",\"metaKeywords\":null},\"content\":\"$130\"},{\"id\":269,\"title\":\"Integrating Google Analytics in Android Example\",\"slug\":\"integrating-google-analytics-in-android-example\",\"excerpt\":\"Analytics is one of the major parts in applications that drive revenue. Mobile App Analytics help you set and track the goal conversions you want most: purchases, clicks, or simply time spent on your app. It is required to make business inclined towards user’s interest.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-11-10T20:30:47.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.851Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"google-analytics-android\",\"easytracker-android\",\"android-event-tracking\",\"android-crash-reporting\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$131\"},{\"id\":270,\"title\":\"Android Handler Example\",\"slug\":\"android-handler-example\",\"excerpt\":\"In this example we will see how to use Handler in android. This example downloads image from server and using Handler it is communicating back with UI thread.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-11-05T11:26:47.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.878Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-handler\",\"background-thread-ui\",\"message-queue\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Handler Example: Update UI from Backgroun
1d Thread\",\"metaDescription\":\"Learn how to use Android's Handler class to communicate from a background thread to the UI thread, with an example that downloads and displays an image.\",\"metaKeywords\":null},\"content\":\"$132\"},{\"id\":271,\"title\":\"Get Device ID Example in Android\",\"slug\":\"get-device-id-example-in-android\",\"excerpt\":\"This example explains how to get device unique id in android. The device unique id is needed when we want user registration for a specific device. This way we can achieve security. Most of the banking applications today are using such approach.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-11-01T09:08:32.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.904Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-device-id\",\"android-secure-android-id\",\"unique-device-identifier-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Get a Unique Device ID in Android\",\"metaDescription\":\"Learn how to retrieve a unique device ID in Android using Settings.Secure.ANDROID_ID, useful for device-based user registration and security.\",\"metaKeywords\":null},\"content\":\"$133\"},{\"id\":272,\"title\":\"Listing all SDCard Filenames with extensions in android\",\"slug\":\"listing-all-sdcard-filenames-with-extensions-in-android\",\"excerpt\":\"Here in this example we will see how to list all files present in SDCard of your android device. In the below example it searches for all of the SDCard folders and lists all of the images available. You may extend this example to list other file formats\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-11-01T02:14:26.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.932Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-list-sdcard-files\",\"android-file-listing-recursive\",\"android-external-storage-files\",\"list-image-files-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$134\"},{\"id\":273,\"title\":\"Navigation Drawer Android Example\",\"slug\":\"navigation-drawer-android-example\",\"excerpt\":\"The navigation drawer is a panel that displays the app’s main navigation commands on the left side of the screen. This example describes How to implement a navigation drawer using Support Library the DrawerLayout API.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-10-16T07:13:59.000Z\",\"updatedDate\":\"2025-09-16T23:05:33.958Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-navigation-drawer\",\"drawerlayout-android\",\"actionbardrawertoggle\",\"android-fragment-navigation\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$135\"},{\"id\":284,\"title\":\"Best IDE for Grails/Groovy – NetBeans, Spring or IntelliJ?\",\"slug\":\"best-ide-for-grails-groovy-netbeans-spring-or-intellij\",\"excerpt\":\"Integrated development environment (IDE) brings a whole host of features like auto complete, re-factoring source control and more for the developers. However, when it comes to Groovy and Grails, it becomes crucial for the developers to choose the right kind of IDE to improve the productivity on the go.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-09-06T08:26:43.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.313Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"blog\"],\"tags\":[\"grails-ide-comparison\",\"groovy-grails-development\",\"intellij-for-grails\",\"spring-tool-suite\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Best IDE for Grails/Groovy: NetBeans vs STS vs IntelliJ\",\"metaDescription\":\"Compare NetBeans, Spring Tool Suite, IntelliJ IDEA, and the Groovy/Grails Tool Suite for Eclipse to find the best IDE for your Grails and Groovy projects.\",\"metaKeywords\":null},\"content\":\"$136\"},{\"id\":288,\"title\":\"How to Start an Application at Device Bootup in Android\",\"slug\":\"how-to-start-an-application-at-device-bootup-in-android\",\"excerpt\":\"This tutorial will explain to stat an application while the Android device boot-up. For this we need to listen to the BOOT_COMPLETED action and react to it. BOOT_COMPLETED is a Broadcast Action that is broadcast once, after the system has finished booting.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-09-05T07:46:21.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.600Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"boot-completed-broadcast-receiver\",\"android-autostart-on-boot\",\"android-broadcastreceiver-example\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Start an App at Device Bootup in Android\",\"metaDescription\":\"Learn how to auto-start an Android app on device bootup using a BroadcastReceiver that listens for the BOOT_COMPLETED action, with full manifest setup.\",\"metaKeywords\":null},\"content\":\"$137\"},{\"id\":289,\"title\":\"TextSwitcher and ImageSwitcher Example in Android\",\"slug\":\"textswitcher-and-imageswitcher-example-in-android\",\"excerpt\":\"The TextSwitcher and ImageSwitcher methods give you a simple way to add animated transitions. TextSwitcher and ImageSwitcher are used to have an smooth transition animation in android view.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-09-02T12:04:33.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.635Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-textswitcher-example\",\"android-imageswitcher-example\",\"viewswitcher-animation-android\",\"android-view-transition-animation\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$138\"},{\"id\":290,\"title\":\"Creating Custom Views in Android Tutorial\",\"slug\":\"creating-custom-views-in-android-tutorial\",\"excerpt\":\"This tutorials describes how to create custom Views in Android.In this example we will create a custom view with two TextView. One to the left and other to the right as pairs. The custom styles can be configured from xml.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-09-01T07:42:09.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.664Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-custom-view\",\"custom-styleable-attributes\",\"android-attrs-xml\",\"obtainstyledattributes\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Creating Custom Views in Android: Step-by-Step Tutorial\",\"metaDescription\":\"Learn how to build a custom Android View with styleable XML attributes, obtainStyledAttributes(), and a reusable two-TextView layout example.\",\"metaKeywords\":null},\"content\":\"$139\"},{\"id\":291,\"title\":\"Android Include Tag Layout Example\",\"slug\":\"android-include-tag-layout-example\",\"excerpt\":\"In this example, you’ll learn how to use the tag in your XML to avoid replication of views. When you’re creating complex layouts, you may find yourself adding a lot of ViewGroup’s and Views. But, making your view hierarchy tree taller will also result in slowness in your application.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-09-01T04:09:46.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.693Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-include-tag\",\"reusable-layout-android\",\"android-layout-optimization\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Include Tag: Reuse Layouts in XML\",\"metaDescription\":\"Learn how to use the Android \u003cinclude\u003e tag to reuse XML layouts like a shared footer across multiple screens and avoid duplicating view code.\",\"metaKeywords\":null},\"content\":\"$13a\"},{\"id\":292,\"title\":\"How To Send Email In Android\",\"slug\":\"how-to-send-email-in-android\",\"excerpt\":\"The code sample below will help you understand “How To Send Email In Android” using EmailIntent in android. In…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-29T12:09:38.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.720Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-email-intent\",\"intent-action-send-android\",\"android-email-client-chooser\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Send Email in Android Using Intent\",\"metaDescription\":\"Learn how to send an email in Android with Intent.ACTION_SEND, build a simple c
1ompose UI, and launch an email client chooser with working code.\",\"metaKeywords\":null},\"content\":\"$13b\"},{\"id\":294,\"title\":\"Android Seekbar Example\",\"slug\":\"android-seekbar-example\",\"excerpt\":\"SeekBar is one of the useful user interface element in android applications. SeekBar is an extension of ProgressBar that allows the selection of integer values using a natural user interface. Basically SeekBar has a thumb that you can slide to choose a value between 0 and some maximum that you set. A typical usage of Seekbar is your device brightness control and volume control\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-28T11:59:38.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.791Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-seekbar\",\"onSeekBarChangeListener\",\"custom-seekbar-drawable\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android SeekBar Example: Custom Style and Listener\",\"metaDescription\":\"Learn how to create and customize an Android SeekBar with a custom drawable, and handle progress changes using OnSeekBarChangeListener.\",\"metaKeywords\":null},\"content\":\"$13c\"},{\"id\":295,\"title\":\"How to Turn off, Turn on Wifi in Android\",\"slug\":\"how-to-turn-off-turn-on-wifi-in-android\",\"excerpt\":\"The following code snippet will help you to pragmatically turn on and turn off wi-fi in android. This sample code is using android Switch (Available from android API level 14) to toggle between wi-fi state.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-25T12:26:24.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.823Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/advance-android-tutorials/tree/master/android-turn-wifi-on-off\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-wifimanager\",\"toggle-wifi-android\",\"android-wifi-switch\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Turn Wi-Fi On and Off in Android Programmatically\",\"metaDescription\":\"Learn how to toggle Wi-Fi on and off in Android using WifiManager and a Switch widget, with full layout and activity code examples.\",\"metaKeywords\":null},\"content\":\"$13d\"},{\"id\":296,\"title\":\"How to Get List of Installed Apps in Android\",\"slug\":\"how-to-get-list-of-installed-apps-in-android\",\"excerpt\":\"Android PackageManager class is used to retrieve information on the application packages that are currently installed on the device. You can get an instance of PackageManager class by calling getPackageManager().\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-25T09:44:39.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.889Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-packagemanager\",\"list-installed-apps-android\",\"android-listview-adapter\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Get List of Installed Apps in Android\",\"metaDescription\":\"Learn how to use Android's PackageManager to list installed apps with a custom ListView adapter showing app icons, names, and package details.\",\"metaKeywords\":null},\"content\":\"$13e\"},{\"id\":297,\"title\":\"Starting an Android Activity for Result\",\"slug\":\"starting-an-activity-for-a-result\",\"excerpt\":\"In Android user interface is displayed through an activity. Activity is used to represent the data to user and allows user interaction. In an android application, we can have multiple activities and that can interact with each other. This tutorial I will explain more about, how to switch between one Activity to another.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-25T05:27:56.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.934Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"startactivityforresult-android\",\"android-activity-result\",\"android-intent-communication\",\"onactivityresult-callback\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$13f\"},{\"id\":298,\"title\":\"How to Pass a Data from One Activity to Another in Android\",\"slug\":\"pass-a-data-from-one-activity-to-another-in-android\",\"excerpt\":\"In Android user interface is displayed through an activity. Activity is used to represent the data to user and allows user interaction. In an android application, we can have multiple activities and that can interact with each other. During activity interaction we might required to pass data from one activity to other. This tutorial I 
1will explain more about, how to send data while switching between one Activity to another.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-25T01:32:58.000Z\",\"updatedDate\":\"2025-09-16T23:05:34.995Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"pass-data-between-activities-android\",\"android-intent-putextra\",\"android-bundle-example\",\"android-intent-tutorial\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$140\"},{\"id\":299,\"title\":\"How to create a HTTP adapter in IBM Worlight\",\"slug\":\"how-to-create-a-http-adapter-in-ibm-worlight\",\"excerpt\":\"This tutorial explains how to create a HTTP adapter in IBM Worlight and easy steps to deploy on…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-23T12:48:50.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.023Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"blog\"],\"tags\":[\"worklight-http-adapter\",\"worklight-adapter-xml\",\"wl-server-invokehttp\",\"worklight-rest-integration\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Create an HTTP Adapter in IBM Worklight\",\"metaDescription\":\"Step-by-step guide to creating and deploying an HTTP adapter in IBM Worklight, including adapter XML configuration and invoking a REST procedure.\",\"metaKeywords\":null},\"content\":\"$141\"},{\"id\":300,\"title\":\"Invoking Adapter procedure in IBM Worklight\",\"slug\":\"invoking-adapter-procedure-in-ibm-worklight\",\"excerpt\":\"This tutorial will help you to understand the Adapters in IBM Worklight and Invoking Adapter procedure in IBM…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-22T14:15:17.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.049Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"blog\"],\"tags\":[\"ibm-worklight-adapter\",\"wl-client-invokeprocedure\",\"worklight-sql-adapter\",\"mobile-enterprise-adapter\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$142\"},{\"id\":301,\"title\":\"Struts2 Localization and Internationalization Example\",\"slug\":\"struts2-localization-example\",\"excerpt\":\"This tutorial will explain Struts2 Localization, internationalization (i18n) with Example. We will build a sample internationalized web application with support for English, French and Japanese.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-21T08:26:39.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.116Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/390/thumbnail.png\",\"topics\":[\"struts2\"],\"tags\":[\"struts2-internationalization\",\"struts2-localization-i18n\",\"resource-bundle-properties\",\"multilingual-web-application\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$143\"},{\"id\":302,\"title\":\"Android Gridview Example- Building Image Gallery in android\",\"slug\":\"android-gridview-example-building-image-gallery-in-android\",\"excerpt\":\"GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. In this tutorial, we’ll build an Image Gallery using a GridView in android. Each grid to display an image thumbnails and a text. While an item is selected, a toast message will display the position of the grid selected.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-20T14:21:30.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.157Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"gridview\",\"image-gallery\",\"custom-adapter\",\"arrayadapter\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android GridView Example: Build an Image Gallery\",\"metaDescription\":\"Learn how to build an image gallery in Android using GridView, a custom ArrayAdapter, and item click handling to open a full-size details view.\",\"metaKeywords\":null},\"content\":\"$144\"},{\"id\":275,\"title\":\"Creating SQL Adapter in IBM Worklight\",\"slug\":\"creatin-a-sql-adapter-in-ibm-worklight\",\"excerpt\":\"This tutorial will help you to understand the SQL adapter and to create a SQL adapter from IBM…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-18T07:48:44.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.187Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"blog\"],\"tags\":[\"ibm-worklight-sql-adapter\",\"worklight-adapter-tutorial\",\"mysql-jdbc-adapter\",\"hybrid-mobile-backend\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Create a SQL Adapter in IBM Worklight\",\"metaDescription\":\"Step-by-step guide to creating, configuring, and testing a SQL adapter in IBM Worklight, including MySQL JDBC setup and defining Worklight procedures.\",\"metaKeywords\":null},\"content\":\"$145\"}
1,{\"id\":173,\"title\":\"Java enum Programming Tutorial\",\"slug\":\"java-enum-programming-tutorial\",\"excerpt\":\"An enumeration is a special class, which provides a type-safe implementation of constant data in a java program. Java enum type is introduced in Java 2.0. It is used to restrict a variable only a predefined values from an enumerated list. The items in the enumerated list are called enums.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-17T00:13:28.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.215Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-enum-tutorial\",\"enum-type-safety-java\",\"declaring-enum-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$146\"},{\"id\":68,\"title\":\"Java String Complete Tutorial\",\"slug\":\"java-string-complete-tutorial\",\"excerpt\":\"Strings are sequence of characters. In the Java programming language, strings are objects. The Java platform provides the…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-15T12:18:44.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.250Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-string-immutability\",\"string-pool-java\",\"string-comparison-java\",\"string-format-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$147\"},{\"id\":127,\"title\":\"How to Convert POJO to XML in Android\",\"slug\":\"how-to-convert-pojo-to-xml-in-android\",\"excerpt\":\"POJO is an acronym for Plain Old Java Object, basically a class with attributes and it’s getters and…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-11T09:20:32.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.322Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"pojo-to-xml-java\",\"xmlserializer-android\",\"android-xml-serialization\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Convert POJO to XML in Android Using XmlSerializer\",\"metaDescription\":\"Learn how to convert a POJO to XML in Android using XmlSerializer, with a full example that reads object fields and generates XML tags in order.\",\"metaKeywords\":null},\"content\":\"$148\"},{\"id\":303,\"title\":\"Login Application using Struts2 Tutorial\",\"slug\":\"creating-login-application-using-struts2\",\"excerpt\":\"This example explains step by step tutorials for building Login Application using Struts2 Java Framework. The login workflow…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-09T06:26:17.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.412Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/396/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"struts2-login-application\",\"struts2-actionsupport\",\"struts-xml-configuration\",\"struts2-interceptor\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Struts2 Login Application Tutorial with Example\",\"metaDescription\":\"Learn how to build a login application in Struts2, covering web.xml setup, ActionSupport validation, struts.xml configuration, and JSP login pages.\",\"metaKeywords\":null},\"content\":\"$149\"},{\"id\":304,\"title\":\"Android Radio Button Example\",\"slug\":\"android-radio-button-example\",\"excerpt\":\"In this tutorial, we show you how to use radio button in android using example. RadioButton is a…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-03T06:17:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.507Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-radiobutton\",\"radiogroup-example\",\"onCheckedChangeListener\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android RadioButton Example with RadioGroup\",\"metaDescription\":\"Learn how to use RadioButton and RadioGroup in Android, handle selection changes with OnCheckedChangeListener, and clear or submit selections.\",\"metaKeywords\":null},\"content\":\"$14a\"},{\"id\":305,\"title\":\"Android Menu Example\",\"slug\":\"android-menu-example\",\"excerpt\":\"This tutorial explains how to create menu in android with example. Menus are a common user interface component…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-03T05:50:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.539Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-options-menu\",\"onCreateOptionsMenu\",\"android-menu-xml\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Menu Example: Options Menu with XML and Java\",\"metaDescription\":\"Learn how to create an Android options menu using XML declarations, inflate it with onCreateOptionsMenu, and handle item clicks in your activity.\",\"metaKeywords\":null},\"content\":\"$14b\"},{\"id\":307,\"title\":\"Android Button Example\",\"slug\":\"android-button-example\",\"excerpt\":\"This tutorial explains how to use Button widget in Android. The examples used in this tutorial, will show you how to create different button layout such as normal button, image button, button with image and text, etc.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-08-03T03:05:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.640Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"button\",\"button-styling\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Button Example: Create and Style Buttons\",\"metaDescription\":\"Learn how to create Android buttons in XML, handle click events in your Activity, and style buttons with custom colors, icons, and backgrounds.\",\"metaKeywords\":null},\"content\":\"$14c\"}
1,{\"id\":308,\"title\":\"How to Programmatically Zip and Unzip File in Android\",\"slug\":\"how-to-programmatically-zip-and-unzip-file-in-android\",\"excerpt\":\"This tutorial explains “How to Programmatically Zip and Unzip File in Android”. Zipping means writting (compress) data into zip files. Below code snippet will help you to zip and unzip files using a generic wrapper class that allows you to easily zip files in Android.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-07-30T07:44:37.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.710Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-zip-unzip-file\",\"android-zipoutputstream\",\"java-ziputils-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Zip and Unzip Files Programmatically in Android\",\"metaDescription\":\"Learn how to zip and unzip files in Android using a reusable ZipManager wrapper class built on ZipOutputStream and ZipInputStream.\",\"metaKeywords\":null},\"content\":\"$14d\"},{\"id\":311,\"title\":\"Searching arrays and collections in java\",\"slug\":\"searching-arrays-and-collections-in-java\",\"excerpt\":\"Arrays and Collection class provides methods that allows to search a specific element in the list. Things to…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-07-28T09:13:10.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.848Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-array-search\",\"binary-search-java\",\"java-collections-search\",\"arrays-binarysearch\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$14e\"},{\"id\":314,\"title\":\"Using Static Import in Java\",\"slug\":\"using-static-import-in-java\",\"excerpt\":\"To import a specific member inside your java source file, put an import statement at the beginning of…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-07-28T07:56:42.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.909Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"static-import-java\",\"java-import-static-members\",\"java-static-import-example\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$14f\"},{\"id\":315,\"title\":\"Creating Drop Down List Using Android Spinner\",\"slug\":\"android-spinner-example\",\"excerpt\":\"This tutorial explains creating spinner in android and attaching event to spinner in android. Here in this tutorial, you’ll create a Simple spinner widget that displays a list of countries and shows appropriate flag as per selected country from the spinner.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-07-26T03:18:13.000Z\",\"updatedDate\":\"2025-09-16T23:05:35.937Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-spinner\",\"spinner-dropdown-list\",\"onItemSelectedListener\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Spinner Example: Dropdown List with Images\",\"metaDescription\":\"Learn how to create an Android Spinner dropdown list of countries that updates an ImageView with the matching flag using OnItemSelectedListener.\",\"metaKeywords\":null},\"content\":\"$150\"},{\"id\":317,\"title\":\"Android ViewFlipper Example- Creating Image Slideshow Using ViewFlipper\",\"slug\":\"android-viewflipper-example\",\"excerpt\":\"ViewFlipper is and user interface widget available in android since android API level 1. It can hold two more views, but only one child can be shown at a time. Using this we can implement functionality similar to android gallery item, swiping allows to navigate between images.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-07-25T06:23:07.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.003Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-viewflipper\",\"image-slideshow-android\",\"swipe-gesture-detector\",\"viewflipper-auto-flip\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android ViewFlipper Example: Build an Image Slideshow\",\"metaDescription\":\"Learn how to use Android ViewFlipper to build a swipeable image slideshow with auto-flip, custom animations, and gesture detection, complete with code.\",\"metaKeywords\":null},\"content\":\"$151\"}
1,{\"id\":318,\"title\":\"ProgressBar while Loading WebView in Android\",\"slug\":\"progressbar-while-loading-webview\",\"excerpt\":\"This tutorial demonstrate the usage of ProgressBar while Loading WebView contents in android. This example explains horizontal ProgressBar and ProgressBar dialog with WebView. Progressbar is a visual indicator of progress in some operation.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-07-24T06:28:44.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.044Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-webview-progressbar\",\"webchromeclient-example\",\"android-webview-loading-indicator\",\"indeterminate-progressbar-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$152\"},{\"id\":319,\"title\":\"Using External Fonts in Android View\",\"slug\":\"using-external-fonts-in-android-view\",\"excerpt\":\"This tutorial explains example for using external fonts in Android View. Android applications are capable of loading the external font files with .ttf extension.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-07-19T08:51:33.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.102Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"custom-font-android-textview\",\"typeface-createfromasset\",\"android-ttf-font-assets\",\"custom-textview-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$153\"},{\"id\":320,\"title\":\"Handler and AsyncTask in Android\",\"slug\":\"handler-and-asynctask-in-android\",\"excerpt\":\"Handler and AsyncTasks are way to implement multithreading in android with UI/Event Thread. Handler is available since Android…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-07-17T12:37:58.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.139Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-handler-class\",\"android-asynctask-multithreading\",\"android-ui-thread-messaging\",\"android-post-runnable\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Handler vs AsyncTask in Android: Key Differences\",\"metaDescription\":\"Learn the difference between Handler and AsyncTask in Android for multithreading, including how each schedules work on and off the UI thread.\",\"metaKeywords\":null},\"content\":\"$154\"},{\"id\":322,\"title\":\"Image Picker Using Intent.ACTION_PICK in Android\",\"slug\":\"writing-image-picker-using-intent-in-android\",\"excerpt\":\"Android supports seamless integration of applications and content providers. Lot many things are handy provided to developers, which…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-07-05T13:49:24.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.213Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"intent-action-pick\",\"android-image-picker\",\"pick-image-from-gallery-android\",\"android-oncreateoptionsmenu\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$155\"},{\"id\":324,\"title\":\"Different Way to Handle Events in Android\",\"slug\":\"different-way-to-handle-events-in-android\",\"excerpt\":\"Typically events do responds to user interactions. Android platform supports multiple ways to handle the events on View’s.…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-06-24T12:45:04.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.264Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-onclicklistener\",\"android-event-handling\",\"android-onclick-xml-attribute\",\"android-view-click-events\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"4 Ways to Handle Click Events in Android\",\"metaDescription\":\"Compare four ways to handle View click events in Android: anonymous listeners, the onClick XML attribute, Activity interfaces, and listener fields.\",\"metaKeywords\":null},\"content\":\"$156\"},{\"id\":325,\"title\":\"Homescreen App Widgets Example in Android\",\"slug\":\"app-widgets-example-in-android\",\"excerpt\":\"In this example we will learn about creating a simple 4×2 home screen App widget using an App…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-06-23T12:41:23.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.291Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-app-widget\",\"appwidgetprovider\",\"home-screen-widget\",\"android-remoteviews\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android App Widgets Tutorial: Build a Home Screen Widget\",\"metaDescription\":\"Learn how to build a home screen App Widget in Android using AppWidgetProvider and RemoteViews, including layout XML, button clicks, and update broadcasts.\",\"metaKeywords\":null},\"content\":\"$157\"},{\"id\":326,\"title\":\"JSON Feed Reader in Android\",\"slug\":\"json-feed-reader-in-android\",\"excerpt\":\"In the course of this tutorial, we will take step by step look into building a JSON feed…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-06-16T13:28:50.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.328Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-json-parsing\",\"asynctask-download-json\",\"android-listview-webview\",\"share-intent-android\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$158\"},{\"id\":312,\"title\":\"Android TextToSpeech Example\",\"slug\":\"android-texttospeech-example\",\"excerpt\":\"Android is called one among the very advanced operating system in providing cool features out of box. It supports convert
1ing Text-To-Speech (TTS) or also known as speech synthesis. It is introduced from android 1.6, API level 4. Text-To-Speech enables your Android device to speak text of different languages.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-06-11T07:31:47.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.356Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-texttospeech\",\"tts-android-example\",\"android-speech-synthesis\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android TextToSpeech Example: Convert Text to Speech\",\"metaDescription\":\"Learn how to implement Android TextToSpeech (TTS) with a reusable TTSManager class, handle language initialization, and queue multiple utterances.\",\"metaKeywords\":null},\"content\":\"$159\"},{\"id\":329,\"title\":\"Loading Image Asynchronously in Android ListView\",\"slug\":\"loading-image-asynchronously-in-android-listview\",\"excerpt\":\"In this tutorial, we will create a simple ListView in Android that downloads data asynchronously from the internet using a AsyncTask. AsyncTask enables you to implement MultiThreading without getting your hands dirty into threads. AsyncTask is easy to use, and it allows performing background operation in dedicated thread and passing the results back UI thread.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-06-01T13:01:07.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.407Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"asynctask-image-download\",\"android-listview-lazy-loading\",\"httpurlconnection-bitmap-download\",\"android-listview-thumbnail-images\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$15a\"},{\"id\":330,\"title\":\"How to sort an ArrayList in java\",\"slug\":\"how-to-sort-an-arraylist-in-java\",\"excerpt\":\"ArrayList are also called as dynamic arrays that can grow as needed. In Java ArrayList class extends AbstractList…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-05-24T06:20:13.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.433Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-arraylist-sort\",\"collections-sort-java\",\"comparable-vs-comparator\",\"sort-objects-in-arraylist\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Sort an ArrayList in Java: 3 Methods Explained\",\"metaDescription\":\"Learn how to sort an ArrayList in Java using Collections.sort(), the Comparable interface, and custom Comparator objects, with complete code examples.\",\"metaKeywords\":null},\"content\":\"$15b\"},{\"id\":331,\"title\":\"How To Loop ArrayList In Java\",\"slug\":\"how-to-loop-arraylist-in-java\",\"excerpt\":\"In this tutorial we will see How To Loop ArrayList In Java in different ways. Below example will loop through ArrayList and…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-05-22T20:21:59.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.463Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-arraylist-loop\",\"java-iterator\",\"for-loop-vs-iterator-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"How to Loop Through an ArrayList in Java (4 Ways)\",\"metaDescription\":\"Learn four ways to loop through an ArrayList in Java: regular for loop, enhanced for loop, while loop, and Iterator, with a complete code example.\",\"metaKeywords\":null},\"content\":\"$15c\"},{\"id\":332,\"title\":\"Creating Frame by Frame Animations in Android\",\"slug\":\"creating-frame-animations-in-android\",\"excerpt\":\"This example explains step by step process to create Frame Animations in Android. An animation created by moving an object little-by-little over several consecutive frames.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-05-19T07:25:36.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.515Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-frame-by-frame-animation\",\"animationdrawable-android\",\"android-animation-list-xml\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Creating Frame-by-Frame Animations in Android\",\"metaDescription\":\"Step-by-step guide to building frame-by-frame animations in Android using AnimationDrawable, an animation-list XML, and start/stop controls.\",\"metaKeywords\":null},\"content\":\"$15d\"},{\"id\":333,\"title\":\"Installing Android Studio\",\"slug\":\"installing-android-studio\",\"excerpt\":\"Android Studio is an IDE based on IntelliJ IDEA used for android application development. It is released on 15th may 2013. This tool has more options for Android Development, making the process faster and more productive. A “live layout” was shown that renders your app as you’re editing in real-time. In this tutorial you can learn steps for Installing Android Studio.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-05-19T05:08:19.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.544Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"install-android-studio\",\"android-studio-no-jdk-found-error\",\"android-sdk-setup\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Installing Android Studio: Setup and Common Fixes\",\"metaDescription\":\"Learn the steps for installing Android Studio and how to fix common setup issues like the No JDK found error and outdated Android SDK templates.\",\"metaKeywords\":null},\"content\":\"$15e\"},{\"id\":334,\"title\":\"Android Studio Features\",\"slug\":\"android-studio-features\",\"excerpt\":\"This tutorial explains Android Studio Features and Installation steps. Android Studio is an IDE based on IntelliJ IDEA used for android application development.…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-05-19T04:07:08.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.604Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-studio-ide\",\"intellij-idea-android\",\"gradle-build-support\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Studio Features: A Complete Overview\",\"metaDescription\":\"Explore Android Studio's key features, including Gradle build supp
1ort, the rich layout editor, Lint tools, and code analysis for Android development.\",\"metaKeywords\":null},\"content\":\"$15f\"},{\"id\":335,\"title\":\"Android Toast Example\",\"slug\":\"android-toast-example\",\"excerpt\":\"In this tutorial we will explain how to work with Android Toast with example. The example below demonstrates…\",\"difficulty\":\"beginner\",\"publishedDate\":\"2013-05-12T13:44:20.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.634Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/android-ui-tutorials/tree/master/android-simple-listview\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-toast\",\"custom-toast-android\",\"toast-makeText\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Toast Example: Simple and Custom Toast Messages\",\"metaDescription\":\"Learn how to show Toast messages in Android using Toast.makeText(), change their position with setGravity(), and build a custom Toast layout with your own view.\",\"metaKeywords\":null},\"content\":\"$160\"},{\"id\":336,\"title\":\"Android WebView Example\",\"slug\":\"android-webview-example\",\"excerpt\":\"In the course of this tutorial, we will teach you how to use Android WebView and answer to some of the most common questions on android WebView. Android WebView is an embedded browser that can render static HTML data or even remote URL. A WebView is an android UI component that displays webpages.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-05-10T12:14:55.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.706Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-webview\",\"webviewclient\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android WebView Example: Load HTML and URLs In-App\",\"metaDescription\":\"Learn how to use Android WebView to load static HTML or remote URLs, override link handling with WebViewClient, and keep browsing inside your app.\",\"metaKeywords\":null},\"content\":\"$161\"},{\"id\":337,\"title\":\"Android ListView Example\",\"slug\":\"android-listview-tutorial\",\"excerpt\":\"This post will walk you through building simple and customized ListView in Android using different Android adapters. ListView is a view group that, displays a list of scrollable items.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-05-06T13:16:04.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.741Z\",\"videoLink\":null,\"githubLink\":\"https://github.com/StackTipsLab/android-ui-tutorials/tree/master/android-simple-listview\",\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"listview\",\"listview-custom-adapter\",\"android-baseadapter\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android ListView Tutorial: ArrayAdapter to Custom Adapter\",\"metaDescription\":\"A complete Android ListView tutorial covering ArrayAdapter basics, building a custom BaseAdapter, and styling list selection colors and dividers.\",\"metaKeywords\":null},\"content\":\"$162\"},{\"id\":338,\"title\":\"Normalize all whites paces from string\",\"slug\":\"normalize-white-spaces-from-string\",\"excerpt\":\"Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-05-02T04:09:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.811Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"java\"],\"tags\":[\"java-normalize-whitespace\",\"stringbuffer-java\",\"java-string-manipulation\",\"remove-extra-spaces-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$163\"},{\"id\":339,\"title\":\"Download Image using AsyncTask in Android\",\"slug\":\"download-image-using-asynctask-in-android\",\"excerpt\":\"This tutorial explains how to download Image using AsyncTask in Android. The example below download image while showing progress bar while during download.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-03-19T07:06:09.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.850Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-asynctask-example\",\"download-image-android\",\"android-progressdialog\",\"httpclient-bitmap-download\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Download Image Using AsyncTask in Android (with Code)\",\"metaDescription\":\"Learn how to download an image in Android using AsyncTask while showing a progress dialog, with a step-by-step explanation of the AsyncTask lifecycle.\",\"metaKeywords\":null},\"content\":\"$164\"},{\"id\":340,\"title\":\"Android Styles and Themes Tutorial\",\"slug\":\"android-styles-and-themes-tutorial\",\"excerpt\":\"This tutorial describes how to create and use styles and themes in Android applications with examples and code snippets.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-03-15T12:50:15.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.879Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-styles-xml\",\"android-themes\",\"nine-patch-drawable\",\"android-style-inheritance\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Styles and Themes Tutorial with Examples\",\"metaDescription\":\"Learn how to create and apply Android styles and themes, including style inheritance, nine-patch drawables, selectors, and gradient backgrounds.\",\"metaKeywords\":null},\"content\":\"$165\"},{\"id\":342,\"title\":\"Android Interview Questions And Answers\",\"slug\":\"android-interview-questions-and-answers\",\"excerpt\":\"This post answers some of the common questions in android. The source code snippets are pretty simple to use. How to Make a call in Android, How to integrating sharing in Android, How to open link in Android Browser, etc.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2013-01-24T18:23:34.000Z\",\"updatedDate\":\"2025-09-16T23:05:36.994Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"android\"],\"tags\":[\"android-interview-questions\",\"android-share-intent\",\"android-send-sms\",\"android-toast-example\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":\"Android Interview Questions and Answers with Code\",\"metaDescription\":\"Common Android interview questions and answers with code snippets covering SMS, calls, email, sharing intents, HTML in TextView, and passing data between activities.\",\"metaKeywords\":null},\"content\":\"$166\"},{\"id\":343,\"title\":\"How Does Reference Counting Garbage Collection Work\",\"slug\":\"reference-counting-garbage-collection\",\"excerpt\":\"This article will help you to understand the basic concept of Garbage Collection and the process flow for…\",\"difficulty\":\"beginners\",\"publishedDate\":\"2012-02-26T23:26:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.025Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"blog\"],\"tags\":[\"reference-counting-gc\",\"java-garbage-collection\",\"memory-management-java\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$167\"},{\"id\":344,\"title\":\"What is Garbage Collector and how it works ?\",\"slug\":\"overview-of-garbage-collector\",\"excerpt\":\"This article will help you to understand the basic concept of Garbage Collection like dangling pointer, memory leak and strategies to avoid and reduce memory costs.\",\"difficulty\":\"beginners\",\"publishedDate\":\"2012-02-26T23:18:00.000Z\",\"updatedDate\":\"2025-09-16T23:05:37.062Z\",\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":\"/media/articles/441/thumbnail.png\",\"topics\":[\"java\"],\"tags\":[\"java-garbage-collection\",\"memory-leak-java\",\"dangling-pointer-java\",\"java-memory-management\"],\"course\":null,\"displayOrder\":0,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$168\"},{\"id\":465,\"title\":\"MDC Logging with Interceptors in Spring Boot\",\"slug\":\"mdc-logging-with-interceptors-in-spring-boot\",\"excerpt\":\"How to use MDC to attach a request-correlation ID to every log line for a given HTTP request, using a Spring MVC interceptor.\",\"difficulty\":\"beginner\",\"publishedDate\":null,\"updatedDate\":null,\"videoLink\":null,\"githubLink\":null,\"featured\":false,\"thumbnail\":null,\"topics\":[\"spring-boot\"],\"tags\":[\"mdc-logging\",\"spring-boot-interceptor\",\"request-correlation-id\",\"slf4j-logback\"],\"course\":null,\"seo\":{\"metaTitle\":null,\"metaDescription\":null,\"metaKeywords\":null},\"content\":\"$169\"}],\"columns\":3,\"topicsBySlug\":{\"android\":{\"slug\":\"android\",\"name\":\"Android\",\"bgColor\":\"#3ad580\"},\"java\":{\"slug\":\"java\",\"name\":\"Java\",\"bgColor\":\"#F89820\"},\"spring-boot\":{\"slug\":\"spring-boot\",\"name\":\"Spring Boot\",\"bgColor\":\"#6cb440\"},\"python\":{\"slug\":\"python\",\"name\":\"Python\",\"bgColor\":\"#f7ca3d\"},\"blog\":{\"slug\":\"blog\",\"name\":\"Blogging\",\"bgColor\":\"#ff9d00ff\"},\"spring\":{\"slug\":\"spring\",\"name\":\"Spring\",\"bgColor\":\"#6cb440\"},\"xamarin\":{\"slug\":\"xamarin\",\"name\":\"Xamarin\",\"bgColor\":\"#3498db\"},\"design-pattern\":{\"slug\":\"design-pattern\",\"name\":\"Design Pattern\",\"bgColor\":\"#ff606c\"},\"maven\":{\"slug\":\"maven\",\"name\":\"Maven\",\"bgColor\":\"#a72052\"},\"git\":{\"slug\":\"git\",\"name\":\"Git\",\"bgColor\":\"#e84d32\"},\"django\":{\"slug\":\"django\",\"name\":\"Django\",\"bgColor\":\"#003c2a\"},\"flutter\":{\"slug\":\"flutter\",\"name\":\"Flutter\",\"bgColor\":\"#0b5698\"},\"junit5\":{\"slug\":\"junit5\",\"name\":\"JUnit 5\",\"bgColor\":\"#249c5f\"},\"aws\":{\"slug\":\"aws\",\"name\":\"AWS\",\"bgColor\":\"#f69403\"},\"docker\":{\"slug\":\"docker\",\"name\":\"Docker\",\"bgColor\":\"#1c60e6\"},\"bootstrap\":{\"slug\":\"bootstrap\",\"name\":\"Bootstrap\",\"bgColor\":\"#4f46e5\"},\"c\":{\"slug\":\"c\",\"name\":\"C Programming\",\"bgColor\":\"#2563eb\"},\"cordova\":{\"slug\":\"cordova\",\"name\":\"Cordova\",\"bgColor\":\"#0f766e\"},\"html5\":{\"slug\":\"html5\",\"name\":\"HTML5\",\"bgColor\":\"#e2e8f0\"},\"ibm-worklight\":{\"slug\":\"ibm-worklight\",\"name\":\"IBM Worklight\",\"bgColor\":\"#e2e8f0\"},\"ios\":{\"slug\":\"ios\",\"name\":\"iOS\",\"bgColor\":\"#e2e8f0\"},\"javascript\":{\"slug\":\"javascript\",\"name\":\"JavaScript\",\"bgColor\":\"#e2e8f0\"},\"json\":{\"slug\":\"json\",\"name\":\"JSON\",\"bgColor\":\"#121725ff\"},\"kafka\":{\"slug\":\"kafka\",\"name\":\"Apache Kafka\",\"bgColor\":\"#1c1e22ff\"},\"laravel\":{\"slug\":\"laravel\",\"name\":\"Laravel\",\"bgColor\":\"#ef2f03\"},\"microservices\":{\"slug\":\"microservices\",\"name\":\"MicroServices\",\"bgColor\":\"#e2e8f0\"},\"mongodb\":{\"slug\":\"mongodb\",\"name\":\"MongoDB\",\"bgColor\":\"#16a54f\"},\"php\":{\"slug\":\"php\",\"name\":\"PHP\",\"bgColor\":\"#e2e8f0\"},\"react\":{\"slug\":\"react\",\"name\":\"Reactjs\",\"bgColor\":\"#e2e8f0\"},\"sencha-touch\":{\"slug\":\"sencha-touch\",\"name\":\"Sencha Touch\",\"bgColor\":\"#e2e8f0\"},\"seo\":{\"slug\":\"seo\",\"name\":\"SEO\",\"bgColor\":\"#e2e8f0\"},\"unity\":{\"slug\":\"unity\",\"name\":\"Unity\",\"bgColor\":\"#e2e8f0\"},\"wordpress\":{\"slug\":\"wordpress\",\"name\":\"Wordpress\",\"bgColor\":\"#E2E8F0\"}},\"currentPage\":1,\"basePath\":\"/articles\"}]}]]}],[\"$L16a\"],\"$L16b\"]}]\n"])</script>
1<script>self.__next_f.push([1,"16c:[]\ne:\"$W16c\"\nf:[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$L16d\",null,{\"children\":\"$L16e\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$L16f\",null,{\"children\":[\"$\",\"$170\",null,{\"name\":\"Next.Metadata\",\"children\":\"$L171\"}]}]}],[\"$\",\"meta\",null,{\"name\":\"next-size-adjust\",\"content\":\"\"}]]}]\n11:[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/31h00aiyhac91.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]\n"])</script>
1<script>self.__next_f.push([1,"172:I[97367,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\"],\"OutletBoundary\"]\n16a:[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/0a3lk9460xb-w.js\",\"async\":true,\"nonce\":\"$undefined\"}]\n16b:[\"$\",\"$L172\",null,{\"children\":[\"$\",\"$170\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@173\"}]}]\n"])</script>
1<script>self.__next_f.push([1,"16e:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script>
1<script>self.__next_f.push([1,"174:I[27201,[\"/_next/static/chunks/0zl4fdmf-9zey.js\",\"/_next/static/chunks/20l7v14ur27g4.js\",\"/_next/static/chunks/2_aqbasgm93x0.js\",\"/_next/static/chunks/1-8s9_t85wwr4.js\"],\"IconMark\"]\n171:[[\"$\",\"title\",\"0\",{\"children\":\"Tutorials | StackTips\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"All tutorials on Java, Spring Boot, Android, and web development.\"}],[\"$\",\"link\",\"2\",{\"rel\":\"manifest\",\"href\":\"/manifest.webmanifest\",\"crossOrigin\":\"$undefined\"}],[\"$\",\"link\",\"3\",{\"rel\":\"canonical\",\"href\":\"https://stacktips.com/articles\"}],[\"$\",\"link\",\"4\",{\"rel\":\"icon\",\"href\":\"/brand/icon-light.png\",\"type\":\"image/png\"}],[\"$\",\"link\",\"5\",{\"rel\":\"icon\",\"href\":\"/brand/icon-dark.png\",\"type\":\"image/png\",\"media\":\"(prefers-color-scheme: dark)\"}],[\"$\",\"link\",\"6\",{\"rel\":\"apple-touch-icon\",\"href\":\"/brand/icon-dark.png\"}],[\"$\",\"$L174\",\"7\",{}]]\n173:null\n"])</script>
1</body></html>

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.