Posts

Showing posts from 2020

How to Create an Emulator in Android Studio

Image
In this article, we will take a look at how to create an emulator in Android Studio.
First, open Android Studio to create a project or open an existing project. Now, Click on the Tools in the top menu and then on AVD Manager.

This opens the Android Virtual Device Manager where we can create our emulators.


Start the creation of the emulator by clicking on the Create Virtual Device button. It opens a new screen where we select the device hardware.


In addition to the available hardware profiles, we can import an existing profile or create new hardware by clicking on the options at the bottom left.


Click Next after selecting the hardware profile. Now we are asked to select the OS Version. Select the preferred one and download it if necessary. After that, click Next.




Verify the configuration of the selected hardware. If we want to tweak more than the AVD name then in the advanced settings we can change the number of cores, RAM, internal Storage space, external storage space and more.


Fina…

Get the Result From Last Activity When Middle Activity Is Finished

We usually get the result from an activity by starting it with startActivityForResult() and listening to the onActivityResult() in the calling activity. But there are some cases, where we may want the result to be received from the subsequent activities rather than the immediately invoked activity.
For example, let's take three activities named FirstActivity, SecondActivity (middle activity) and ThirdActivity (last activity). They have a feature through which the first activity opens the second activity and the second activity opens the third activity closing itself. Now, the third activity has to send the result back to the first activity.
In this article, we will take a look at this scenario where we have to send the result from the last activity and read it in the first activity.
As usual, we start the middle activity for the result from the first activity.
// Open the middle activity startActivityForResult( Intent(context, SecondActivity::class.java), …

How to Change Material Chip Text Size, Text Style and Font

Chips in Android is a Material Design Component used primarily for actions or choice or during filters or as an input.
The attributes like textColor, textStyle and fontFamily are ignored when added to the Material Chips directly. We need to modify these values using textAppearance.
<com.google.android.material.chip.Chip android:id="@+id/maleChip" style="@style/Widget.MaterialComponents.Chip.Choice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checkable="true" android:layoutDirection="locale" android:text="@string/chip_text_male" android:textAppearance="@style/AppTheme.GenderChip" android:textColor="@color/colorWhiteText" app:chipBackgroundColor="@drawable/select_chip" app:chipEndPadding="@dimen/chip_horizontal_margin" app:chipStartPadding="@dimen/chip_horizontal_margin" />
The te…

Use Kotlin Android Extensions to Replace findViewById

Kotlin Android Extensions is a great way to avoid writing findViewById in the activity or fragment.

Simply, add the kotlin-android-extensions plugin to the module level build.gradle file.
apply plugin: 'kotlin-android-extensions'
Only one step to enable the feature. Now, we can remove the manual initializations.
// Initialize the UI elements val constraintLayout = findViewById<ConstraintLayout>(R.id.coordinatorLayout) val responseTextView = findViewById<TextView>(R.id.responseTextView) val bottomAppBar = findViewById<BottomAppBar>(R.id.bottomAppBar) val fab = findViewById<FloatingActionButton>(R.id.fab) val productRecyclerView = findViewById<RecyclerView>(R.id.productRecyclerView) val filterButton = findViewById<Button>(R.id.filterButton) val sortButton = findViewById<Button>(R.id.sortButton)
The compilers suggest us only one import to get all the synthetic properties available in the layout. If the above views are available in the activ…

Add View Binding to Replace findViewById

View Binding initializes every UI element which has an id in the layout files and exposes them to the developers through a generated class.

If you think writing findViewById in every activity or fragment should not be a developer's job then you are reading the right article.

Does the code inside the activity or fragment start like this?
Manual UI elements initialization

// Initialize the UI elements final ConstraintLayout constraintLayout = findViewById(R.id.coordinatorLayout); final TextView responseTextView = findViewById(R.id.responseTextView); final BottomAppBar bottomAppBar = findViewById(R.id.bottomAppBar); final FloatingActionButton fab = findViewById(R.id.fab); final RecyclerView productRecyclerView = findViewById(R.id.productRecyclerView); final Button filterButton = findViewById(R.id.filterButton); final Button sortButton = findViewById(R.id.sortButton);
Butter Knife UI elements initialization

// UI elements @BindView(R.id.coordinatorLayout) CoordinatorLayout coordinatorLayo…

How to Fetch and Save Stock Price

