Pankaj Valani

Pankaj Valani's Posts

Sr. Android developer

Room Database in android java

Hi everyone, in this post, we will discuss Room Database in android java.

Below are all steps covered in this blog

  • How to use the Room database
  • How to add Room Database in android studio
  • Insert,Update,Delete record
  • How to pass query in Database

What is a Room?

  • The Room strong library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.

  • Normally Room databases are fast created and have good performance like reading, updating and deleting records. Room Database makes everything easy and fast

  • Room Database more detail open this link: https://developer.android.com/training/data-storage/room/

Components of Room Here room have main 3 components

Entity:

  • Instead of creating the SQLite table, we will create the Entity. An entity is nothing but a model class annotated with @Entity. The variables of this class are our columns, and the class is our table.

Database:

  • It is an abstract class where we define all our entities.

DAO:

  • Stands for Data Access Objects. It is an interface that defines all the operations that we need to perform in our database.

Demo App Create

  • First, we create a new project in android studio.
  • Name of my project "Room DataBase"

Adding Dependencies

  • Add needed dependencies for the room database.
  • Android studio in this file add dependencies "build.gradle".
  • See the below image and add the latest version room database replace here "$room_version" add original version

First, we will create DAO class:

  • This DAO class-main work intermediary between the user and database. All performed operations are defined here.
  • Below create StudentDao class
@Dao
public interface StudentDao {

@Query("SELECT * FROM Student")
List<Student> getAll();

@Insert
void insert(Student student);

@Update
void updateTask(Student student);

@Delete
void deleteTask(Student student);
}

Nowhere explain all components of StudentDao Class

  • Compulsory add class upper "@Dao" keyword
  • Three methods create insert, update, delete
  • Most important thing here is "@Query"

What is a Query?

  • Using query to get database existing record.
  • @Query("SELECT * FROM Student") this query gets all student records.
  • But the user wants to get only the standard "5" student record and only get how to pass a query?
    @Query("SELECT * FROM STUDENT where std = :std")

    List<Student> dataCheck(String std);
  • Here "std" id table field name
  • Call this method "data check(String std)" pass a string in "5" and database in getting only 5 stander student record
  • So this concept use the query parameter

Second steps create student model class

@Entity(tableName = "student")
public class Student implements Serializable {

@PrimaryKey(autoGenerate  = true)
private int id;

@ColumnInfo(name = "std")
private int std;

@ColumnInfo(name = "name")
private String name;

public int getId() {
    return id;
  }

public void setId(int id) {
    this.id = id;
  }

public int getStd() {
    return std;
  }

public void setStd(int std) {
    this.std = std;
  }

public String getName() {
    return name;
  }

public void setName(String name) {
    this.name = name;
  }
}
  • PrimaryKey: auto increment values
  • tableName : user wants to set the table name
  • ColumnInfo: give the table in columns name

Third steps Create Database class:

@Database(entities = {Student.class}, version = 1)
public abstract class AppDatabase extends     RoomDatabase {
public abstract Student studentDao();
}
  • User wants to add multiple tables how can add like that:

@Database(entities = {Student.class,Abc.class,Xyz.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract Student studentDao(); }

  • To create a new model class like Abc.class and Xyz.class etc same method.

Fourth step inserts, update and delete records create separate method:

 public class InsertUpdateDeletRecord {

    private String DB_NAME = "db_task";

    private Student Student;
    public studentRepository(Context context) {
        Student = Room.databaseBuilder(context, Student.class, DB_NAME).build();
    }

    public void insertTask(String std,String name) {

        insertTask(std, name);
    }

    public void insertTask(String std,String name) {
        Student student = new Student();
        student.setstd(std);
        student.setname(name);

        insertTask(student);
    }

    public void insertTask(final Student student) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                Student.daoAccess().insertTask(student);
                return null;
            }
        }.execute();
    }

    public void updateTask(final Student student) {
        student.setModifiedAt(AppUtils.getCurrentDateTime());

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                Student.daoAccess().updateTask(student);
                return null;
            }
        }.execute();
    }

    public void deleteTask(final int id) {
        final LiveData<student> task = getTask(id);
        if(task != null) {
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    Student.daoAccess().deleteTask(task.getValue());
                    return null;
                }
            }.execute();
        }
    }

    public void deleteTask(final student student) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                Student.daoAccess().deleteTask(student);
                return null;
            }
        }.execute();
    }

 }

Sample Implementation of basic CRUD operations using ROOM

