Android - Coding Infinite https://codinginfinite.com/android/ Your infinite Coding Solutions Sun, 05 Jun 2022 08:00:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 https://codinginfinite.com/wp-content/uploads/2018/07/CODING-INFINITE-FAVICON.png Android - Coding Infinite https://codinginfinite.com/android/ 32 32 Best Coding Apps For Android in 2022 https://codinginfinite.com/best-coding-apps-for-android-in-2022/ Sun, 05 Jun 2022 08:00:16 +0000 https://codinginfinite.com/?p=4302 If you are here, you might be a beginner in programming who wants to learn to code. Or, you might be an experienced programmer who wants to have some fun tools to revise coding concepts. Android apps that help you learn coding are just made for you. In this article, we will discuss some of...

The post Best Coding Apps For Android in 2022 appeared first on Coding Infinite.

]]>
If you are here, you might be a beginner in programming who wants to learn to code. Or, you might be an experienced programmer who wants to have some fun tools to revise coding concepts. Android apps that help you learn coding are just made for you. In this article, we will discuss some of the best coding apps for android in 2022. 

Sololearn

Sololearn is one of my personal favorites. Most people will agree that it is one of the best coding apps for android.  When I started to learn python, I needed something that would help me retain the programming concepts. Sololearn did that for me by providing programming challenges in the app. 

Sololearn provides lessons and certifications for more than 20 languages like Java, Python, C++, C#, Swift, etc.  Whether you are a beginner who wants to learn the basics or an experienced programmer who wants to deepen your knowledge, Sololearn is there for you. It provides personalized content with lessons having practice questions that help you learn concepts in an easy manner.

Each course in Sololearn is bite-sized and you can complete the course within a few minutes. This helps you learn to program even if you have less time to do so.

Sololearn also has a good community where you can share your achievements, answer other people’s queries, share your code, and solve others’ problems. You can also challenge different people to play a quiz competition with you. Each quiz in Sololearn has 5 questions that are asked to both the players. The player who answers most of the questions correctly wins.

With Sololearn, you can also write and edit code on your phone. Sololearn provides support for writing and executing many languages like C, C++, Python, Java, Ruby, PHP, and others. 

GeeksForGeeks

GeeksForGeeks is one of the leading websites helping people learn to code easily. In its Android application, GeeksForGeeks provides thousands of articles on web technologies, Python, Java, C++, C#, Competitive programming, Interview experiences, and core computer science subjects like database management systems, operating systems, and whatnot. You will get everything related to computer science here on this app.

Apart from the articles, GeeksForGeeks also provides quizzes in all the above-mentioned areas. The quizzes help you refresh your knowledge and retain information in a fun way.

GeeksForGeeks also provides resources for interview preparation. It provides practice questions tagged by the name of companies where the questions were asked in the interviews.

Apart from these, GeeksForGeeks also provides you with recorded and live lectures for computer science subjects. They also provide doubt support to students who enroll in certain courses provided by them. In the app, you can also save articles and download video lectures that you can watch later. 

If you are rigorously preparing to get into a software company, GeeksForGeeks might be one of the best coding apps for you. Its self-paced courses are awesome and you will surely consider it one of the best coding apps for android in 2022 if you learn from it.

Programming Hub

Programming Hub might be one of the best coding apps for your android phone. It provides free as well as premium course content for learning programming. With a wide variety of courses ranging from Basics of Python to Natural language processing and blockchain development, Programming Hub can be your ready-to-go partner in your programming journey.

The Programming Hub app has more than 5000 programming examples in more than 20 programming languages. All the programs are precompiled with output to help you practice and learn to program easily.

With concept-based illustrations, interactive learning experience, and periodic updates with new programming examples and course content, Programming Hub makes it easy for you to learn programming concepts.

Mimo

If you are looking for a personalized learning experience at your own pace, Mimo might be the best coding app for you. Mimo provides bite-sized lessons and coding challenges in programming languages like Python, Javascript, HTML, CSS, etc. 

You can run and build real-world projects in the mobile IDE provided by Mimo. You can build a portfolio of projects, apps, and websites with Mimo to showcase your skills. Mimo also provides you with certifications to validate your programming skills.

With these specialties and a community of millions of coders, Mimo is certainly one of the best coding apps for android in 2022 that you must try. 

ScratchJr

ScratchJr is the best android coding app for children. ScratchJr is itself a programming language inspired by the Scratch programming language that was developed by MIT. It is developed by the Developmental Technologies group at Tufts University, the Lifelong Kindergarten group at MIT media lab, and the Playful Invention Company.

This app helps young children to create their own interactive stories and games using the android app. For each task, specific programming blocks are assigned in the app. Children snap together different blocks to make characters move, jump, dance, and sing. 

In the app, children can also modify characters in the paint editor. They can also insert their favorite photo to use as the character and make the characters come to life.

As young children learn to code with ScratchJr, they learn how to express their thoughts while interacting with the app. In the learning process, the children also learn to solve problems, develop sequencing skills, and design projects that help them build solid analytical skills.

If you want your child to start with coding, ScratchJr might be one of the best android apps to learn to code.

Grasshopper: Learn to Code

Grasshopper is designed by Google to help you learn to code. It provides fun, quick games on your phone that teach you to write real Javascript programs. YOu can progress through levels challenging yourself to learn more and more. 

Grasshopper also provides visual puzzles that help you develop your problem-solving skills and solidify coding concepts. The real-time feedback in the app guides you like a teacher and you can use industry-standard Javascript with just a few taps on your phone. The app also provides badges for achievements as you progress in your learning path.

If you want to learn Javascript, Grasshopper might be one of the best coding apps for your android phone.

CuriousJr

CuriousJr provides online programming courses for grades 6 to 12. It provides fun coding gaming to teach you to learn to program. With free animated videos and coding games, CuriousJr helps you to learn sequences, loops, functions, and other programming constructs in an easy manner. 

You can type the code and execute it in the app itself. With proper feedback, the app also helps you identify your weaknesses so that you can work on them. 

CuriousJr also provides you with its own app store where you can create and publish your android apps. Additionally, it also provides certifications that help you validate your knowledge.

With an easy and simple interface for beginners and interactive learning, CuriousJr is certainly one of the best coding apps for android in 2022.

Codemurai

Codemurai provides hundreds of byte-sized programming lessons to help you learn coding languages and frameworks, including HTML, CSS, JS, Python, and Unity. Codemurai provides a curated learning curriculum where you can learn to code, level up, and earn coins, experience, and badges by completing lessons and challenges.

It is a beginner-friendly application. Starting from zero, you can become a full-stack web developer by learning courses like Typescript, Angular, ES6, MongoDB, Node.js, and React. 

The learning experience in Codemurai certainly pays off the time and energy you invest into learning. This is why Codemurai is one of the best coding apps for android in 2022.

Enki

The Enki app describes itself as a mentor in your pocket helping you learn data, coding, and technical skills. It provides a personalized and continuous learning path that helps you learn and maintain your coding, data, and technical skills through a science-backed and interactive learning experience.

Enki provides personalized workout suggestions based on your learning style. It also provides revision workouts, a coding playground, and hands-on exercises to apply your knowledge.

With a tracked learning path, mentor reviews, and a great community, Enki makes it to the best coding apps for android in 2022.

Encode

Encode provides bite-sized lessons that efficiently present coding concepts with real code examples. It provides plenty of interactive coding challenges that help you improve your coding skills. You can also download the programming lessons to watch them later even if you are offline. With its simple, no-frills experience supported by an intuitive interface and lots of free courses, Encode makes it to the list of best coding apps for android in 2022.

Conclusion

In this article, we have discussed the 10 best coding apps for android in 2022. To learn to program, you can download these apps and give them a try. If you require my suggestion to decide which app to download, here it is.

Go for Sololearn if you want to have fun while you learn to code. Go for GeeksForGeeks if you are preparing for a coding job interview.

I hope you enjoyed reading this article. To learn more about android, you can read this article on how to create animation in android app. You might also like this article on software development trends in 2022.

The post Best Coding Apps For Android in 2022 appeared first on Coding Infinite.

]]>
Porting an iOS Application to Android (and Vice Versa): Why and How? https://codinginfinite.com/porting-an-ios-application-to-android-and-vice-versa-why-and-how/ Mon, 01 Jun 2020 16:41:51 +0000 https://codinginfinite.com/?p=4200 It’s very common to start with just one app, usually, for iOS. Reasons differ—from testing new channels to not having enough resources to make two apps. But once the app is doing well on the market, it’s time to expand and adapt it to another platform. Which gives rise to some questions: What’s the point...

