InfyOm Blog

latest-post

In our daily life, we are going through lots of packages, and some of us don't know how to build our own package into Laravel.

We are going to perform the core steps to create your own package in laravel. In this tutorial we are going to build zoom package, so we will perform steps related to it.

Setup Fresh Laravel Repo 

Setup fresh laravel repo, and then create directories within it. 

for e.g Create infyomlabs/zoom-api directory into root.


Now create src directory into zoom-api

Run Composer init Into src Directory

After hitting composer init it will ask some information from you, as you can see in below image I have entered some of information. you can just hit enter if you do not want to add other information.


Add your config file (Optional)

Create directory config into src directory and add your config.php file there from where you can manage your env variables. 


Add Service Provider

Create your service provider from where you can do lots of actions. like you can publish config/routes/ migrations files from there. here we are publishing the zoom config file. 


Add your class (Which contains all functions) 

Here we have added a Zoom class which will be contained all zoom functions. 

Update Composer.json 


Finally, Test it in your existing project

Put the following code to your main composer.json (in your project's root). and hit composer update

  "repositories": [
        {
            "type": "path",
            "url": "infyomlabs/zoom-api",
            "options": {
                "symlink": true
            }
        }
    ],
    "license": "MIT",
    "require": {
        "infyomlabs/zoom-api": "dev-develop"
    },


January 27, 20211 minuteuserVishal Ribdiya

Posts

post
Here we will learn, how to export annotation drawn using PDFTron.

Events for export annotation

When we draw any annotation "annotationChanged" event will be fired, then we cache that event and we can export that annotation using "exportAnnotations".
When we draw annotation we'll save them in the database and when we reload the same document we can retrieve saved annotations from database and can again show them, we will learn that in my next blog post.
Here is example of how to save and annotation in database.

Example

WebViewer({
    path: 'path_to_the_PDFTron_'lib'_folder_on_your_server',
    css: 'webviewer_css',
    licenseKey: 'YOUR_PDF_TRON_LICENSE_KEY',
    initialDoc: 'YOUR_FILE URL' //url of a file to load
}, document.getElementById('viewer'))
    .then(function (instance) {
        let docViewer = instance.docViewer;
        let annotManager = instance.annotManager;
       
        annotManager.on('annotationChanged', (annots, action, e) => {
            if (e.imported) return;

            annotManager.exportAnnotations({
                links: false,
                widgets: false,
                annotList: annots
            }).then(function (xfdfStrings) {

                annots.forEach(function (annot) {
                    if (action === "delete") {
                        deleteAnnotation(annot.mu);
                    } else {
                        saveAnnotation(annot.mu, xfdfStrings);
                    }
                });

                if (action === "add") {
                    annotManager.selectAnnotation(annots[0]);

                    if (annots[0]['Subject'] !== 'Comment') {
                        // to open comment box
                        document.getElementById('viewer').childNodes[0].contentWindow.document.querySelector('div[data-element="annotationCommentButton"]').click();
                    }
                }
            });
        });
    });

let saveAnnotation = function (annotationId, annotationXfdf) {
    let saveAnnotationUrl = '';
    if (fromExtension) {
        saveAnnotationUrl = `YOUR_PROJECT_URL/annotations/${annotationId}`;
    } else {
        saveAnnotationUrl = `YOUR_PROJECT_URL/annotations/${annotationId}`;
    }

    $.ajax({
        url: saveAnnotationUrl,
        type: 'POST',
        data: {annotation: annotationXfdf},
        success: function (result) {
            console.log(result);
        },
        error: function (result) {
            console.log(result);
        }
    });
};

let deleteAnnotation = function (annotationId) {

    let deleteAnnotationUrl = '';
    if (fromExtension) {
        deleteAnnotationUrl = `YOUR_PROJECT_URL/annotations/${annotationId}`;
    } else {
        deleteAnnotationUrl = `YOUR_PROJECT_URL/annotations/${annotationId}`;
    }

    $.ajax({
        url: deleteAnnotationUrl,
        type: 'DELETE',
        success: function (result) {
            console.log(result);
        },
        error: function (result) {
            console.log(result);
        }
    });
};
October 10, 20201 minuteauthorMonika Vaghasiya
post
In the previous article, we learned 6 areas or tips on How to increase profits in our business - part 1.

In this article, we will learn more about how to increase profit in our business. Maximizing Profit depends on the strategies that business owners take. There are only two ways to do this:
1. Increase Prices
2. Reduce Cost.

You simply cannot say that you are going to increase the profit of your business without a specific strategy. All you can do to increase profit is to improve the variables that ultimately determine your Profitability. Let's see 7 more points to increase profit.

7. Know your sales Channel




To stimulate your sales channel, you need to generate excitement and a reason to buy. This can be done by introducing vibrant, brightly colored sales that include all your products and services and by expressing a sense of urgency, encouraging sales partners, and adding subscription sales.

8. Find a new Customer




Follow up after meetings. Contact the people you meet to see if they are likely. If they say they no longer need your services, ask them when it's a good time to call, or if they have business associates who can use what you sell now.

9. Remove unprofitable service and product




If you have more than one product or service, any analysis will determine if one is more profitable than the other. If you have a lot of products in your offering, you can trust that some of them will not make money. The trick is to find out what they are and then put in motion plans to eliminate them. The basic tool for doing this is an orderly list that ranks all your products and services showing total revenue and all direct costs and total profits.

10. Reduce labor costs with part-time workers




Employment is lower than full-time workers than part-time workers. Take advantage of this luxury by hiring multiple part-time workers. Warn that if these people are presented to your company with a full-time opportunity they will leave them first.

11. Develop a CEO monthly letter to employees to create teamwork and communication




You'll want to have monthly conversations with your team, letting them know about any updates, highlighting individual performances, and reminding them of goals for the quarter and year. This will help build team morale and focus on expectations.

12. Invest in your people




Your team will only be able to make exceptional work progress and be competent when you invest in their improvement. Invest in their continuing education and also provide the best resources to do their job effectively.

13. Send personal notes of congratulations or thank employees at their home




When you send complimentary notes to employees ’homes, it shows that you think of them as a person rather than just a worker. This helps increase employee loyalty to your company.

That's it. If you want to run a profitable business, take these tips and apply them to your business. It will help your business perform better, keep growing, and increase profits.
October 09, 20202 minutesauthorAnkit Kalathiya
post
Hello, wonderfully friends today in this blog in learning in android XML file creating different type 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
  •  flow below image steps:


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" />

  <solid android:color="#CFCFCF" />

  <padding
    android:bottom="0dp"
    android:left="0dp"
    android:right="0dp"
    android:top="0dp" />

  <size
    android:height="60dp"
    android:width="270dp" />
 
</shape>


Corners:

  • The below image is showing the shape corner radius
Solid :

  • -Solid means shape inner color “#CFCFCF”

Padding:

- There is always confusion developer 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:

  •  Its very simple shape width - height 
October 07, 20201 minuteauthorPankaj Valani
post
Today I’m going to write on Create Floating Widget never stop closing the app from the background. First of all, you must know what is the service in Android.

What is a service in Android?

A service is a component that runs in the background without direct interaction with the user. Since the service has no user interface, it is not bound to the life cycle of the activity. If you want to repeat a task, using the service is the best way.
Service stops are one of the biggest problems when you clear the application from background functions.


My service is below:

public class FloatingViewService extends Service  {

    private WindowManager mWindowManager;
    private View mFloatingView;
    private View floatingButton;
    private final static float CLICK_DRAG_TOLERANCE = 10;

    private float downRawX, downRawY;
    private float dX, dY;
    int LAYOUT_FLAG;
    private SpeechRecognizer speechRecognizer;

    public FloatingViewService() {
    }
		Context context;

    public FloatingViewService(Context applicationContext) {
        super();
        context = applicationContext;
        Log.i("HERE", "here service created!");
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
					 KeyguardManager myKM = (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
              if( myKM.inKeyguardRestrictedInputMode()) {
                  Intent i = new Intent(this,FloatingViewService.class);
                  startService(i);
//            //it is locked
                } else {
                    Intent i = new Intent(this, FloatingViewService.class);
                    startService(i);
        //it is not locked
             }
            return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mFloatingView = LayoutInflater.from(this).inflate(R.layout.floating_layout, null);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
        }

        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                LAYOUT_FLAG,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        mWindowManager.addView(mFloatingView, params);

        floatingButton.setOnTouchListener(new View.OnTouchListener() {
            private int initialX;
            private int initialY;
            private float initialTouchX;
            private float initialTouchY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        initialX = params.x;
                        initialY = params.y;
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();

                        downRawX = event.getRawX();
                        downRawY = event.getRawY();
                        dX = v.getX() - downRawX;
                        dY = v.getY() - downRawY;

                        return true;

                    case MotionEvent.ACTION_UP:

                        float upRawX = event.getRawX();
                        float upRawY = event.getRawY();

                        float upDX = upRawX - downRawX;
                        float upDY = upRawY - downRawY;
                        return true;

                    case MotionEvent.ACTION_MOVE:
                        params.x = initialX + (int) (event.getRawX() - initialTouchX);
                        params.y = initialY + (int) (event.getRawY() - initialTouchY);
                        mWindowManager.updateViewLayout(mFloatingView, params);
                        return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
AndroidManifest.xml  file and update your service declarations under the application tag. Also, add  FOREGROUND_SERVICE, INTERNET and  WAKE_LOCK .Make sure you don't forget to include them as they won't work otherwise.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
          package="com.example.endless">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">

        <service
                android:name=".FloatingViewService"
                android:enabled="true"
                android:exported="false">
        </service>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

You can use the following code to check if the service is running. If the service is already in running mode, it does not need to be restarted otherwise start in your MainActivity.

FloatingViewService mFloatingService = new FloatingViewService(getApplicationContext());
  Intent mServiceIntent = new Intent(getApplicationContext(), mFloatingService.getClass());
if (!isMyServiceRunning(mFloatingService.getClass())) {
    startService(mServiceIntent);
}

Method isMyServiceRunning() is below add this in your MainActivity.

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            Log.i ("isMyServiceRunning?", true+"");
            return true;
        }
    }
    Log.i ("isMyServiceRunning?", false+"");
    return false;
}
Then Create a Floating Widget design. Create File floating_layout.xml Like This

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RelativeLayout
        android:id="@+id/rl_close_button"
        android:layout_width="100dp"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:id="@+id/relativeLayoutParent"
            android:layout_width="80dp"
            android:layout_height="70dp">

            <RelativeLayout
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:background="@drawable/floating_round_main_shape">

                <RelativeLayout
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_centerInParent="true"
                    android:background="@drawable/floating_inner_round_shape">

                    <ImageView
                        android:layout_width="25dp"
                        android:layout_height="25dp"
                        android:layout_centerInParent="true"
                        android:src="@drawable/ic_voice_icon" />

                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>

I hope it will help these services. 
Note:-This service will run better in Oreo and above versions.


October 04, 20203 minutesauthorVivek Beladiya
post
First, create a new Android Studio project and add the dependencies and plugin. First set up OneSignal in your project.
Add OneSignal dependency and plugin to your build.Gradle app-level.

apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

dependencies {
    implementation 'com.onesignal:OneSignal:3.12.6'
}
end add OneSignal dependency to your build.Gradle project-level.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.4, 0.99.99]'
    }
}
Step: 2  Create a new OneSignal Project

  • login your OneSignal Account than create an app
    1.png 34.06 KB
  • Enter Your Android Application Name & Select platform  Google Android(FCM)
    2.png 76.02 KB
  • Generate a Firebase Server Key Read the documentation.
  •  Enter your Firebase Server Key & Firebase Sender ID.