Insert:

 InsertUpdateDeletRecord 
 insertUpdateDeletRecord = new 
 InsertUpdateDeletRecord(getApplicationContext( ));
 String std = "5";
 String name = Android";
 insertUpdateDeletRecord.insertTask(title, 
 description);

Update:

 InsertUpdateDeletRecord 
 insertUpdateDeletRecord = new 
 InsertUpdateDeletRecord(getApplicationContext( ));
 Student student = 
 insertUpdateDeletRecord.getTask(2);
 student.setName("Java");
 student.setStd("6");
 insertUpdateDeletRecord.updateTask(student);

Update:

 InsertUpdateDeletRecord 
 insertUpdateDeletRecord = new 
 InsertUpdateDeletRecord(getApplicationContext());
 insertUpdateDeletRecord.deleteTask(3);
July 25, 20214 minutesPankaj ValaniPankaj Valani
How to integration google ad in android app. Part - 1

Dear, Friend in this blog we discussion google ad integration. Many companies work in client base & product base. Product based company in very very important ad integration in the app. Multiple types of AD are available like a Facebook ad, start-up ad, google ad, etc. Today we learning google ad integration.

Type of Google AD:

  • Banner AD
  • Interstitial Ad
  • Rewarded Video Ad
  • Native Ad

1.Banner Ad

Banner Ads occupy only a portion of the screen depending on the ad size that is created. It comes in multiple sizes Standard, Medium, Large, Full-Size, Leaderboard, and Smart Banner. Smart banners are very useful when you target multiple device sizes and fit the same ad depending on the screen size.

2.Interstitial Ads

Interstitial ads occupy the full screen of the app. Basically, they will show on a timely basis, between screen transition or when the user is done with a task.

3.Rewarded Video Ad

This ad shows a video-type ad.

4.Native Ad

In this app in full description ad showing.

Create a new project

Create a new project in Android Studio from File ⇒ New Project.

Open build. Gradle and add play services dependency as AdMob requires it.

compile ‘com.google.android.gms:play-services-ads:11.8.0’

build.gradle
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'

    compile 'ccom.google.android.gms:play-services-ads:11.8.0'
}

Add the App ID and Ad unit IDs to your strings.xml.

    AdMob
    Interstitial
    Welcome to Admob. Click on the below button to launch the Interstitial ad.
    Show Interstitial Ad
    Show Rewarded Video Ad

    ca-app-pub-XXXXXXXX~XXXXXXXXXXX
    ca-app-pub-XXXXXXXX~XXXXXXXXXXX
    ca-app-pub-XXXXXXXX~XXXXXXXXXXX
    ca-app-pub-XXXXXXXX~XXXXXXXXXXX

Create a class named MyApplication.java and extend the class from Application. In this application class, we have to globally initialize the AdMob App Id. Here we use MobileAds.initialize()

MyApplication.java

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
         MobileAds.initialize(this, getString(R.string.admob_app_id));
    }
}

Open AndroidManifest.xml and add MyApplication to tag.

<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-3940256099942544/6300978111"/>
January 13, 20212 minutesPankaj ValaniPankaj Valani
How can I run my app on my phone without USB connection with my pc

We will learn to run the app without connecting a USB cable in this blog. The main purpose of this blog is to let users run apps without any restriction. Sometimes if the cable is connected with the device and if the device cable gets disturbed then the app does not run properly.

Let's see how we can run the app without cable.

Step 1: Click File Menu => Settings

2021-01-08-5ff84742652f6

Step 2: Click Plugins

2021-01-08-5ff8475b600ed

Step 3: Install ADB Wi-Fi Plugin

2021-01-08-5ff8476c3d0f6

Notes:

  • In the third image, I already installed the plugin in my android studio. But in your case, you may need to install it.
  • Then your android studio restarts.

After the restart, your android studio will show the "ADB Wifi" option showing as per the following image

2021-01-08-5ff847ae6fa6b

Click ADB Wifi and the below screen will be displayed.

2021-01-08-5ff847f31608f

  • Click to connect
  • Make sure your device and pc are connected to the same wifi. Otherwise, it will not get connected.
  • You will need to connect one time when the android studio is opened for the first time.
November 21, 20201 minutePankaj ValaniPankaj Valani
How to create APK and Bundle in android java

While developing apps in Android Studio, developers can create an APK file and share it with other developers or to QA people for testing purposes.

APK can be created with two types:

  1. Debug APK
  2. Release APK
  • Debug APK is very fast in building and Release APK is a little bit slow.