The post Porting an iOS Application to Android (and Vice Versa): Why and How? appeared first on Coding Infinite.

]]>
It’s very common to start with just one app, usually, for iOS. Reasons differ—from testing new channels to not having enough resources to make two apps.

But once the app is doing well on the market, it’s time to expand and adapt it to another platform.

Which gives rise to some questions:

  • What’s the point of porting an app?
  • What benefits does it bring?
  • What are the challenges?
  • And why not just use one of the online app converters?

Now, this is not an instruction on how to convert apps. But a guide explaining the most popular reasons for app converting—and what to pay attention to during this process.

Let’s get started.

Why Convert Apps from One Platform to Another?

There’s a bunch of reasons—be it good results you’re getting from one app or the need to grow the audience.

Basically, there are three reasons, as old as humanity itself:

  • get more users
  • get access to new markets
  • get more money

I suggest taking a more detailed look at them.

New users

By having apps for both platforms, you reach more of your target audience and make the mobile strategy more profitable.

Many businesses, especially when it comes to startups, start with a single platform—the one most of their audience uses. That’s because startups often don’t have enough money to make two native apps.

Starting with an MVP for iOS/Android is a rational and more budget-friendly decision.

According to Statcounter, Android may hold 75% of the mobile OS market share worldwide.

More wealthy markets belong to iOS, though:

  • Oceania — 53% market share
  • US — 54%
  • Canada — 53%
markets where ios dominates

You can’t ignore this if your product is aimed at one of these regions, if not all of them. And that’s not including countries where iOS takes 20-40% market share, which is also a huge part.

New markets

If you want to get access to a few more markets, you should probably have two apps for two platforms.

By converting your iOS app to Android, you may get new users from Android-loving countries like Central or Eastern Europe, Africa, Asia, or Latin America.

And vice versa: need to cover North America, Oceania, or some other local markets (like Norway, Japan, Saudi Arabia)? Convert your Android app to iOS.

operating system markets

More money

It all depends on the monetization model you’ve picked. Still, in any case, two apps can potentially bring bigger revenue than one:

  • iOS owner buy apps more often and spend more on in-app purchases
  • Android apps are downloaded more, which means better earnings from in-app advertising.

Platform’s share isn’t the only thing to pay attention to when discovering new operating systems.

There are some rules for markets like the European one. To launch an app there, you need to make sure that your iOS and Android apps are compliant with GDPR.

For Arabic markets, UI designers should adjust the interface to the Arabic language—make it go from right to left.

What to Pay Attention to When Converting Apps?

First, I don’t recommend using online app converting platforms. All you’re going to get is unstable code with tons of issues at best or not working at worst. If you’re looking for a painless solution, it’s better to hire dedicated developers.

Here I’m taking about native development: for iOS, it’s Objective-C/Swift programming, Android — Java/Kotlin.

These programming languages are official and most widely used for mobile development.

Once again: there’s no magic wand that’ll turn Swift code into Kotlin one. It takes a few skilled mobile devs to make it work.

What’s more, each programming language has its own syntax, and the time required to build the same authorization feature may slightly differ on iOS and Android.

Now, let’s see what tech and design challenges you’re going to face when porting the apps.

Adaptating to Different OS Versions

Both Android and iOS get updates every year. Here’s the problem: many users don’t or can’t update to the latest OS version.

For you, that means your app should run on the most popular OS versions. Or some percentage of users will have to quit.

Actually, if you’re converting an Android app to iOS, the situation isn’t that bad. 89% of iOS users update to the latest OS version (for now, it’s iOS 13). 9% use iOS 12 and 2% stay on an older version.

iOS OS adoption

But it’s a bit tricky with Android, so you may want to check some statistics on Android OS usage.

Almost half of all users (41%) have the latest OS version (currently, it’s Android Pie). 19% are using the previous Android version (Oreo), and the rest—Nougat, Marshmallow, or Lollipop versions.

Android OS adoption

Number of Screen Sizes and Resolutions

The next thing is adapting the app’s layout to different screen sizes and resolutions. Especially when it comes to iOS-to-Android converting.

The list of iOS screen sizes has 16 points in it. As for Android, it’s much more complicated.

There are hundreds of Android-based devices with different screen resolutions made by different manufacturers.

ios vs android screen sizes and resolutions

Android developers handle this issue by supporting different densities and adjusting the app for a few screens. Then the app will be automatically adjusted to other resolutions.

UI Design Challenges

Next stop—UI/UX design. It’s as important as the tech part (after all, it’s the first thing app users will see). But there’s another catch: Android and iOS have different design languages—flat and material.

How exactly do they differ?

Fonts

Android uses Roboto typeface, iOS—San Francisco. Both guidelines show different use cases with various sizes, letter spacings, and weights. That makes fonts look natural within a system, but it’s another headache for you.

Android vs iOS fonts

Icons

System icons also differ. They are more delicate on iOS and bolder on Android.

Android vs iOS icons

Digital files

Media assets porting—photos, videos, PDF files, docs—from one platform to another is important, too, as they have different sizes on Android and iOS.

Here’s the grid for iOS:

iOS grid

Android:

Android grid

Of course, there’s a lot more design differences between these two systems. But these are the most visible for users.

Converting apps is tricky but rewarding—you discover new markets, get more users, and earn more money.

Anyway, I advise starting with an iOS app, as many successful startups did. Instagram appeared on Android only 4 years after the launch on iOS, Airbnb spent 14 months to convert iOS app to Android. You know the results.

But the choice of the platform always depends on the target audience. Maybe in your case, Android is the best option to start with.

Don’t use app converters, code translators, and other stuff—they waste your time, nothing else. Converting an app from one platform to another requires a deep understanding of the app’s logic and good coding skills.

If you’re entrusting the task to developers—make sure to provide them with the source code, media files, and documentation.

If you’re making it yourself, pay attention to tech, and design differences between these two platforms.

The post Porting an iOS Application to Android (and Vice Versa): Why and How? appeared first on Coding Infinite.

]]>
The 7 Hottest Trends in Android Development for 2020 https://codinginfinite.com/the-7-hottest-trends-in-android-development-for-2020/ Tue, 07 Apr 2020 13:54:46 +0000 https://codinginfinite.com/?p=4186 With no doubt, Android app development is one of the fastest-growing sectors of web development. An array of smart technologies available open almost unlimited possibilities to both end-users and software developers. This, in turn, results in a high competition level in the industry. To survive in this highly competitive environment one needs to keep up...

The post The 7 Hottest Trends in Android Development for 2020 appeared first on Coding Infinite.

]]>
With no doubt, Android app development is one of the fastest-growing sectors of web development. An array of smart technologies available open almost unlimited possibilities to both end-users and software developers. This, in turn, results in a high competition level in the industry. To survive in this highly competitive environment one needs to keep up with the latest trends. Let’s review the seven hottest trends in Android app development for the year 2020.

Instant Applications

The concept of instant apps is great: users are allowed to try the application before downloading. As evidenced in practice, this results in a higher installation rate. When choosing between two similar apps, users tend to opt for the one they have already tested. This is especially true for mobile games; however, the solution can be of use for business applications as well. An example is the Crossword app offered by the New York Times, which is available in an instant mode, i.e. without downloading.

From the point of view of a regular user, instant apps have some very attractive advantages.

  • They use less traffic if compared to conventional apps.
  • They help save storage space on the device.
  • They are compatible with most Android-powered devices.
  • They let us use all the app’s features without the need to install it.

Most instant apps provide great user experience, thanks to their thought-out UI. They run smoothly in a usual mobile web-browser.

From the point of view of a developer, the creation of an instant app is almost as easy as the creation of a conventional application. The source code and API are the same. Moreover, one can make an existing application instant.

Flutter by Google

The Flutter technology is a special framework, which lets developers create multi-platform native apps. It adds a lot of flexibility and saves time, as you need to develop only one app compatible with both Android and iOS, instead of two separate products. There are at least three reasons to use this tool.

  1. Flutter lets use native elements of both iOS and Android elements to make the user experience more comfortable. It can modify the functionality of particular native widgets. Thanks to that, an app looks and feels like an original OS’s application.
  2. Flutter is a convenient option for creating MPV products, as it helps to cut off the development time.
  3. Flutter is easy to use. Google provides a generous set of detailed instructions, manuals, and video classes that explain how to use the technology.

Many popular apps, such as Google Ads and Alibaba, are created with the use of the Flutter technology. Experts believe its popularity will only grow. Without a doubt, it is one of the hottest trends in Android development.