Step: 3  Add Your Created Onesignal App ID

Add OneSignl default config  to your build.Gradle app-level.
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.myapplication.app"
        minSdkVersion 17
        targetSdkVersion 30
        versionCode 1
        versionName "1.0.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [onesignal_app_id               : "Enter Your App ID",
                                onesignal_google_project_number: " Enter Firebase Sender ID"]
    }

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
The next step is to create the class MyApplication & Declare the class MyApplication in AndroidManifest.xml.

import android.app.Application;
import android.content.Context;
import androidx.multidex.MultiDex;
import com.onesignal.OneSignal;

public class MyApplication extends Application {
    public static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        context = this;
				
        OneSignal.startInit(this)
                .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
                .unsubscribeWhenNotificationsAreDisabled(true)
                .init();
    }

    public static Context getContext() {
        return context;
    }
}
Declare the class MyApplication in AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myapplication.app">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:name="com.myapplication.app.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:requestLegacyExternalStorage="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name="com.myapplication.app.activity.SplashActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


October 01, 20201 minuteauthorVivek Beladiya
post
We are adding a sitemap in our all site pages for making sure search engines (such as Google) can find and crawl them all. 

So, I will show you how to set a sitemap on the Gatsby site.

To generate an XML sitemap, you will use the gatsby-plugin-sitemap package.