How to create a Release APK File:

  • Flowing below all steps
  • Open android studio
  • Click Build on the toolbar
  • Click Generate Signed Bundle/APK.
  • Select APK
  • Click the Next button
  • After clicking the next button, you will see the following dialog.
  • Click the "Create new..." button, highlighted in the following image by a red circle if you are creating an APK for the first time. Otherwise, you can choose from existing.
  • It will open one another dialog box
  • Key store path in select save location .jks file
  • Fill in all the information
  • Set a valid name for the key alias
  • Set 100 as validity years
  • Fill Certificate Information
  • Click OK
  • After you click on it, select "release" from the dialog box
  • Select "V1 (Jar Signature)" & "V2 (Full APK Signature)" checkboxes
  • Click Finish
  • It will start the process of building your APK

How to create a debug .apk file

  • Click Build and select Build Bundles(s)/APK(s)
  • Select "Build APK(s)" from the dialog box
  • It will start the process of building your debug APK file creating
November 25, 20201 minutePankaj ValaniPankaj Valani
Useful Shortcut Keys for Android Studio

Hello, friend, the shortcut way everyone likes. but remember a shortcut is to improve yourself and save time. It's a very good way. so in this blog learning the android studio shortcut key.use all short cut key and save time and performance improve

Search Keys:

  • Shift+Shift — Search Everywhere
  • Ctrl+F — Find Text within a Single File
  • Ctrl+Shift+F-Find Text in All Files
  • Ctrl+R — Replace Selected Text in a Single File
  • Ctrl+Shift+R — Replace Selected Text in all Files (Be Careful while Using This)
  • Ctrl+Shift+A —Search for IDE Commands

Navigation Keys:

  • Ctrl+N — Navigate to Class
  • Ctrl+Shift+N — Navigate to a File
  • Ctrl+B — Jump to Declarations
  • Alt+ ↑ — Jump to the Previous Method
  • Alt+↓ — Jump to Next Method
  • Ctrl+G — Jump to Line
  • Ctrl+E — Recent Files
  • Ctrl+Shift+Backspace — Jump to Last Edited Location
  • Ctrl+B — Find Declarations
  • Ctrl+Left Mouse(or)Ctrl+Alt+F7— Show Usage
  • Alt + F7 / Ctrl + F7 — Find usages /Find usages in file
  • Ctrl+Shift+B — Find Implementations
  • F3 — Find Next
  • Shift+F3 — Find Previous

BookMark Keys:

  • F11 — Toggle bookmark
  • Ctrl+F11 — Toggle bookmark with the mnemonic(0–9 or A-Z)
  • Ctrl +(0–9) — Go to numbered bookmark
  • Shift+F11 — Show all Bookmarks
  • Ctrl + Shift + F7 — Highlight usages in file

Selection Keys:

  • Ctrl + W — Extend selection (selects a word->line->method->Class )
  • Ctrl +Shift+ W — Decrease Selection
  • Alt + J — Select next occurrence
  • Ctrl + Alt + Shift + J — Select all occurrences
  • Alt + Shift + J — Unselect occurrence
  • Ctrl+Shift+V — Paste from recent buffers (from a History of Copied Contents)

Editing Keys:

  • Ctrl+F6 — Refactor Code
  • Ctrl+D — Duplicate a Line/Selected part
  • Ctrl+Y — Delete a Line/Selected part
  • Ctrl+Q — Quick Documentation
  • Ctrl + Space — Code completion
  • Ctrl+Shift+Space — Smart code completion (by expected type removes unrelated suggestions)
  • Alt+Insert — Generate Code
  • Ctrl+J — Insert Live template
  • Ctrl + O — Override methods
  • Ctrl + I — Implement methods
  • Ctrl + Alt + T — Surround with…
  • Ctrl + / — Comment / uncomment with line comment
  • Ctrl + Shift + / — Comment / uncomment with block comment
  • Ctrl+Alt+L — Reformat code

Run:

  • Ctrl + F9 — Compile and Run Make a project
  • Ctrl + Shift + F9 — Compile selected file, package or module
  • Shift + F10 — Run
  • Shift + F9 — Debug
  • Ctrl + Shift + F10 — Run context configuration from editor

Debugging:

  • F8 / F7 — Step over / into
  • Shift + F7 / Shift + F8 — Smart step into/Step out
  • Alt + F9 — Run to cursor
  • Alt + F8 — Evaluate expression
  • F9 — Resume program
  • Ctrl + F8 — Toggle breakpoint
  • Ctrl + Shift + F8 — View breakpoints
November 05, 20202 minutesPankaj ValaniPankaj Valani
How to create different type shape in android java

Hello, wonderful friends today in this blog on learning in android XML files creating different types of shape creating. A shape is an XML file that defines a geometric shape, including strokes, colors, and gradients