AI and Machine Learning

AI and ML are intensively used in app development. They help make an application more flexible and customizable. An AI-based app learns the user’s behavior patterns to bring interaction to a new level. A constant analysis of the user’s interests and inquiries lets create unique smart suggestions for him and predict his actions. Artificial Intelligence is also a powerful marketing tool, as it lets make targeted, more precise suggestions to potential customers. Thanks to it, a mobile application can turn into a powerful marketing channel.

Examples of well-known AI- and ML-based applications include Google Maps, LinkedIn, Tinder, Netflix, and others. If you have ever used these apps, you’ve definitely had a chance to appreciate their convenience and a lot of smart features.

Chatbots

Chatbots are widely used in the B2B sector. While they can’t be considered cutting-edge technology, they remain one of the hottest trends in 2020, thanks to their effectiveness and ease of use. A chatbot is a great alternative for a live operator of a customer support service. Unlike a live operator, it can work 24/7 without being tired and helps avoid mistakes caused by a human factor. Another great advantage of a chatbox is fasts responses. Some major brands, such as Starbucks, have already made use of this smart solution.

Android Jetpack

This is a complex developer kit that includes multiple tools and libraries, which let create top-notch apps from the scratch. Thanks to the detailed guides offered by Google, the suite is easy to start with. Basically, it consists of 4 key components:

  1. Foundation, which helps in programming and testing.
  2. Architecture, which includes components needed for creating reliable apps for Android.
  3. Behavior, which is responsible for the implementation of various services, such as in-app notifications.
  4. User interface components, which are used for making the app UI convenient and user-friendly.

On-Demand Applications

On-demand applications use smart technologies for tracking user location and behavior. Based on the information collected, they offer the most relevant services. It helps solve everyday tasks faster and more effectively.

One can implement the on-demand functionality in almost any app – taxi services, food delivery, travel apps, and so on. The stellar examples of on-demand apps are Uber and Google Maps, which track user location and instantly offer the needed services on the user’s demand. This functionality is quite easy to implement, and it can be rightfully considered one of the leading trends of 2020.

Internet of Things

Internet of Things seems to be one of the most promising trends, thanks to the consistent growth of smart Internet-enabled devices around. Just some of the most obvious spheres of application of the IoT technology are healthcare, fitness, and education. For example, some independent devices, such as smartwatches and fitness trackers can collect information about a user’s health condition and send it to medical centers without human participation.

The technology is applied in the sphere of education. Just some examples of popular IoT-based apps are Edmodo, Nymi, and C-Pen. They open a broad spectrum of opportunities to users, such as sharing important educational materials, remote control of students’ progress, the collaboration of tutors, parents, and pupils, and so on.

Final Thoughts

The year 2020 offers a lot of great opportunities for Android app developers. But, if you want to create really competitive products, you need to be aware of the latest trends in the industry and try to apply them in the development process. We’ve reviewed seven hot trends, which seem to have the largest potential. However, you shouldn’t stop here, as there are some other great tools to consider, for example, Augmented Reality, which can provide a really unique user experience. Be creative and use thee right tools depending on your business specifics. After all, an ability to use a non-standard approach and estimate the project from a long-term perspective is a key to success.

Author’s bio

Vitaly Kuprenko is a writer for Cleveroad. It’s a web and mobile app development company with headquarters in Ukraine. He enjoys writing about technology and digital marketing.

The post The 7 Hottest Trends in Android Development for 2020 appeared first on Coding Infinite.

]]>
How To Create Animations In Android Application https://codinginfinite.com/how-to-create-animations-in-android-application/ Wed, 12 Feb 2020 09:17:07 +0000 https://codinginfinite.com/?p=4081 Did you know that there are more than 2.7 million apps on the Google Play Store as of 2019? The demand and need for mobile apps are so high, that Google reports releasing about 3000 plus apps every day on its Play Store! The app market seems to appeal to Millennials much more than any...

The post How To Create Animations In Android Application appeared first on Coding Infinite.

]]>
Did you know that there are more than 2.7 million apps on the Google Play Store as of 2019?

The demand and need for mobile apps are so high, that Google reports releasing about 3000 plus apps every day on its Play Store!

The app market seems to appeal to Millennials much more than any other generation, with 21% of Millennials opening an app 50+ times a day!

Numbers seem to be in favor of mobile apps with 57% of all digital media usage coming from mobile apps

Google is a much-loved company worldwide and is synonymous with technology, creativity, and innovation.

They’ve earned a reputation of being the best and most reliable in the Android market business, and rightly so.

Having your app on the Google Play Store will provide good visibility and will reach your desired audience. So ho do you set up making your app stand out in the Android market?

To have edge over competitors, you have got to have an appealing visual language. High resolution, well-designed graphics, and animations are synonymous with great visual appeal.

The Android framework provides a set of powerful APIs for applying animation to UI elements.

Types of Animations

There are three animation systems for Android Apps.

Property Animation

This lets you animate any property of any object, regardless of whether it shows on the screen or not. This is the preferred method of animation in Android.

To animate an object, you must specify the object property and how long you want to animate it.

View Animation

Also known as “tween animation”, you can use this to animate objects in a view. This is limited to simple sequential transformations, such as moving, resizing and rotations.

Drawable Animation

This lets you load a sequence of “Drawable” resources or images, frame by frame. This is the traditional method of animation, which uses a series of images played in order, like a roll film.

Let us know now see how we can create animations.

Android Animation Using XML Code

With this, you can cover basic animations like fade in, fade out, scale, rotation, slide up and down and so on.

The XML animations code is quite simple to use and requires one to use the XML file in Java.

To do this, open the Android Studio and create a new project with the “Empty Activity” template.

Then you must create an anim resource directory that is meant to store all your animation files.

To put it very simply, right-click on “res directory” > New > Android Resource Directory > anim.

The next step is to add the animation in the file. Add the below code for a blink effect in your blink.xml file.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="0.0"
      android:toAlpha="1.0"
      android:interpolator="@android:anim/accelerate_interpolator"
      android:duration="800"
      android:repeatMode="reverse"
      android:repeatCount="infinite"/>
</set>

Next, load the animation and set to view in activity to the blink effect.

public class BlinkActivity extends Activity{
TextView textMessage;
// Animation
Animation animBlink;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_blink);
    textMessage = (TextView) findViewById(R.id.textMessage);
    textMessag.setText(Welcome to Android Code Portal);
    // load the animation
    animBlink = AnimationUtils.loadAnimation(getApplicationContext(),
    R.anim.blink);
   // start the animation
    textMessage.startAnimation(animBlink);}
}

Animate Bitmaps

Drawable animations are used to animate a bitmap graphic like an icon or an illustration. Sometimes, images may need to be animated on-screen.

For example, if you want to morph one icon into another once it has been tapped (turning a play button to a pause button). There are two ways of doing this.

Use AnimationDrawable

This allows you to choose many static drawable files, which will then be displayed one at a time to create an animation.

You can define the frames of an animation in your code using a single XML file that lists the sequence of frames that composes the animation.

This particular XML file belongs In the “res/drawable/” directory of the concerned project. The instructions will consist of the order and duration for each frame.

The XML file consists of a <animation-list> which contains the <items> that will be played one after another. Below is an example of an XML file for a Drawable animation:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">
    <item android:drawable="@drawable/rocket_thrust1" android:duration="200" />
    <item android:drawable="@drawable/rocket_thrust2" android:duration="200" />
    <item android:drawable="@drawable/rocket_thrust3" android:duration="200" />
</animation-list>

This animation cycle will run for three frames. If the “android:oneshot” attribute of the list is set to “false”, then the animation will loop.

We can also apply the above animation for an “ImageView” where it can be added as the background animation to a View and then called to play.

In the code below, the animation is added to an “ImageView” and then animated when the screen is touched.

AnimationDrawable rocketAnimation;
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
  rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
  rocketAnimation = (AnimationDrawable) rocketImage.getBackground();

  rocketImage.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        rocketAnimation.start();
      }
  });
}

Use AnimatedVectorDrawable

This is a type of drawable that is scalable, without getting pixelated. You normally define animated vector drawable in three XML files:

A vector drawable with the <vector> element in res/drawable/. Right-click on res/drawable > New Drawable Resource File.

Enter the chosen name. use the “android:name” attribute to assign a unique name to groups and paths, so you can refer to them from your animator definitions.