Install the package by running the following command: npm install gatsby-plugin-sitemap


How to configure

Once the installation is complete, you can now add this plugin to your gatsby-config.js, like so:

Configure siteUrl and add this {resolve: `gatsby-plugin-sitemap`} into the plugins array. code looks like


module.exports = {
  siteMetadata: {
    title: `InfyOm Technologies`,
    description: `InfyOm Technologies`,
    keyword: `InfyOm Technologies`,
    author: `@gatsbyjs`,
    siteUrl: `http://infyom.com`
  },
  flags: {
    PRESERVE_WEBPACK_CACHE: true,
  },
  plugins: [
    {resolve: `gatsby-plugin-sitemap`},
  ],}

Above is the minimal configuration required to have it work. By default, the generated sitemap will include all of your site’s pages.
you can exclude a path using the exclude option. you need to configure it

  • output (string) The file path and name. Defaults to /sitemap.xml.
  • exclude (array of strings) An array of paths to exclude from the sitemap.
code looks like,

module.exports = {
  siteMetadata: {
    title: `InfyOm Technologies`,
    description: `InfyOm Technologies`,
    keyword: `InfyOm Technologies`,
    author: `@gatsbyjs`,
    siteUrl: `http://infyom.com`
  },
  flags: {
    PRESERVE_WEBPACK_CACHE: true,
  },
  plugins: [
    {
	resolve: `gatsby-plugin-sitemap`,
    options: {
      output: `/some-other-sitemap.xml`,
        exclude: [`/category/*`, `/path/to/page`],
		}
	},
  ],
}
NOTE: This plugin only generates an output when run in production mode! To test your sitemap, run: gatsby build && gatsby serve