Historical stock prices are available on a significant number of websites to download but wouldn't it be easier to use a script to fetch these prices and save it to our local machine?
In this article, we will learn how to fetch the historic stock prices of a company using Python. Let's first import the required dependencies to perform the actions.
# Get the dates import datetime # Create files in the operating system import os # Convert data frames to file formats import pandas as pd # Fetch the stock prices import pandas_datareader as web # Find relative dates of the past or of the future from dateutil.relativedelta import relativedelta
Now, create a StockPrice class with a helper function fetch to fetch the stock price and save function to save the stock prices to the local folder.
class StockPrice: """ Provide functionality to fetch the historical stock prices and save it to a path """ def __init__(self): ""&q…

Alert Dialog - Material Design Component

Image
Alert Dialog in Android is a blocking window shown to the user for immediate user attention and interaction.
To build and show an alert dialog, we will be using MaterialAlertDialogBuilder. It is an extension of AlertDialog.Builder that we are familiar with but provides Material theming to the dialog.
The below pictures shows the subtle differences in using MaterialAlertDialogBuilder and AlertDialog.Builder.


Before, we start implementing the Material Alert Dialog, add Material Design Components to our project. Now, let's create the Alert Dialog.
private fun showAlert(context: Context) { // Build the dialog val builder = MaterialAlertDialogBuilder(context) // Set Dialog title .setTitle(context.getString(R.string.alert_dialog_title)) // Set Dialog message .setMessage( context.getString( R.string.alert_dialog_message, nameTextView.text.toString().capitalize(Locale.US) ) ) //…

Add Navigation Components to the Project

Image
Navigation helps the users navigate inside the application between fragments and the activity. Navigation Component, on the other hand, is part of Android Jetpack and helps us (the developers) build navigation for component clicks, deep links and more.

Navigation Component consists of Navigation Graph, Nav Host and the Nav Controller. We will talk about them in detail throughout the article and implement it.


1. First, add the dependencies to the module level build.gradle file.
implementation 'androidx.navigation:navigation-fragment-ktx:2.2.0' implementation 'androidx.navigation:navigation-ui-ktx:2.2.0'
2. Create a Nav Host
The Nav Host is a container for all the fragments to be shown on. With the help of Nav Controller, the developer can navigate the user between fragments and nested nav graphs.
<fragment android:layout_width="match_parent" android:id="@+id/nav_host_fragment" app:defaultNavHost="true" app:navGraph="@navi…

Bottom App Bar for Android - A Material Design Component

Image
Similar to an App Bar (Top App Bar or Toolbar), Google introduced the Bottom App Bar as part of the Material Design Components back in 2018.
Let's get into the implementation by adding a dependency to the build.gradle file.
implementation "com.google.android.material:material:1.2.0-alpha03"
In the next step, let's add the BottomAppBar and the FloatingActionButton to the activity layout.
<com.google.android.material.bottomappbar.BottomAppBar android:id="@+id/bottomAppBar" style="@style/Widget.MaterialComponents.BottomAppBar.PrimarySurface" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" app:hideOnScroll="true" app:fabAnimationMode="slide" app:menu="@menu/menu_main" app:navigationIcon="@drawable/ic_menu_white" /> <com.google.android.material.floatingactionbutton.FloatingActionButt…

StringRequest Volley - Retrieve Response as String

Image
Volley is an Android HTTP networking library. In the previous article, we had a glimpse of the Volley library and performed a POST request using JsonObjectRequest.
In this article, we will fetch the response as string from https://reqres.in/api/users/2 and display it as the TextView text. For this purpose, we will be using StringRequest which makes a GET request to an endpoint and returns the response as a string.
// Build the request final StringRequest stringRequest = new StringRequest(URL_USER, new Response.Listener<String>() { @Override public void onResponse(@NonNull String response) { // Api call successful Log.d(TAG, "Response: " + response); // Show the response on the screen responseTextView.setText(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(@NonNull VolleyError error) { // Api call failed // Print the error to stacktrace error.printStackTrace(); // Show th…

Perform a Post Request Using Volley

Image
Volley is a very simple customizable HTTP client introduced by Google. Volley comes with request caching, prioritization and ordering. In addition to that, making concurrent network requests and canceling them is easier with Volley.

First, create a project and add volley dependency to the module level build.gradle file.

implementation 'com.android.volley:volley:1.1.1'
Create a login screen with username, password and a login button. User is able to enter their email address and password as shown in the figure below.


Build the login payload with entered username and password.
// Build the request payload final JSONObject jsonObject = new JSONObject(); try { jsonObject.put("email", email); jsonObject.put("password", password); } catch (JSONException e) { e.printStackTrace(); }
Lets us make an API call to https://reqres.in/api/login with the built request payload to log the user in.

// Build the request final JsonObjectRequest jsonObjectRequest = new J…