<!-- res/drawable/vectordrawable.xml -->
<!-- Source: Android Developer Website -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="64dp"
    android:width="64dp"
    android:viewportHeight="600"
    android:viewportWidth="600">
    <group
        android:name="rotationGroup"
        android:pivotX="300.0"
        android:pivotY="300.0"
        android:rotation="45.0" >
        <path
            android:name="v"
            android:fillColor="#000000"
            android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />
    </group>
</vector>

Animated vectors drawable with the <animated-vector> element in res/drawable/. This refers to the groups and paths in the vector drawable by their names.

<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
  android:drawable="@drawable/vectordrawable" >
    <target
        android:name="rotationGroup"
        android:animation="@animator/rotation" />
    <target
        android:name="v"
        android:animation="@animator/path_morph" />
</animated-vector>

One or more object animators with the <objectAnimator> element in res/animator/. In the example below, the first animator rotates the target group 360 degrees.

<objectAnimator
    android:duration="6000"
    android:propertyName="rotation"
    android:valueFrom="0"
    android:valueTo="360" />

Animation Between Activities

In this kind of animation refers to transitions between your activities.

This is supported by Android 5.0 (API level 21) or higher.

Here, you can apply simple entry and exit transitions supported by Android:

  • Explode – moves in and out from the center of the screen
  • Slide – slides in from the side of the screen and slides out from the other side
  • Fade – used to play with the opacity of the view while entering into the screen

Before going into the details of that, you need to know Price to Create an App. It will help you to know what the animation in the app will cost you.

To animate between activities, you must first define the style with the “android:windowActivityTransitions” attribute which enables windows content transitions. See the example below.

<style name="BaseAppTheme" parent="android:Theme.Material">
  <!-- enable window content transitions -->
  <item name="android:windowActivityTransitions">true</item>

  <!-- specify enter and exit transitions -->
  <item name="android:windowEnterTransition">@transition/explode</item>
  <item name="android:windowExitTransition">@transition/explode</item>

  <!-- specify shared element transitions -->
  <item name="android:windowSharedElementEnterTransition">
    @transition/change_image_transform</item>
  <item name="android:windowSharedElementExitTransition">
    @transition/change_image_transform</item>
</style>

The last step is to start the Activity by enabling transition:

startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(this).toBundle())

Animate UI Visibility and Motion

Subtle animations, that aren’t jarring to the eye are needed to change the visibility or position of views in your layout.

The property animation system provided by the “android.animation” package is available on Android 3.0 and higher (API level 11). This can be used to move, reveal or hide views in a layout.

For example, changing the position properties makes the view move across the screen and on changing the alpha property, the view fades out.

Check this link to understand how to do this. Common animations include changing view visibility with crossfade or circular reveal, swapping views with a card flip and changing the view size with a zoom animation.

There’s so much more you can do with animation on Android! This is just the beginning. Check this link for more in-depth information on Android animations, straight from the experts.

There are also lots of libraries you can refer to if you want to implement some cool and quirky animations. You can find the top libraries here.

Conclusion

Here, we have provided you with a step-by-step guide to create animation in Android applications. We hope this article proves to be a great value to you.

If you have any questions or suggestions related to this blog, then feel free to comment on them in the comment box. Thank You.!

The post How To Create Animations In Android Application appeared first on Coding Infinite.

]]>
Which is the Best Language or Platform To Develop Android Apps and Why https://codinginfinite.com/best-language-platform-develop-android-apps/ https://codinginfinite.com/best-language-platform-develop-android-apps/#comments Thu, 23 Jan 2020 12:09:22 +0000 https://codinginfinite.com/?p=4009 Coding an Android application is a challenging task. To begin with, it is important to choose the best programming language that will be apt to develop Android apps. The nature of iOS coding languages is limited but there are wide arrays of languages for Android apps. This, on one hand, offers flexibility to developers but...

The post Which is the Best Language or Platform To Develop Android Apps and Why appeared first on Coding Infinite.

]]>
Coding an Android application is a challenging task. To begin with, it is important to choose the best programming language that will be apt to develop Android apps. The nature of iOS coding languages is limited but there are wide arrays of languages for Android apps. This, on one hand, offers flexibility to developers but on the other hand makes it quite confusing. In this article, we will learn about the languages that must be utilized for coding Android applications. It is important to know about the strengths and the weakness of the programming languages.

Unity

When thinking about which Android programming language to choose for your upcoming application, beginning with this one will be beneficial. This is an open-source tool with a robust community that means developers will receive support any time they need. The tool only requires a few code lines to develop Android apps as it can help in setting up a gaming app in less than one hour. Unity being multi-platform offers a practical method of learning coding that is object-oriented. When your objective is to become a successful game developer, using this tool will be most prevalent.

Corona

An Android App language that is easy to learn & use but offer a certain amount of control & power is this one. It is simple to code in LUA and the mechanism becomes even easier with Corona SDK. The tool supports native libraries as well by which you can publish in numerous platforms.

To develop Android apps in the genre of games, Corona is the most perfect one. Code entering is done perfectly with the utilization of text editors such as Notepad++. In fact, there is no requirement of compiling as well and you can easily run the said code on emulator.

Java

The language that receives the biggest support from Google, Java is the official language for any Android application development. The answer is Java to the question, what programming language does Android use. Operated by a virtual machine, Java code functions on Android devices & infers the code. An object-oriented language, it carries some confusing topics such as checked exceptions, constructors and null pointer exceptions. Novice developers must not start suddenly with Java as it might con. fuse them.

A developer must carry the knowledge of concepts such as Android Manifest & Gradle for engaging in successful Android development with the utilization of this route. Though Java is extremely versatile & used widely, there are numerous communities for its complicated nature.

C/C++

If you are developing Android apps in the field of 3d games, then this is the apt programming language for you. In fact, you will be able to use libraries that are written in C++ or C. But it is a bit complicated when it comes to the set up as it brings forwards bugs and is a bit rigid.

Python

Indigenous Python development is not supported by Android but you can easily get hands-on the best Python Android app with current technologies. There are numerous tools that have made its way in the current market that help in converting Python applications into Android packages. These can operate well on Android devices.

One of the examples is Kivy which is an open-source Python library. It is utilized for the development of mobile applications. Encouraging quick application development, it offers complete support to Android. But as Kivy is not natively supported, Kivy will not be equipped with native benefits

PhoneGap

To make an Android app that is long-lasting, PhoneGap is the most “simplified” option. It is an Apache Cordova power-driven Android programming language with which you can construct applications by utilizing the same code that is used for websites. This is displayed via a “WebView” but it is packaged like an application. PhoneGap is that programming language that then functions as the bridge permitting developers to get hands-on native features of Smartphones or other devices like camera or accelerometer.

android

Wrapping it up

The time to pick and choose has finally arrived.

Just how there are a plethora of applications, there are numerous programming languages to develop Android apps as well. But no language can be regarded as the very correct language for Android application development. It is entirely upon the developer to choose the language and the selection must depend on the preferences & objectives of every individual project. Irrespective of the programming language you choose, it will be extremely beneficial for you to expand your expertise. It will also lead to your sheer growth as a successful Android developer.

Connect with us today for learning about the various programming languages from our experienced team of developers. They will assist you in fabricating the best Android application that will win hearts and in turn attain leads and conversions for your brand. Programming an Android app is tough. Let us help you with the procedure.

Thank you for reading.

Here’re some more articles of the same interest:

— What Stats & Surveys Are Saying About Top Programming Languages In 2020

— Six Pillars to Become a Senior Level Software Developer

The post Which is the Best Language or Platform To Develop Android Apps and Why appeared first on Coding Infinite.

]]>
https://codinginfinite.com/best-language-platform-develop-android-apps/feed/ 1
6 Android Apps Harnessing The Power of Machine Learning https://codinginfinite.com/6-android-apps-harnessing-the-power-of-machine-learning/ Thu, 23 Jan 2020 11:44:41 +0000 https://codinginfinite.com/?p=3999 When we look around us today and hear about things like the Internet of Things, Artificial Intelligence, Machine Learning etc, the first thought to cross our mind must be: ‘We have come a long way. The world around has progressed rapidly or we are on the Fastrack of a technological revolution. But, is that really...

The post 6 Android Apps Harnessing The Power of Machine Learning appeared first on Coding Infinite.

]]>
When we look around us today and hear about things like the Internet of Things, Artificial Intelligence, Machine Learning etc, the first thought to cross our mind must be: ‘We have come a long way. The world around has progressed rapidly or we are on the Fastrack of a technological revolution.