now we are done and open sitemap using your domain. for ex. https://xxx.com/sitemap.xml










September 28, 20201 minuteauthorShailesh Ladumor
post
As we discussed earlier that we cannot measure Employee Morale directly but we need to look at other organizational aspects. Let’s discuss which aspect we can use and how we can measure employee morale.

Measurement of Morale 
  • Observation 
  • Survey 
  • Periodic Interview
  • Attitude Measurement  
  • Opinion Analysis
  • Morale Indicators
    • Productivity
    • Absenteeism
    • Turnover
    • No. of accident
  • Use suggestion Box 

Observation

We can observe things like how employees are performing their role, their work attitude, and behavior at the workplace. These things can be done by superior by observing subordinates. However the observation method is not used frequently to measure Employee Morale as it has many demerits like overburden on employees, Superior may be bias etc.

Survey
We can use the Survey method to check morale levels in the organization. We can design  questions according to our purpose of measuring morale & Organizational Goals.

Periodic Interview
Management can ensure the efficiency of work by taking regular interviews in the organization. Management can do the job satisfaction survey to know the level of Morale in the organization.

Attitude Measurement 
The attitude survey is also known as the morale Survey. We can use the questionnaire or can take face-to-face personal interviews with employees. If the employee strength is high then we can use a random sampling method. We can design the question about their job, co-workers, Supervision, and Organization. But we need to pre-decide the questions & keep them in written documents. 

Opinion Analysis
We can do opinion analysis as well. We can ask for various quotations from employees regarding existing Policies, Strategies, Rules, and Regulations in the organization. 

Morale Indicators
We can use morale indicators like Productivity, Absenteeism, Turnover. No. of Accident etc. low Productivity, high Absenteeism, and high Turnover are signs of low morale in the organization. On the other hand, the high Productivity, low Absenteeism, low Turnover rate are the sign of high Employee Morale in organization. 

Use Suggestion Box
We can use a Suggestion Box where the employees can give their Inputs related to their work and workplace. By doing this we came to know about the employees’ likes & dislikes.

Importance of High Morale-
We cannot underestimate morale at our workplace as we know that happy employees are more productive. Job satisfaction matters to keep the workforce happy. Happy employees bring success to organizations by their efficient work, loyalty, and commitment which has a direct impact on organizational growth and profitability.

Demerits of Low Employee Morale-
The low morale leads to many problems in the organization as the employees are not happy with their work. high turnover, absenteeism, unclear expectation from both side Employees as well as Employer, increase in grievances and complain, lack of peaceful industrial relation, increase accident rate, Increase in industrial disputes, etc. there all problem decreased the profitability, competency in market & Goodwill, so the workforce with low morale seems dangerous for the organization.

To pen down, we can say that we need to take care of our employees, make them happy and they will take care of our business. For this, we need to maintain high morale in our organization.


September 25, 20203 minutesauthorMariyam Bemat
post
What is a recycler view?

  • RecyclerView is used to show the data in the form of a scrollable list. It is a ViewGroup to display a large set of data. For each item in a large dataset, it displays a View. So RecyclerView is very useful no use the scrollable list.

Why use RecyclerView in Android?

  • One reason is so we can create a List through the LinearLayout and the orientation can be vertical. For example, in the Facebook application, all parameters will be the same as share, comment, like, etc. Now if we will take LinearLayout, all the views will create separate views in the memory.
Add dependencies :



dependencies {  

    implementation "androidx.recyclerview:recyclerview:1.1.0"
} 