First Creating .xml file:

  1. Open android studio
  2. Go to drawable
  3. Right-click drawable menu

Follow below image steps:

2020-12-18-5fdc731fe3b6a

Now friend starts coding:

  • Creating a capsule shape flow below code:
<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:bottomLeftRadius="30dp"
android:bottomRightRadius="30dp"
android:radius="60dp"
android:topLeftRadius="30dp"
android:topRightRadius="30dp"/>

Corners:

The below image is showing the shape corner radius

Solid:

Solid means shape inner color “#CFCFCF”

Padding:

There is always developer confusion between padding and margin. Both provide extra space/gap inside or outside the container. In simple words, margin means to push outside, whereas padding means to push inside.

Size:

It's very simple shape width - height

October 07, 20201 minutePankaj ValaniPankaj Valani
How to create any API response model class in android java
  • Developer use API calling retrofit, volley JSON or other tools but API response check-in postman time confusion how to creating this response model class
  • So a friend in this topic I will try your confusion remove flow below all steps and 5 min inner creating a wonderful model class

Step: 1 Android studio in install "RoboPOJOGenerator"

  • Location in the android studio:
  1. Open android studio
  2. Go to File
  3. Go to Setting
  4. Click plugin
  • check the below image && click and install RoboPOJOGenerator then your android studio restart
android

Step: 2 How to open RoboPOJOGenerator

  1. Open android studio
  2. Go to File
  3. Select directory below the image in showing related select any one directory
  4. Right-click - select New - then below showing "RoboPOJOGenerator"
android

Step: 3 How to add postman response

  1. Postman response copy
  2. Paste this response in "RoboPOJOGenerator" in one black color dialog showing in android studio
  3. Left top side one cursor visible on this area in paste this response
  4. Select "GSON" option in "RoboPOJOGenerator"
  5. Last click generate button after a few moments your model class is ready
android
android
August 15, 20201 minutePankaj ValaniPankaj Valani
Facebook Login With Firebase In Android Java

1.Add this library build.gradle(:app)

  • This library user for firebase integration dependencies
  • { 
       implementation 'com.google.firebase:firebase-auth:19.4.0'
    }

2.Add this permission in AndroidManifest.xml

  • This permission use internet connection checking
{
<com.facebook.login.widget.LoginButton          
android:id="@+id/login_button"          
android:layout_width="match_parent"          
android:layout_height="match_parent"          
android:layout_gravity="center"
android:visibility="gone"/>
}

3.Activity in add this permission

  • This permission is for user data. Without this permission user data not meet

  • loginButtonThis button is Facebook button

  • LoginManager.getInstance().logInWithReadPermissions(FacebookLoginActivity.this, Arrays.asList("email", "public_profile"));
  • loginButton.setReadPermissions("email", "public_profile");

4.Initialize Authentication:

void initializeAuthentication(){
   FirebaseAuth  mAuth = FirebaseAuth.getInstance();
   GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
   .requestIdToken(getString(R.string.default_web_client_id))
   .requestEmail()
   .build();
   mGoogleSignInClient = GoogleSignIn.getClient(this, so); 
}

7.Add This Function:

  • This function user login result return
void faceBookLogin(LoginResult loginResult){
   setFacebookData(loginResult);
   Profile profile = Profile.getCurrentProfile();      
   if (profile != null) {        
      String avatar = ImageRequest.getProfilePictureUri(profile.getId(), 200, 200)
     .toString();    
   }    handleFacebookAccessToken(loginResult.getAccessToken());
}

7.Handle Token :

  • This token return firebase login fails or not an event
private void handleFacebookAccessToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)           
.addOnCompleteListener(this, new OnCompleteListener() {                
      @Override                
      public void onComplete(@NonNull Task task) {
      if (task.isSuccessful()) {
      FirebaseUser user = mAuth.getCurrentUser();
      user.getIdToken(true).addOnCompleteListener(new OnCompleteListener() {
      @Override
      public void onComplete(@NonNull Task task) {
            String token = task.getResult().getToken();
       }
    });
 } else {
      String errorCode = String.valueOf(task.getException());
      Toast.makeText(FacebookLoginActivity.this, "Login failed.", Toast.LENGTH_SHORT).show();
                    } 
            }
    });
}

Notes:

  • “Default_web_client_id” this keyword, not changes because creating google-services.json file time automatically this keyword in add values so this key work put at its
How to creating google JSON file : JSON File

Add google JSON file this location in android studio:

facebook
July 28, 20201 minutePankaj ValaniPankaj Valani