But, is that really the case? Probably not. The world that we live in today is not something that sprang out of the darkness. AI and ML did not fall from the sky. The use of Artificial Intelligence and Machine Learning is the byproduct of constant research; it is the byproduct of human intelligence and learning.

What we have learnt over the years, the knowledge we have accumulated over the years, we have passed on that knowledge to our machines. In order to automate, dehumanize, and imbrute the daily tasks, we have taught the machines to do our part of the job; making humans more productive in turn.

Here’re the 6 Android apps that are powered by Machine Learning and byzantine algorithms worth taking inspiration from. These companies managed to hire dedicated Android developers and built some fantastic apps.

LeafSnap

Scientists and researchers fed hundreds of thousands of photos of trees and leave to its algorithm. The process involves feeding an image to the algorithm and denoting a name to it. Just like a small child, the machine learns to connect the dots.

LEAFSNAP

When you take a snap of the leaf from within this app, the underlying algorithm determines the species and fossils of the subject in the picture.

Snapchat

The good old Snapchat! With the help of clever facial recognition algorithm developed by Looksery, which Snapchat acquired for $150 million, their Machine Learning software has become smart enough to recognize human faces and the exact dimensions of eyes, nose, ears, and mouth.

Netflix

Netflix already knows what you want to watch, before even you know what you want to watch. That complex line was nothing compared to the uber complex algorithm that Netflix deploys in order to show you recommended videos on its homepage.

Tinder

The cupid that shoots arrows for you on Tinder is called Machine Learning. It uses all kinds of magic dust and algorithms to find the perfect match for you. The cards that you swipe left and right on, are each masked by an algorithm who watches the show from behind the curtains. It learns and adapts according to your behaviour on the app.

Oval Money

Just like a financial manager would plan and strategize a plan depending upon his experiences and lessons learnt as a part of collective intelligence, the app does the same in the virtual world. It analyzes spending and saving patterns of a large number of users registered on the app and prepares a plan for its users based on the collected data.

Aipoly Vision

The initial idea behind building this app was to aid those who are visually impaired with their everyday tasks. All one needs to do is point the camera towards the subject and the app’s algorithm will recognize the objects appearing on the camera in real-time.  Their Machine Learning program was taught to recognize thousands of objects with a perennial process of feeding new and updated information.

AIPOLY VISION

Conclusion

The Machine Learning process doesn’t have a finish line today. There is no predetermined destination where one has to stop. The process of learning is eternal and perpetual; be it machines or humans. In a way, these Android apps are a way for machines to learn more about the world. These apps are not the end product of machine learning research and development, but they are a part of the learning and development process.

There is plenty of space in the market for anyone willing to take the risk and get an app developed. Data collection is one of the biggest drivers of business today. You can easily hire Android developers and start building an app.

Here’re some more articles of the same interest:

— What Stats & Surveys Are Saying About Top Programming Languages In 2020

— Six Pillars to Become a Senior Level Software Developer

The post 6 Android Apps Harnessing The Power of Machine Learning appeared first on Coding Infinite.

]]>
Android Google Map Marker Clustering Tutorial https://codinginfinite.com/android-google-map-custom-marker-clustering/ https://codinginfinite.com/android-google-map-custom-marker-clustering/#comments Thu, 09 May 2019 11:19:39 +0000 https://codinginfinite.com/?p=2590 Google Maps are a great way to show data. It might seem natural that the more geographical point Markers we add the better story it tells. But that’s not always the ideal case because once we’ve hundreds, even more, points the performance of Android application quickly begins to decrease. Let’s see an overloaded marker picture...

The post Android Google Map Marker Clustering Tutorial appeared first on Coding Infinite.

]]>
Google Maps are a great way to show data. It might seem natural that the more geographical point Markers we add the better story it tells. But that’s not always the ideal case because once we’ve hundreds, even more, points the performance of Android application quickly begins to decrease. Let’s see an overloaded marker picture of Google Maps.

Google Maps With So Many MarkersWe all have probably seen a map picture like this. There are so many markers on Google Maps, you can’t even see the map. The colors of markers tell some different kind of story, but there’s so much to overlap with other icons that you might well just be missing other data.

One way of getting rid of this problem to grouped (cluster) the marker’s on a Google Map and show only a specific amount of them. To see how marker clustering looks alike see the below picture.

Google Map Marker Clustering

The number on a cluster indicates how many markers it contains. Once we zoom onto cluster location we’ll able see the markers.

So, this tutorial shows you how to use marker clustering to display a large number of markers on Google Map in an Android application. Enough of this intro on marker clustering let’s dive into Android Studio and start building our application.

Note: I assume that you have successfully set-up Google Maps API in your Android app. If not, then visit Google Maps API get started section.

Getting Started

Before start coding our application we need to add the marker clustering util library (provided by Google) in the app-level build.gradle file.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
 
    ........
    ........
   
    // MapV2 clustring marker dependency
    implementation 'com.google.maps.android:android-maps-utils:0.5'

    // Google play services location dependency
    implementation 'com.google.android.gms:play-services-location:16.0.0'
}

Sync the project and everything should be fine without any kind of gradle error.

Experiment with marker Clustering

Now that everything is done let’s see how the marker clustering done on Google Maps. The simplest way to show the cluster, first, we need to implement ClusterItem on our model class. Let’s create a simple User class that implements ClusterItem.

public class User implements ClusterItem {

    private final String username;
    private final LatLng latLng;

    public User(String username, LatLng latLng) {
        this.username = username;
        this.latLng = latLng;
    }

    @Override
    public LatLng getPosition() {  // 1
        return latLng;
    }

    @Override
    public String getTitle() {  // 2
        return username;
    }

    @Override
    public String getSnippet() {
        return "";
    }
}

Here’s what going on inside the above code.

  1. The ClusterItem returns the position of the marker, which later Google Maps use’s and show the marker. Must always return same LatLng position.
  2. Title of the marker which will be visible when you click on a single marker.

Next, we need to add the ClusterManager inside our MapActivity.

public class MapActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment supportMapFragment = (SupportMapFragment)      getSupportFragmentManager().findFragmentById(R.id.map_fragment);  // 1
        supportMapFragment.getMapAsync(new OnMapReadyCallback() {  // 2
            @Override
            public void onMapReady(GoogleMap googleMap) {
                setUpClusterManager(googleMap);
            }
        });
    }

    private void setUpClusterManager(GoogleMap googleMap){
        ClusterManager<User> clusterManager = new ClusterManager(this, googleMap);  // 3
        googleMap.setOnCameraIdleListener(clusterManager);
        List<User> items = getItems();
        clusterManager.addItems(items);  // 4
        clusterManager.cluster();  // 5
    } 

    private List<User> getItems() {
       ......  // returns the collection of users.
    }
}

Taking each commented section in turn.

  1. Obtain the SupportMapFragment from xml.
  2. Registering a callback to get notified when we’re ready to use Google Maps.
  3. Creates a new ClusterManager which later handles the clustering for our markers. Note the type of argument<User> which declares the ClusterManager to be of User type.
  4. Feed the items to our newly created ClusterManager.
  5. Call the cluster method, you may want to call this method after feeding items to ClusterManager.

Here’s the demo of our application with marker clustering and you can get the finished code for Default Marker Clustering from here.

Custom marker inside the Marker Clustering

Since weren’t satisfied with the default solution, we need to make some customization to our default setup. Now let’s say I need to change the red default marker icon which shows inside the Cluster Marker with my own custom marker. For that, we need to create a new ClusterRenderer with to extend the DefaultClusterRenderer class.

Here, let’s create a new ClusterManager class to show our custom marker instead of default ones.

public class MarkerClusterRenderer extends DefaultClusterRenderer<User> {   // 1

    private static final int MARKER_DIMENSION = 48;  // 2

    private final IconGenerator iconGenerator;
    private final ImageView markerImageView;

    public MarkerClusterRenderer(Context context, GoogleMap map, ClusterManager<User> clusterManager) {
        super(context, map, clusterManager);
        iconGenerator = new IconGenerator(context);  // 3
        markerImageView = new ImageView(context);
        markerImageView.setLayoutParams(new ViewGroup.LayoutParams(MARKER_DIMENSION, MARKER_DIMENSION));
        iconGenerator.setContentView(markerImageView);  // 4
    }

    @Override
    protected void onBeforeClusterItemRendered(User item, MarkerOptions markerOptions) { // 5
        markerImageView.setImageResource(R.drawable.location_vector_icon);  // 6
        Bitmap icon = iconGenerator.makeIcon();  // 7
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));  // 8
        markerOptions.title(item.getTitle());
    }
} 