Notes:

  • Androidx in recycler view dependencies:  implementation "androidx.recyclerview:recyclerview:1.1.0"
  • Your android studio, not androidx:  implementation 'com.android.support:recyclerview-v7:28.0.0'

Now we will add the RecyclerView layout in our activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
xmlns:app="http://schemas.android.com/apk/res-auto"  
xmlns:tools="http://schemas.android.com/tools"  
android:layout_width="match_parent"  
android:layout_height="match_parent"  
tools:context=".MainActivity">  
  
<androidx.recyclerview.widget.RecyclerView  
    android:id="@+id/recyclerView"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent" />  
  
</RelativeLayout>

We create a layout file named row_layout.xml.

<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
xmlns:app="http://schemas.android.com/apk/res-auto"  
xmlns:tools="http://schemas.android.com/tools"  
android:layout_width="match_parent"  
android:layout_height="match_parent"  
tools:context=".MainActivity">  
  
<androidx.recyclerview.widget.RecyclerView  
    android:id="@+id/recyclerView"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent" />  
  
</RelativeLayout>

We create a layout file named row_layout.xml

<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="horizontal">  
  
    <ImageView  
        android:id="@+id/image"  
        android:layout_width="300px"  
        android:layout_height="300px"  
        android:layout_marginLeft="10dp"  
        android:layout_marginTop="10dp"  
        android:src="@color/colorPrimaryDark" />  
  
    <TextView  
        android:id="@+id/description"  
        android:layout_width="250dp"  
        android:layout_height="55dp"  
        android:layout_toRightOf="@id/image"  
        android:layout_marginLeft="15dp"  
        android:layout_marginTop="35dp"  
        android:text="abcd"  
        android:textColor="#000"  
        android:textSize="30sp" />  
  
</RelativeLayout>

Create a Model Class :

public class Data {  
  
    public String name;  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public int getImageId() {  
        return imageId;  
    }  
  
    public void setImageId(int imageId) {  
        this.imageId = imageId;  
    }  
  
    public int imageId;  
  
    Data(String name, int imageId) {  
        this.name = name;  
        this.imageId = imageId;  
    }  
} 

Create RecyclerVIew_Adapter.java

public class RecyclerView_Adapter extends RecyclerView.Adapter<View_Holder> {  
  
    List<Data> list = Collections.emptyList();  
    Context context;  
  
    public RecyclerView_Adapter(List<Data> data, Application application) {  
        this.list = data;  
        this.context = application;  
    }  
  
    @NonNull  
    @Override  
    public View_Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {  
        //Inflate the layout, initialize the View Holder  
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);  
        View_Holder holder = new View_Holder(v);  
        return holder;  
    }  
  
    @Override  
    public void onBindViewHolder(@NonNull View_Holder holder, int position) {  
  
        //Use the provided View Holder on the onCreateViewHolder method to populate the current row on the RecyclerView  
        holder.name.setText(list.get(position).name);  
        holder.imageView.setImageResource(list.get(position).imageId);  
  
    }  
  
    @Override  
    public int getItemCount() {  
        return list.size();  
    }  
} 

  • onCreateViewHolder()- It inflates the row layout and initializes the view holder. It handles findViewById) (methods, find views once, and recycle them so that repetitive calls are avoided.
  • onBindViewHolder()- It uses the onCreateViewHolder() View Holder to fill in the current RecyclerView row with data.
  • getItemCount()- This method returns the collection size which contains the items that we wish to show.
The code file of the ViewHolder Java class is listed below.

import android.view.View;  
import android.widget.ImageView;  
import android.widget.TextView;  
import androidx.recyclerview.widget.RecyclerView;  
  
public class View_Holder extends RecyclerView.ViewHolder {  
  
    TextView name;  
    ImageView imageView;  
  
    View_Holder(View itemView) {  
        super(itemView);  
        name = (TextView) itemView.findViewById(R.id.name);  
        imageView = (ImageView) itemView.findViewById(R.id.image);  
    }  
} 

MainActivity.java class file:

 public class MainActivity extends AppCompatActivity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        List<Data> data = fill_with_data();  
  
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);  
        RecyclerView_Adapter adapter = new RecyclerView_Adapter(data, getApplication());  
        recyclerView.setAdapter(adapter);  
        recyclerView.setLayoutManager(new LinearLayoutManager(this));  
  
    }  
  
    public List<Data> fill_with_data() {  
  
        List<Data> data = new ArrayList<>();  
        data.add(new Data("Android", R.drawable.c));  
        data.add(new Data("Kotlin", R.drawable.cc));  
		data.add(new Data("Kotlin", R.drawable.ccc));  
        return data; 
    }  
} 


September 22, 20203 minutesauthorPankaj Valani