Here’s what’s going on inside the MarkerClusterRenderer class.

  1. Extending the default renderer in order to customize the marker’s inside the cluster.
  2. Setting the constant value for the single marker size.
  3. IconGenerator a utility class to generate the Bitmap icon marker.
  4. Adding the child view for IconGenerator class and in our case the ImageView which simply shows the marker.
  5. Called before every ClusterItem added to the Google Maps.
  6. Sets the drawable resource as the content of this marker ImageView.
  7. Generates the Bitmap of the previously custom view setting.
  8. Sets the icon for the marker.

Now we just need to set the instance of MarkerClusterRenderer class to our ClusterManager inside the MapActivity.

private void setUpClusterManager(GoogleMap googleMap) {
        ClusterManager<User> clusterManager = new ClusterManager<>(this, googleMap);
        clusterManager.setRenderer(new MarkerClusterRenderer(this, googleMap, clusterManager));
        ......
        ......
}

After adding the MarkerClusterRenderer class instance here’s the demo of our application with custom markers inside the Marker Clustering. You can get the complete code of Custom Marker Clustering from this link.

I hope this article will help you do custom Marker Clustering on Google Maps with Android application. Anything, I miss in this article please let me know via the comments section.

What’s Next

Show Custom Info Window On A Marker Click

Thank you for being here and keep reading…

The post Android Google Map Marker Clustering Tutorial appeared first on Coding Infinite.

]]>
https://codinginfinite.com/android-google-map-custom-marker-clustering/feed/ 10
Testing Different Methods of Launching Android Activities In Kotlin https://codinginfinite.com/methods-launching-android-kotlin-activities/ Thu, 11 Apr 2019 12:45:38 +0000 https://codinginfinite.com/?p=2460 I learned the 😓 hard way: There should be better ways to launch the Kotlin Android activities. Passing extra’s data via intent for serialization, and de-serialization on target Activity. So, I have read a lot of articles and gather a couple of cool ways to launch Android activities. Launching activities in android app is a...

The post Testing Different Methods of Launching Android Activities In Kotlin appeared first on Coding Infinite.

]]>
I learned the 😓 hard way: There should be better ways to launch the Kotlin Android activities. Passing extra’s data via intent for serialization, and de-serialization on target Activity. So, I have read a lot of articles and gather a couple of cool ways to launch Android activities. Launching activities in android app is a common task and different developer use different approaches. Now let’s see the different types of one-by-one.

Traditional Way

There are developers who still use the old way to launch an activity. Let’s look at the typical traditional way of launching an activity.

val intent = Intent(context, OtherActivity::class.java)
startActivity(intent)

Now if we need to pass an intent argument it becomes messier and not developer friendly experience. The major point is argument serialization, deserialization, type-safety, and null checks.

val intent = Intent(context, OtherActivity::class.java)
intent("name",user.name)
intent("email",user.email)
intent("id",user.uuid)
startActivity(intent)

At the OtherActivity we need to do quite a few things. Let’s see:

class OtherActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState : Bundle) {
         super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_other)
         val name = intent.getStringExtra("name") ?: throw IllegalStateException("field name missing in Intent")
         val email = intent.getStringExtra("email") ?: throw IllegalStateException("field email missing in Intent")
         val id = intent.getStringExtra("id") ?: throw IllegalStateException("field id missing in Intent")
    }

}

The above example works for our contrived example but can we improve it? Because there is always a better way to solve the problem.

Creating a launch extension function with reified Keyword

The method we’re going to use is originally published here on this link.

In this method, we’ll create an extension function for Activity and Context class. I can show you how to launch activity with this approach.

inline fun <reified T : Any> Activity.launch(
    requestCode: Int = -1,
    options: Bundle? = null,
    noinline init: Intent.() -> Unit = {}
) {
    val intent = intent<T>(this)
    intent.init()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        startActivityForResult(intent, requestCode, options)
    else
        startActivityForResult(intent, requestCode)
}

inline fun <reified T : Any> Context.launch(
    options: Bundle? = null,
    noinline init: Intent.() -> Unit = {}
) {
    val intent = intent<T>(this)
    intent.init()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        startActivity(intent, options)
    else
        startActivity(intent)
}

inline fun <reified T : Any> intent(context: Context): Intent = Intent(context, T::class.java)

After adding the extension function, we can directly use the .launch() into an Activity or Context class and use it like this:

// In Context reference class 
context.launch<OtherActivity>()

// In Activity reference class
activity.launch<OtherActivity>()

// Pass arguments
activity.launch<OtherActivity> {
   putExtra("name",user.name)
   putExtra("email",user.email)
   putExtra("id",user.id)
}

// launch activity for result
activity.launch<OtherActivity>(requestCode = 25)

// launch activity for result with arguments
activity.launch<OtherActivity>(requestCode = 25){
   putExtra("name",user.name)
   putExtra("email",user.email)
   putExtra("id",user.id)
}

// launch with shared transitions
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, profilePic, "profile")
activity.launch<OtherActivity>(options = options)

Nailed it 🔨 right! But to me, it’s nothing more than a better startActivity() because we still need to deserialize the extra’s parameter inside the OtherActivity class.

class OtherActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState : Bundle) {
         super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_other)
         val name = intent.getStringExtra("name") ?: throw IllegalStateException("field name missing in Intent")
         val email = intent.getStringExtra("email") ?: throw IllegalStateException("field email missing in Intent")
         val id = intent.getStringExtra("id") ?: throw IllegalStateException("field id missing in Intent")
    }
}

Let’s give it one more try and reduce the boilerplate code in order to do deserialization.

Launch activity with the args parameter & intent deserialization

Let’s get crazy and create an ideal data class for our extra parameter in order to do serialization and deserialization.

data class user(val name : String, val email : String, val uuid : UUID)

class OtherActivityArgs constructor(val user : User) {
   
     companion object {
        private const val NAME = "_name_"
        private const val EMAIL = "_email_"
        private const val ID = "_id_"

        fun deserializeFrom(intent: Intent): User {
            return User(
                name = intent.getStringExtra(NAME),
                email = intent.getStringExtra(EMAIL),
                uuid = UUID.fromString(intent.getStringExtra(ID))
            )
        }
    }

}

Next, create a generic ActivityArgs interface with some custom methods.

interface ActivityArgs {

    fun intent(context: Context): Intent

    fun launch(context: Context, options: Bundle? = null) =
       context.launch(intent = intent(context), options = options)

    fun launch(activity: Activity, options: Bundle? = null, requestCode: Int = -1) = 
       activity.launch(intent = intent(activity), requestCode = requestCode, options = options)
}

Now in order to do intent creation, we must implement the ActivityArgs interface on OtherActivityArgs class.

class OtherActivityArgs constructor(private val user: User) : ActivityArgs {

    companion object {
        private const val NAME = "_name_"
        private const val EMAIL = "_email_"
        private const val ID = "_id_"

        fun deserializeFrom(intent: Intent): User {
            return User(
                name = intent.getStringExtra(NAME),
                email = intent.getStringExtra(EMAIL),
                uuid = UUID.fromString(intent.getStringExtra(ID))
            )
        }
    }

    override fun intent(context: Context) = Intent(
        context, OtherActivity::class.java
    ).apply {
        putExtra(NAME, user.name)
        putExtra(EMAIL, user.email)
        putExtra(ID, user.uuid.toString())
    }
}

Before to start using the ActivityArgs class we must update our extension functions for Context and Activity class.

fun Activity.launch(
    requestCode: Int = -1,
    options: Bundle? = null,
    intent: Intent
) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        startActivityForResult(intent, requestCode, options)
    else
        startActivityForResult(intent, requestCode)
}

fun Context.launch(
    options: Bundle? = null,
    intent : Intent
) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        startActivity(intent, options)
    else
        startActivity(intent)
}

After this we can do some launching activities stuff of the previous example like below:

val args = OtherActivityArgs(user) // pass the user object for intent creation
args.launch(activity = this)

Later, we can do deserialization easily in the OtherActivity class.

class OtherActivity : AppCompatActivity() {

    private val user by lazy {
        OtherActivityArgs.deserializeFrom(intent)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_other)
        // use the user object
    }
}

 

Boom! we have a solution that it is easily maintained– there’s only one class that handle serializing and deserializing arguments for the OtherActivity class.

Conclusion:

The good thing is that, the Intent construction method doesn’t require setting the Context explicitly. It can only be called in or on Context classes.

So, what do you think about start activities, serializing and deserializing the data? I excited to get your feedback or tips to improve those methods even further. Please let me know via comments section.

Thank you for being here and keep reading…

The post Testing Different Methods of Launching Android Activities In Kotlin appeared first on Coding Infinite.

]]>
Android Crop Image Using UCrop Library https://codinginfinite.com/android-image-ucrop-camera-gallery/ Wed, 06 Feb 2019 13:59:26 +0000 https://codinginfinite.com/?p=1707 Almost in every Android Application, we ask users to add profile picture when signing up and after that, we simply upload the avatar to our backend. But, before uploading that avatar, sometimes, we need to crop the selected image. So, today I would like to talk about how we can select an image from Gallery...

The post Android Crop Image Using UCrop Library appeared first on Coding Infinite.

]]>
Almost in every Android Application, we ask users to add profile picture when signing up and after that, we simply upload the avatar to our backend. But, before uploading that avatar, sometimes, we need to crop the selected image.

So, today I would like to talk about how we can select an image from Gallery or take Picture from the camera and crop that avatar. The application that we’re going to build in this article will work on all versions of Android from Honeycomb (API 11) to Pie (API 28).

For cropping the image we’re going to use UCrop libraryUCrop library aims to provide an ultimate and flexible image cropping experience. You can read more about UCrop library in this article.

Before start coding, I want to show you guys the demo of our application.

Get Started

In Android Studio go to Create Android Project, press next twice and select Empty Activity, then finish. After the Android Studio gradle builds successfully you’re ready to do the code. You can see MainActivity like below.

public class MainActivity extends AppCompatActivity {

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

Include Dependencies

We’re gonna need to add the UCrop dependency in our app-level build.gradle file. Add the below dependency in the build.gradle file.

implementation 'com.github.yalantis:ucrop:2.2.2'

Now add the maven dependency in a top-level build.gradle file.

repositories {
       google()
       jcenter()
       maven { url "https://jitpack.io" }
   }

Once you’ve done these dependencies build your android project and add the following permissions in the Android Manifest file.

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

You may be curious why the hack I add the Storage permission in order to pick an image from Gallery or take a picture from Camera. Actually, when we select the image from the gallery or take pictures from the camera we need to store an image inside the device memory because of the UCrop library take the Uri instance in order to crop the image. And it would be good because we need to store the cropped image somewhere inside the memory and after that show the image inside the application.

Actually, there’s another thing which we need to discuss before start making our application. As I said at the start of this article, that our application will work on all existing Android devices. So, we need to handle the FileUriExposedException and for that, we need to implement FileProvider in our application. You can read more about FileUriExposedException in this link.

In order to implement FileProvider in your application. First, you need to add a FileProvider <provider/> tag in a AndroidManifest.xml file under the <application/> tag.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
</manifest>

The ${applicationId} automatically gets the package name of your Android application and concat the .provider with it.

The @xml/provider_paths we need to add it separately in the resource directory. First, you need to create an xml named directory inside the res folder and then create a file named provider_paths inside the previously created directory. Now paste the following code inside the provider_paths file.

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

Done! FileProvider is now declared and be ready to use.

1. Open Camera And Take Picture

First of all, we need to query for all the activities in the device which will handle the  CAPTURE_REQUEST intent. Now let’s open the camera when the user clicks on openCamera dialog action.

Note: I’m not gonna ask for camera or storage permission in this article but you can get the complete code of the above demo application from the Github.

private void openCamera() {
      Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      File file = getImageFile(); // 1
      Uri uri;
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) // 2
           uri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID.concat(".provider"), file);
      else
           uri = Uri.fromFile(file); // 3
      pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); // 4
      startActivityForResult(pictureIntent, CAMERA_ACTION_PICK_REQUEST_CODE); 
}

Here what’s going on in the openCamera method.

  1. Creating an image File with the getImageFile method. This method simply creates a new File in the external storage directory. We’ll see the implementation of the method in a couple of minutes.
  2.  If the SDK version of the device is API level 23+ then we simply create the Uri with the help of FileProvider in order to prevent the FileUriExposedException. The BuildConfig.APPLICATION_ID simply give us the package name of our application and concat the .provider with it as we did it in the AndroidManifest.xml file.
  3. Simply creates the Uri fromFile utility method if the SDK version is less than 24 API level.
  4. Sets the path of where you want to store the selected image so, that we can read the image in the onActivityResult method from the uri path. We’ll see how to do that.

Now let’s create the getImageFile method inside the Activity class.

String currentPhotoPath = ""; 
private File getImageFile() {
     String imageFileName = "JPEG_" + System.currentTimeMillis() + "_";
     File storageDir = new File(
         Environment.getExternalStoragePublicDirectory(
             Environment.DIRECTORY_DCIM
         ), "Camera"
     );
     File file = File.createTempFile(
         imageFileName, ".jpg", storageDir  
     );
     currentPhotoPath = "file:" + file.getAbsolutePath();
     return file;
 }

This method simply creates a random File name with .jpg extension inside the external storage directory. Also, we’re storing the file path inside the currentPhotoPath variable so that we can read the image from specified photo path.

After taking the picture from Camera our image will be stored inside the data extra’s which we pass when creating the Intent for Camera. Now let’s retrieve our image in onActivityResult method and crop it.

Crop the Taken Picture

First, you need to override the onActivityResult method inside your Activity class and add the following code.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(requestCode == CAMERA_ACTION_PICK_REQUEST_CODE && resultCode == RESULT_OK) {
          Uri uri = Uri.parse(currentPhotoPath);
          openCropActivity(uri, uri);
    }
}

If you observe the code carefully you may have noticed that we’re not using the data.getData() method. It always gives us null because we’re providing a file uri, so load with the currentPhotoPath and call the openCropActivity method.

Note: Our newly taken image will be replaced from the cropped image because I pass the same Uri’s as the sourceUri and destinationUri. You can change this logic by passing a different Uri for a destination.

Add the below openCropActivity method inside your Activity class.

private void openCropActivity(Uri sourceUri, Uri destinationUri) {
        UCrop.of(sourceUri, destinationUri)
        .withMaxResultSize(maxWidth, maxHeight)
        .withAspectRatio(5f, 5f)
        .start(context);
}

The UCrop configuration is created using the builder pattern. The UCrop.of method takes the first parameter as the sourceUri where the image file actually stored and the second parameter as the destinationUri where you want to store the cropped image.

After calling the openCropActivity method the UCrop simply opens up the image cropping activity with the startActivityForResult method and send the cropped image result in the onActivityResult method. Add the updated code inside the onActivityResult method.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(requestCode == CAMERA_ACTION_PICK_REQUEST_CODE && resultCode == RESULT_OK) {
          Uri uri = Uri.parse(currentPhotoPath);
          openCropActivity(uri, uri);
    } else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
          Uri uri = UCrop.getOutput(data);
          showImage(uri);
    }
}

In the updated code we simply get our cropped image Uri and call the showImage method.

Next, add the following method inside your Activity class.

private void showImage(Uri imageUri) {
    File file = FileUtils.getFile(context, imageUri);
    InputStream inputStream = new FileInputStream(file);
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
    imageView.setImageBitmap(bitmap);
}

Here we’ve completed our first part of an article where we take the picture from a camera and show the cropped image inside the ImageView.

2. Select Image From Gallery

In order to allow the user to select an image, we need to create an Intent which opens up the Documents app and only shows the images. Now let’s open the Documents app when the user clicks on selectImage dialog action.

Let’s create a new method to open the images.

private void openImagesDocument() {
    Intent pictureIntent = new Intent(Intent.ACTION_GET_CONTENT);
    pictureIntent.setType("image/*");  // 1 
    pictureIntent.addCategory(Intent.CATEGORY_OPENABLE);  // 2
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
         String[] mimeTypes = new String[]{"image/jpeg", "image/png"};  // 3
         pictureIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
    }
    startActivityForResult(Intent.createChooser(pictureIntent,"Select Picture"), PICK_IMAGE_GALLERY_REQUEST_CODE);  // 4
}

The following shows the explanation of the above code.

  1. By setting the type we specify we only need images no videos or anything else.
  2. The CATEGORY_OPENABLE used to indicate that Intent only wants URI’s that can be opened. You can read more category openable here in this link.
  3. The mimeTypes specify that we are only interested in jpeg or png type images.
  4. The chooser only shows if there are multiple options available else we simply open up the Documents app.

Crop The Selected Picture

Once you’ve selected the image the onActivityResult method will get hit and we only need to update that method. Add the update method code inside the onActivityResult method.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(requestCode == CAMERA_ACTION_PICK_REQUEST_CODE && resultCode == RESULT_OK) {
          Uri uri = Uri.parse(currentPhotoPath);
          openCropActivity(uri, uri);
    } else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
          Uri uri = UCrop.getOutput(data);
          showImage(uri);
    } else if (requestCode == PICK_IMAGE_GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
          Uri sourceUri = data.getData(); // 1 
          File file = getImageFile(); // 2
          Uri destinationUri = Uri.fromFile(file);  // 3
          openCropActivity(sourceUri, destinationUri);  // 4 
    }
}

The below number points tell you what’s happening inside the updated onActivityResult method.

  1. Get the selected image Uri from data.
  2. Create the image File where you want to store the cropped image result.
  3. Simply creates the destinationUri fromFile utility method.
  4. Calls the openCropActivity method. Here we’re passing different Uri’s because our sourceUri is different where our selected image is stored and destinationUri where we want to save our cropped image result.

Now if you run the application you’ll see that all the application functionality will work perfectly. I hope this article will help you to crop the profile picture image. If you’ve any queries regarding this post please do comment below.

You can get the complete source code of above app from GitHub.

Thank you for being here and keep reading…

The post Android Crop Image Using UCrop Library appeared first on Coding Infinite.

]]>
Android Cab Booking App Tutorial Part 3 https://codinginfinite.com/android-cab-booking-app-tutorial-custom-google-map-marker-animation/ Sun, 30 Dec 2018 09:57:09 +0000 https://codinginfinite.com/?p=2089 This story is the third part of our Android Cab Booking App tutorial If you didn’t read the previous ones you can start here. Previously In Android Cab Booking App In the previous article, we discussed how to read the online-drivers from Firebase Realtime Database, create the data structure for Drivers and animate multiples markers on Google Maps....

The post Android Cab Booking App Tutorial Part 3 appeared first on Coding Infinite.

]]>
This story is the third part of our Android Cab Booking App tutorial If you didn’t read the previous ones you can start here.

Previously In Android Cab Booking App

In the previous article, we discussed how to read the online-drivers from Firebase Realtime Database, create the data structure for Drivers and animate multiples markers on Google Maps.

Also, I update the apps on GitHub. You can follow me by looking at the code. Java application link and Kotlin application link.

9. Show progress animation inside PinView

If you guys see the demo in the first article, you’ll understand that as soon as the Google Maps camera movement start. The ProgressBar inside the PinView start animating until the nearest Driver found and after that, we’ll calculate the distance with DistanceMatrixAPI between the nearest Driver location and the PinView location. Later the distance calculation we hide the ProgressBar and show the distance duration inside the PinView.

So, in order to animate the ProgressBar, we need to implement OnCameraMoveStartedListener on MainActivity. The OnCameraMoveStartedListener has its callback function which defines what action needs to be done when the camera starts its movement. In this callback, we need to start the ProgressBar animation.

Let’s start the ninth part of Cab Booking Application by implementing the OnCameraMoveStartedListener on MainActivity.

class MainActivity : AppCompatActivity(), GoogleMap.OnCameraIdleListener, GoogleMap.OnCameraMoveStartedListener {
      private var googleMap : GoogleMap? = null
      override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            .......
            .......
            val supportMapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment supportMapFragment.getMapAsync { googleMap ->
                    googleMap.setOnCameraIdleListener(this)
                    googleMap.setOnCameraMoveStartedListener(this)  // implements the OnCameraStartedListener                        
                    this.googleMap = googleMap 
            }
     }

The OnCameraMoveStartedListener has one abstract method and we need to implement it as well. Below is the onCameraMoveStarted overridden method.

override fun onCameraMoveStarted(p: Int) {
     pinTimeTextView.visibility = GONE
     pinProgressLoader.visibility = VISIBLE
}

In the onCameraMoveStarted method, we show the ProgressBar and hide the previously shown TextView. Now if you run the application, you’ll see that when the app opens the ProgressBar start animating inside the PinView.Google Maps PinView Animation

10. Get the nearest driver and calculate the Distance

In order to get the nearest Driver, we need to know the PinView location exactly where the user stops while dragging it. If you guy’s remembered from the previous article, we exactly face the same problem when we need to Reverse Geocode a location where user drags the Pin. So, for this, we need to update our onCameraIdle method inside the MainActivity.

Update the onCameraIdle method inside the MainActivity class.

override fun onCameraIdle() {
    val position = googleMap.cameraPosition.target
    viewModel.makeReverseGeocodeRequest(position, geoCoderValue.value)
    viewModel.onCameraIdle(latLng);
}

Next, add the below method inside the MainActivityViewModel class.

fun onCameraIdle(latLng: LatLng) {
        launch(coroutineContext + Dispatchers.Default) {
            if (driverRepo.allItems().isNotEmpty()) {
                val driver = driverRepo.getNearestDriver(latLng.latitude, latLng.longitude)
                driver?.let { calculateDistance(latLng, it) }
            }
        }
    }

At first, we launch a coroutine because the getNearestDriver method is a suspended method. After that, we check if the List<Driver> that we’re keeping inside the DriverCollection is not empty. Later we call the getNearestDriver method inside DriverCollection and call the calculateDistance method if the nearest Driver is not null.

You can get the DriverCollection class from GitHub.

Add the below calculateDistance method inside the MainActivityViewModel class.

private fun calculateDistance(latLng: LatLng, driver: Driver) {
    launch(coroutineContext + Dispatchers.IO) {  // 1
        val destination = arrayOf(driver.lat.toString() + "," + driver.lng.toString())
        val origins = arrayOf(latLng.latitude.toString() + "," + latLng.longitude.toString())
        DistanceMatrixApi.getDistanceMatrix(googleMapHelper.geoContextDistanceApi(), origins, destination)  // 2
            .mode(TravelMode.DRIVING)
            .setCallback(object : PendingResult.Callback<DistanceMatrix> {

                override fun onFailure(e: Throwable?) {
                }

                override fun onResult(result: DistanceMatrix?) {
                    if (result != null)
                        _calculateDistance.postValue(result.rows[0].elements[0].duration.humanReadable)  // 3
                }
            })
    }
}

Let’s go through the logic behind the above code:

  1. launch a coroutine in IO dispatcher, because it is a good approach to execute all network requests inside the IO dispatcher.
  2. The DistanceMatrixApi class is from the dependency which we add in the first article. You can read more about how to use the library here on GitHub.
  3. If the DistanceMatrix result is not null then we pass the result to MainActivity via LiveData to show the distance duration inside the PinView.

Note: The distance we’re calculating is from Driver location to PinView location. That’s how the Careem application shows the calculated distance inside PinView.

Next, add the geoContextDistanceApi method inside the GoogleMapHelper class.

class GoogleMapHelper(private val resources : Resources) {

   companion object {
       private val geoApiContextBuilder = GeoApiContext.Builder()
   }

   .......
   .......

   private fun distanceApi(): String {
        return resources.getString(R.string.google_distance_matrix_api_key)  // replace with your own distance matrix api key.
   }

   fun geoContextDistanceApi(): GeoApiContext {
        return geoApiContextBuilder
            .apiKey(distanceApi())
            .build()
   }
}

Now that we’ve added the utility method inside the GoogleMapHelper class. We need to declare _calculateDistance inside MainActivityViewModel class in order to observe from MainActivity.

private val _calculateDistance = MediatorLiveData<String>()

val calculateDistance : LiveData<String> = _calculateDistance

Next, add the following code inside the MainActivity onCreate method to observe calculateDistance instance from MainActivityViewModel class.

// 1
viewModel.calculateDistance
            .observe(this, Observer { distance ->
                   pinTimeTextView.text = distance
                   pinTimeTextView.visibility = VISIBLE
                   pinProgressLoader.visibility = GONE
            })

When the Observer interface invoked we simply set the distance to pinTimeTextView and hide the currently showing pinProgressLoader.

So, here we’ve completed the tenth part of the Frisbee application. Now when you run the application you’ll see the nearest Driver duration inside the PinView and also the duration updates when the Google Maps camera movement stops. Build and run to view the application progress. Here is mine:

Google Map Custom PinView With Text

Bravo! this concludes that our Frisbee application is complete. Hopefully, the next article will be on Driver application and it’ll be the last article on Android cab booking app tutorial. Stay tuned!

Thank you for being here and keep reading…

Previous Part

The post Android Cab Booking App Tutorial Part 3 appeared first on Coding Infinite.

]]>