Friday, 4 December 2020

How to share message or URL or app like with all social media in android programmatically

 How to share a message or any web URL or our android app like with all social media as well as mail and SMS in android app programmatically via help of Intent. check below.


 Intent intent = new Intent();

 intent.setAction(Intent.ACTION_SEND);

 intent.setType("text/plain");

 intent.putExtra(Intent.EXTRA_TEXT, "Hello Friends!");

 startActivity(Intent.createChooser(intent, "Share Message"));


Thanks

Monday, 2 March 2020

How to set decimals to only 2 digits in Doubles?

 When you want set double value only two digit after decimal. just follow the below process for android using java or also using kotlin

double time = 200.3456;
DecimalFormat df = new DecimalFormat("#.##");     
time = Double.valueOf(df.format(time));


Thanks

Thursday, 27 February 2020

What is differene between ScrollView and NestedScrollView

ScrollView :

It is a widget of android. Scroll View for use of scrolling screen
when user need scroll screen because of screen content not show
 in single screen that time developer set scroll view.
In scroll view parent view or layout need necessary. But if developer need
set scroll view on more than one recycler view or list view that time not
smoothly scroll.

 NestedScrollView:

It is a widget of android. Nested Scroll View for use of scrolling screen
when user need scroll screen because of screen content not show
 in single screen that time developer set nested scroll view.
In nested scroll view parent view or layout need necessary. But if developer need
set nested scroll view on more than one recycler view or list view that time not
smoothly scroll set enableNested Scroll property of enable nested.

Thanks

Monday, 24 February 2020

How to set Navigation drawable in android or How to set side menu in android

Firstly we learn what is Navigation drawable and why we need Navigation drawable.

Navigation drawable : - Navigation drawable is just a menu side which is just like a menu not web menu. and each menu carry a fragment which is carry a screen according to developer need.

Step 1.==>Create an activity. MainNavigationActivity.java

package com.akhari.myapplication;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.navigation.NavigationView;

import androidx.drawerlayout.widget.DrawerLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.Menu;

public class MainNavigationActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_navigation);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
                R.id.nav_tools, R.id.nav_share, R.id.nav_send)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_navigation, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}


Step 2.==> Create layout XML file. activity_main_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main_navigation"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main_navigation"
        app:menu="@menu/activity_main_navigation_drawer" />

</androidx.drawerlayout.widget.DrawerLayout>

 Step 3.==> Create layout XML file. app_bar_main_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".MainNavigationActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main_navigation" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>



 Step4.==> Create layout XML file. content_main_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>


 Step 5.==> Create Navigation XML file. mobile_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/mobile_navigation"
    app:startDestination="@+id/navigation_home">

    <fragment
        android:id="@+id/nav_home"
        android:name="com.akhari.myapplication.ui.home.HomeFragment"
        android:label="@string/title_home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:id="@+id/nav_gallery"
        android:name="com.akhari.myapplication.ui.dashboard.DashboardFragment"
        android:label="@string/title_dashboard"
        tools:layout="@layout/fragment_dashboard" />

    <fragment
        android:id="@+id/nav_slideshow"
        android:name="com.akhari.myapplication.ui.notifications.NotificationsFragment"
        android:label="@string/title_notifications"
        tools:layout="@layout/fragment_notifications" />

    <fragment
        android:id="@+id/nav_tools"
        android:name="com.akhari.myapplication.ui.notifications.NotificationsFragment"
        android:label="@string/title_notifications"
        tools:layout="@layout/fragment_notifications" />

    <fragment
        android:id="@+id/nav_share"
        android:name="com.akhari.myapplication.ui.notifications.NotificationsFragment"
        android:label="@string/title_notifications"
        tools:layout="@layout/fragment_notifications" />

    <fragment
        android:id="@+id/nav_send"
        android:name="com.akhari.myapplication.ui.notifications.NotificationsFragment"
        android:label="@string/title_notifications"
        tools:layout="@layout/fragment_notifications" />

</navigation>

Step 6.==> Create Layout XML file app_bar_main.xml

Step 7.==> Create Menu XML file activity_main_navigation_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_menu_camera"
            android:title="@string/menu_home" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="@string/menu_gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="@string/menu_slideshow" />
        <item
            android:id="@+id/nav_tools"
            android:icon="@drawable/ic_menu_manage"
            android:title="@string/menu_tools" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="@string/menu_share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_menu_send"
                android:title="@string/menu_send" />
        </menu>
    </item>

</menu>


Step 8.==> Create Fragment java file HomeFragment.java same type all
                   fragment file and used according to user use.


package com.akhari.myapplication.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.akhari.myapplication.R;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        final TextView textView = root.findViewById(R.id.text_home);
        homeViewModel.getText().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
}

Step 9.==> Create layout XML file fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent">

    <TextView
        android:id="@+id/text_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

This is used for user android Home page or Home screen or Dashboard screen
of Application.

Thanks

 

Wednesday, 19 February 2020

Common layout for UI design for android or mainly used layout UI design in android.

What is layout ?

A layout defines the structure for a user interface in your app,
such as in an activity. All elements in the layout are built using
a hierarchy of View and ViewGroup objects. A View usually draws something
the user can see and interact with. Whereas a ViewGroup is an invisible
container that defines the layout structure for View and other
ViewGroup objects, as shown in figure 1.






The View objects are usually called "widgets" and can be one of
many subclasses, such as Button or TextView. The ViewGroup
objects are usually called "layouts"
can be one of many types that provide a different
layout structure, such as LinearLayout or ConstraintLayout .

You can declare a layout in two ways:

    Declare UI elements in XML. Android provides a
straightforward XML vocabulary that corresponds to the
View classes and subclasses, such as those for widgets and layouts.

    You can also use Android Studio's Layout Editor to
build your XML layout using a drag-and-drop interface.
    Instantiate layout elements at runtime. Your app can
create View and ViewGroup objects (and manipulate their
properties) programmatically.

Declaring your UI in XML allows you to separate the
presentation of your app from the code that controls its behavior.
Using XML files also makes it easy to provide different layouts
for different screen sizes and orientations (discussed further
in Supporting Different Screen Sizes).

The Android framework gives you the flexibility to use either
or both of these methods to build your app's UI. For example,
you can declare your app's default layouts in XML, and then
modify the layout at runtime.

1. LinearLayout :

Linear Layout has one goal in life:
lay out children in a single row or column
(depending on if its android:orientation is
horizontal or vertical).

2. RelativeLayout

Relative Layout is not nearly as simple as the
previous two: a look at RelativeLayout.LayoutParams
shows a large number of attributes all focused
around positioning children relative to the edges
or center of RelativeLayout (similar to FrameLayout in fact),
but also relative to one another — say, one child
layout_below another child.

3. FrameLayout

FrameLayout acts quite differently compared
to LinearLayout: here all children are drawn
as a stack — overlapping or not. The only control
on positioning is the layout_gravity attribute —
pushing the child towards a side or
centering it within the FrameLayout.

4. CoordinatorLayout

CoordinatorLayout, part of the Android Design Support
Library, is a subclass of FrameLayout and therefore
inherits its use of layout_gravity to position
children, but also includes the concept of a Behavior.

5. ConstraintLayout

ConstraintLayout is a layout on Android that gives you adaptable
and flexible ways to create views for your apps. ConstraintLayout,
which is now the default layout in Android Studio, gives you many
ways to place objects. You can constrain them to their container,
to each other or to guidelines. This allows you to create large,
complex, dynamic and responsive views in a flat hierarchy.

Mainly used layout in UI design for android application .

Thanks

Tuesday, 18 February 2020

How to set tab at bottom in android or How to set Bottom Navigation View at bottom in android with horizontal without scrolling fragment acording to tab.

Firstly we learn what is Bottom Navigation View and why we need Bottom Navigation View.

Bottom Navigation View : - Bottom Navigation View is just a tab which is just like a button but not exactly button. and each tab carry a fragment which is carry a screen according to developer need.

Step 1.==>Create an activity. BottomTabActivity.java

package com.akhari.myapplication;

import android.os.Bundle;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

public class BottomTabActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottom_tab);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
    }

}

Step 2.==> Create layout XML file. activity_bottom_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3.==> Create Fragments for each tab without scroll or without using view pager.
 HomeFragment.java

package com.akhari.myapplication.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

import com.akhari.myapplication.R;

public class HomeFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
       
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        final TextView textView = root.findViewById(R.id.text_home);
      
        return root;
    }
}

create similar type fragments for each tab.

Step 4.==> Create xml file for UI design of fragment.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent">

    <TextView
        android:id="@+id/text_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


You can follow all above step. and archive your task.
Thanks




Monday, 17 February 2020

How to set tab at top in android or How to set tab Layout at top in android with horizontal scrolling fragment acording to tab.

Firstly we learn what is tab layout and why we need tab layout.

Tab layout : - Tab layout is just a tab which is just like a button but not exactly button. and each tab carry a fragment which is carry a screen according to developer need.

Step 1. ==> Create an activity. TabActivity.java

package com.akhari.myapplication;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import com.akhari.myapplication.ui.main.SectionsPagerAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;

public class TabActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab);
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
        FloatingActionButton fab = findViewById(R.id.fab);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
}

Step 2. ==> Create layout XML file. activity_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".TabActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:minHeight="?actionBarSize"
            android:padding="@dimen/appbar_padding"
            android:text="@string/app_name"
            android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary" />
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Step 3.==> Create view Pager adapter file. SectionsPagerAdapter.java

package com.akhari.myapplication.ui.main;

import android.content.Context;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.akhari.myapplication.R;

/**
 * A [FragmentPagerAdapter] that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2};
    private final Context mContext;

    public SectionsPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mContext.getResources().getString(TAB_TITLES[position]);
    }

    @Override
    public int getCount() {
        // Show tab array length total pages.
        return TAB_TITLES.length;
    }
}

Step 4.==> Create fragment according your need i mean how many fragment you need and you define in adapter class just create it. PlaceholderFragment.java

package com.akhari.myapplication.ui.main;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.akhari.myapplication.R;

/**
 * A placeholder fragment containing a simple view.
 */
public class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    private PageViewModel pageViewModel;

    public static PlaceholderFragment newInstance(int index) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_SECTION_NUMBER, index);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
        int index = 1;
        if (getArguments() != null) {
            index = getArguments().getInt(ARG_SECTION_NUMBER);
        }
        pageViewModel.setIndex(index);
    }

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_tab, container, false);
        final TextView textView = root.findViewById(R.id.section_label);
        pageViewModel.getText().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
}

Step 5.==> Create just layout files for those fragment file which you create. fragment_tab.xml.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.main.PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="@+id/constraintLayout"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintTop_creator="1" />

</androidx.constraintlayout.widget.ConstraintLayout>

These all above step if you follow properly than you can achieve your task successfully.

Thanks.

Friday, 14 February 2020

What is difference between Linear layout and Relative layout in android XML

Both layout are used for UI design for Android Application. both layout are main layout and other widget are child layout or child item like Text View, View, Edit Text and etc. Only main difference listed not all. also listed similarity between both.

1. Linear Layout :
 a). In this layout user can set it's child item in one direction like vertically or horizontally.
 b). In this layout all child show after top or left item.
 c). In this layout user set orientation like vertically or horizontally for his/her
       require manage UI  design.
 d). In this layout set position of layout item set gravity and layout gravity like center,
      start, end ,top and bottom.

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="@dimen/activity_horizontal_margin">
    <Button
        android:id="@+id/button_back"
        android:text="Back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text_title"
        android:text="Title"
        android:layout_width="wrap_content"
        android:textSize="18sp"
        android:layout_margin="10dp"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/button_next"
            android:text="Next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/text_value"
            android:text="Value"
            android:textSize="18sp"
            android:layout_margin="10dp"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

</LinearLayout>

2. Relative Layout :
 a). In this layout user can set it's child item in multiple direction like vertically or horizontally.
      using id of widget set toLeft, toRight, toTop, toBottom.
 b). toLeft is deprecated  and change to toStart, toRight is also deprecated and
      change to toEnd.
 c). In this layout set horizontally or vertically only not like top or start or below or end etc.
      like layout_centerHorizontal is true or false and similar in vertically
      layout_centerVertical is true or false.

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <Button
        android:id="@+id/button_back"
        android:text="Back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text_first_name"
        android:text="First Name"
        android:textSize="18sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button_back" />
    <TextView
        android:id="@+id/text_last_name"
        android:text="JournalDev"
        android:textSize="18sp"
        android:layout_width="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/text_first_name"
        android:layout_below="@id/button_back"/>
</RelativeLayout>

and Similarity between both layout below listed.

1). Both layout have many similarity between both layout.
  a). Width, height and many parameter also compulsory.
  b). Margin for top, bottom, start, and end.
  c).  Padding for top, bottom, start and end.
and also many similarity so I am only list out main point.

Thanks.
 

Thursday, 13 February 2020

What is the difference between ListView and RecyclerView?

1. View Holders

In ListView, defining view holders was a suggested approach for keeping references for views. But it was not a compulsion. Although by not doing so, ListView used show stale data. Another major drawback of not using view holders could lead to a heavy operation of finding views by ids every time. Which resulted in laggy ListViews.

This problem is solved in RecylerView by the use of RecyclerView.ViewHolder class. This is one of the major differences in RecyclerView and ListView. When implementing a RecyclerView this class is used to define a ViewHolder object which is used by the adapter to bind ViewHolder with a position. Another point to be noted here, is that while implementing the adapter for RecyclerView, providing a ViewHolder is compulsory. This makes the implementation a little complex, but solves the issues faced in ListView.
2. Layout Manager

When speaking of ListViews, only one type of ListView is available i.e. the vertical ListView. You cannot implement a ListView with horizontal scroll. I know there are ways to implement a horizontal scroll, but believe me it was not designed to work that way.

But now when we look at Android RecyclerView vs ListView, we have support for horizontal collections as well. In-fact it supports multiple types of lists. To support multiple types of lists it uses RecyclerView.LayoutManager class. This is something new that ListView does not have. RecyclerView supports three types of predefined Layout Managers:

    LinearLayoutManager – This is the most commonly used layout manager in case of RecyclerView. Through this, we can create both horizontal and vertical scroll lists.
    StaggeredGridLayoutManager – Through this layout manager, we can create staggered lists. Just like the Pinterest screen.
    GridLayoutManager– This layout manager can be used to display grids, like any picture gallery.

3. Item Animator

Animations in a list is a whole new dimension, which has endless possibilities. In a ListView, as such there are no special provisions through which one can animate, addition or deletion of items. Instead later on as android evolved ViewPropertyAnimator was suggested by Google’s Chet Haase in this video tutorial for animations in ListView.

On the other hand comparing Android RecyclerView vs ListView, it has RecyclerView.ItemAnimator class for handling animations. Through this class custom animations can be defined for item addition, deletion and move events. Also it provides a DefaultItemAnimator, in case you don’t need any customizations.
4. Adapter

ListView adapters were simple to implement. They had a main method getView where all the magic used to happen. Where the views were bound to a position. Also they used to have an interesting method registerDataSetObserver where one can set an observer right in the adapter. This feature is also present in RecyclerView, but RecyclerView.AdapterDataObserver class is used for it. But the point in favor of ListView is that it supports three default implementations of adapters:

    ArrayAdapter
    CursorAdapter
    SimpleCursorAdapter

Whereas RecyclerView adapter, has all the functionality that ListView adapters had except the built in support for DB cursors and ArrayLists. In RecyclerView.Adapter as of now we have to make a custom implementation to supply data to the adapter. Just like a BaseAdapterdoes for ListViews. Although if you wish to know more about RecyclerView adapter implementation, please refer to Android RecyclerView Example.
5. Item Decoration

To display custom dividers in a ListView, one could have easily added these parameters in the ListView XML:

XHTML

android:divider=”@android:color/transparent”

android:dividerHeight=”5dp”

The interesting part about Android RecyclerView is that, as of now it does not show a divider between items by default. Although the guys at Google must have left this out for customization, intentionally. But this greatly increases the effort for a developer. If you wish to add a divider between items, you may need to do a custom implementation by using RecyclerView.ItemDecoration class.

Or you can apply a hack by using this file from official samples: DividerItemDecoration.java
6. OnItemTouchListener

Listviews used to have a simple implementation for detection of clicks, i.e. by the use of AdapterView.OnItemClickListener interface.

But on the other hand RecyclerView.OnItemTouchListener interface is used to detect touch events in Android RecyclerView. It complicates the implementation a little, but it gives a greater control to the developer for intercepting touch events. The official documentation states, it can be useful for gestural manipulations as it intercepts a touch event before it is delivered to RecyclerView.

How to set Radio Button in recycler view

Simple RecyclerView in Android for show simple listing into Android  App. If you are first time create simple listing screen than this example is best for you & using radio button for select one item from all item from recycler view or list for send one activity to another activity or send data to server.

1. Step => Create simple Activity for example of simple RecyclerView or listing data. Create model class below.

package com.akhari.myapplication;

public class MovieModel {
    private String title, genre, year;
    private Boolean isSelect;
    public MovieModel(String title, String genre, String year,
                Boolean isSelect) {
        this.title = title;
        this.genre = genre;
        this.year = year;
        this.isSelect=isSelect; 
    }
 
    public Boolean getIsSelect() {
        return isSelect;
    }

    public void setIsSelect(Boolean isSelect) {
        this.isSelect= isSelect;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String name) {
        this.title = name;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }
}
 
2. Step==> Create Simple adapter for set adapter of recycler View. 
With arrayList of MovieList Model class
 
 
package com.akhari.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MoviesListAdapter  extends  
RecyclerView.Adapter<MoviesListAdapter.MyViewHolder> {
    private ArrayList<MovieModel> modelArrayList;
    private Context mContext;

    public MoviesListAdapter(ArrayList<MovieModel> modelArrayList, 
Context mContext) {
        this.modelArrayList = modelArrayList;
        this.mContext = mContext;
    }

    @Override     
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_row, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override 
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        MovieModel movie = modelArrayList.get(position);
        holder.title.setText(movie.getTitle());
        holder.genre.setText(movie.getGenre());
        holder.year.setText(movie.getYear());
        holder.checkItem.setChecked(movie.getIsSelect());
 
        holder.radioItem.setOnCheckedChangeListener(new 
     CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton 
        buttonView, boolean isChecked) {
            for(int i=0;i<modelArrayList.size();i++){
                modelArrayList.get(i).setIsSelect(false); 
              movie.setIsSelect(isChecked);
              notifyDataSetChanged(); 
           }
       }); 
 
    }

    @Override    public int getItemCount() {
        return modelArrayList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, year, genre;
        public RadioButton radioItem;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            genre = itemView.findViewById(R.id.genre);
            year = itemView.findViewById(R.id.year);
            checkItem=itemView.findViewById(R.id.check_item);
       }
    }
}
 
 
3. ==> Create Simple XML layout file for recycler view row layout. 
      Name of layout file list_row.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="top"
    android:gravity="top"
    android:padding="25dp"
    android:orientation="horizontal">

    <RadioButton android:id="@+id/radio_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>  
 
<RelativeLayout  
    xmlns:android="http://schemas.android.com/apk/res/android"     
    android:layout_width="match_parent"     
    android:layout_height="wrap_content" 
    android:background="?android:attr/selectableItemBackground" 
    android:clickable="true" 
    android:focusable="true"     
    android:orientation="vertical"     
    android:paddingBottom="@dimen/row_padding_vertical" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/row_padding_vertical">

    <TextView         
       android:id="@+id/title" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_alignParentTop="true" 
       android:textColor="@color/title"         
       android:textSize="16dp" 
       android:textStyle="bold" />

    <TextView 
       android:id="@+id/genre"         
       android:layout_width="match_parent"         
       android:layout_height="wrap_content" 
       android:layout_below="@id/title" />

    <TextView         
       android:id="@+id/year"         
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"         
       android:layout_alignParentRight="true" 
       android:textColor="@color/year" />

</RelativeLayout> 

</LinearLayout>
4. ==> Create MainActivity file for recycler view show Movie list with title,
           subtitle, and year. Using Web API or web services and set data on list
package com.akhari.myapplication;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.akhari.myapplication.AppGlobals;
import com.akhari.myapplication.R;
import com.akhari.myapplication.adapter.NewsListAdapter;
import com.akhari.myapplication.database.DeoliLiveDatabase;
import com.akhari.myapplication.interactor.InteractorImpl;
import com.akhari.myapplication.interactor.ResponsePacket;
import com.akhari.myapplication.interfaces.IntegratorConst;
import com.akhari.myapplication.interfaces.OnResponseListener;
import com.akhari.myapplication.model.NewsInfo;
import com.google.gson.JsonObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ProgressDialog progress;
    private ArrayList<MovieModel> movieList = new ArrayList<>();
    private RecyclerView recyclerView;
    private MoviesListAdapter mMoviesListAdapter;

    @Override
    public View onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progress=new ProgressDialog(getActivity());

        recyclerView = findViewById(R.id.recycler_view);

        mMoviesListAdapter = new MoviesListAdapter(movieList,this);
        RecyclerView.LayoutManager mLayoutManager =

         new LinearLayoutManager(getApplicationContext());

        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mMoviesListAdapter);
        prepareMovieList();
    }

    private void prepareMovieList() {

    if(AppGlobals.getInstance().isOnline(getActivity())) {
            getList(true);
        }
    }

    public void getList(boolean isShowProgress){
        if(isShowProgress){
            progress.setMessage("Loading");
            progress.setProgressStyle(ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
            progress.setIndeterminate(true);
            progress.setCancelable(false);
            progress.show();
        }
        try {
            JsonObject jsonObject = new JsonObject();
            new InteractorImpl(getActivity(), this, IntegratorConst.Code_URL,
        IntegratorConst.Tag_URL)
                    .makeJsonPostRequest(IntegratorConst.Method_URL, jsonObject, false);

        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    @Override
    public void onSuccess(int requestCode, ResponsePacket responsePacket) {
        if(progress!=null && progress.isShowing()){
            progress.dismiss();
        }
        try {
             if(IntegratorConst.Code_DeoliWall==requestCode){
                if(responsePacket.getErrorCode()==0){
                    liveDatabase.deleteDeoliWalls();
                    for(int i=0;i<responsePacket.getValues().
                getMovieModelInfo().size();i++) {
            MovieModel movie = new MovieModel(
                responsePacket.getValues().
                getMovieModelInfo().get(i).getTitle(),
                               responsePacket.getValues().
                getMovieModelInfo().get(i).getDescription(),
               responsePacket.getValues().getMovieModelInfo().get(i).getYear());
                   movieList.add(movie);
                    }
        mMoviesListAdapter.notifyDataSetChanged();
                }
            }
        }catch (NullPointerException nxe){
            nxe.printStackTrace();
        }
    }

    @Override
    public void onError(int requestCode) {
        if(progress!=null && progress.isShowing()){
            progress.dismiss();
        }
        Toast.makeText(getActivity(),"Please check your internet or please try again",
    Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

5.  activity_main  layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="top"
    android:gravity="top"
    android:padding="25dp"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"/>

</LinearLayout>

Thanks

Tuesday, 11 February 2020

How to set check box in recycler view and select or unselect all row or item from recycler view or from list in android

Simple RecyclerView in Android for show simple listing into Android  App. If you are first time create simple listing screen than this example is best for you & using check box for select more than one item or row select from recycler view or list for send one activity to another activity or send data to server. Select all item from one check point.

1. Step => Create simple Activity for example of simple RecyclerView or listing data. Create model class below.

package com.akhari.myapplication;

public class MovieModel {
    private String title, genre, year;
    private Boolean isSelect;
    public MovieModel(String title, String genre, String year,
                Boolean isSelect) {
        this.title = title;
        this.genre = genre;
        this.year = year;
        this.isSelect=isSelect; 
    }
 
    public Boolean getIsSelect() {
        return isSelect;
    }

    public void setIsSelect(Boolean isSelect) {
        this.isSelect= isSelect;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String name) {
        this.title = name;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }
}
 
2. Step==> Create Simple adapter for set adapter of recycler View. 
With arrayList of MovieList Model class
 
 
package com.akhari.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MoviesListAdapter  extends  
RecyclerView.Adapter<MoviesListAdapter.MyViewHolder> {
    private ArrayList<MovieModel> modelArrayList;
    private Context mContext;

    public MoviesListAdapter(ArrayList<MovieModel> modelArrayList, 
Context mContext) {
        this.modelArrayList = modelArrayList;
        this.mContext = mContext;
    }

    @Override     
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_row, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override 
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        MovieModel movie = modelArrayList.get(position);
        holder.title.setText(movie.getTitle());
        holder.genre.setText(movie.getGenre());
        holder.year.setText(movie.getYear());
        holder.checkItem.setChecked(movie.getIsSelect());
 
        holder.checkItem.setOnCheckedChangeListener(new 
                CompoundButton.OnCheckedChangeListener() {
         @Override         public void onCheckedChanged(CompoundButton buttonView, 
               boolean isChecked) {
              movie.setIsSelect(isChecked); 
              notifyDataSetChanged(); 
           }
       }); 
 
    }

    @Override    public int getItemCount() {
        return modelArrayList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, year, genre;
        public CheckBox checkItem;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            genre = itemView.findViewById(R.id.genre);
            year = itemView.findViewById(R.id.year);
            checkItem=itemView.findViewById(R.id.check_item);
       }
    }
}
 
 
3. ==> Create Simple XML layout file for recycler view row layout. 
      Name of layout file list_row.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="top"
    android:gravity="top"
    android:padding="25dp"
    android:orientation="horizontal">

    <CheckBox android:id="@+id/check_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>  
 
<RelativeLayout  
    xmlns:android="http://schemas.android.com/apk/res/android"     
    android:layout_width="match_parent"     
    android:layout_height="wrap_content" 
    android:background="?android:attr/selectableItemBackground" 
    android:clickable="true" 
    android:focusable="true"     
    android:orientation="vertical"     
    android:paddingBottom="@dimen/row_padding_vertical" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/row_padding_vertical">

    <TextView         
       android:id="@+id/title" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_alignParentTop="true" 
       android:textColor="@color/title"         
       android:textSize="16dp" 
       android:textStyle="bold" />

    <TextView 
       android:id="@+id/genre"         
       android:layout_width="match_parent"         
       android:layout_height="wrap_content" 
       android:layout_below="@id/title" />

    <TextView         
       android:id="@+id/year"         
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"         
       android:layout_alignParentRight="true" 
       android:textColor="@color/year" />

</RelativeLayout> 

</LinearLayout>
4. ==> Create MainActivity file for recycler view show Movie list with title,
           subtitle, and year. Using Web API or web services and set data on list
package com.akhari.myapplication;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.akhari.myapplication.AppGlobals;
import com.akhari.myapplication.R;
import com.akhari.myapplication.adapter.NewsListAdapter;
import com.akhari.myapplication.database.DeoliLiveDatabase;
import com.akhari.myapplication.interactor.InteractorImpl;
import com.akhari.myapplication.interactor.ResponsePacket;
import com.akhari.myapplication.interfaces.IntegratorConst;
import com.akhari.myapplication.interfaces.OnResponseListener;
import com.akhari.myapplication.model.NewsInfo;
import com.google.gson.JsonObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ProgressDialog progress;
    private ArrayList<MovieModel> movieList = new ArrayList<>();
    private RecyclerView recyclerView;
    private MoviesListAdapter mMoviesListAdapter;

    @Override
    public View onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progress=new ProgressDialog(getActivity());

        recyclerView = findViewById(R.id.recycler_view);

       CheckBox checkItem=findViewById(R.id.check_item);

    checkItem.setOnCheckedChangeListener(new 
                CompoundButton.OnCheckedChangeListener() {
         @Override         public void onCheckedChanged(CompoundButton buttonView, 
               boolean isChecked) {
              for(int i=0;i<movieList.size();i++){
                 movieList.get(i).setIsSelect(isChecked);
              } 
             mMoviesListAdapter.notifyDataChanged(); 
           }
       }); 


        mMoviesListAdapter = new MoviesListAdapter(movieList,this);
        RecyclerView.LayoutManager mLayoutManager =

         new LinearLayoutManager(getApplicationContext());

        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mMoviesListAdapter);
        prepareMovieList();
    }

    private void prepareMovieList() {

    if(AppGlobals.getInstance().isOnline(getActivity())) {
            getList(true);
        }
    }

    public void getList(boolean isShowProgress){
        if(isShowProgress){
            progress.setMessage("Loading");
            progress.setProgressStyle(ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
            progress.setIndeterminate(true);
            progress.setCancelable(false);
            progress.show();
        }
        try {
            JsonObject jsonObject = new JsonObject();
            new InteractorImpl(getActivity(), this, IntegratorConst.Code_URL,
        IntegratorConst.Tag_URL)
                    .makeJsonPostRequest(IntegratorConst.Method_URL, jsonObject, false);

        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    @Override
    public void onSuccess(int requestCode, ResponsePacket responsePacket) {
        if(progress!=null && progress.isShowing()){
            progress.dismiss();
        }
        try {
             if(IntegratorConst.Code_DeoliWall==requestCode){
                if(responsePacket.getErrorCode()==0){
                    liveDatabase.deleteDeoliWalls();
                    for(int i=0;i<responsePacket.getValues().
                getMovieModelInfo().size();i++) {
            MovieModel movie = new MovieModel(
                responsePacket.getValues().
                getMovieModelInfo().get(i).getTitle(),
                               responsePacket.getValues().
                getMovieModelInfo().get(i).getDescription(),
               responsePacket.getValues().getMovieModelInfo().get(i).getYear());
                   movieList.add(movie);
                    }
        mMoviesListAdapter.notifyDataSetChanged();
                }
            }
        }catch (NullPointerException nxe){
            nxe.printStackTrace();
        }
    }

    @Override
    public void onError(int requestCode) {
        if(progress!=null && progress.isShowing()){
            progress.dismiss();
        }
        Toast.makeText(getActivity(),"Please check your internet or please try again",
    Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

5.  activity_main  layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="top"
    android:gravity="top"
    android:padding="25dp"
    android:orientation="vertical">

    <CheckBox
        android:id="@+id/check_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/select_data"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"/>

</LinearLayout>

Thanks

Monday, 10 February 2020

How to set check box in recycler view.

Simple RecyclerView in Android for show simple listing into Android  App. If you are first time create simple listing screen than this example is best for you & using check box for select more than one item or row select from recycler view or list for send one activity to another activity or send data to server.

1. Step => Create simple Activity for example of simple RecyclerView or listing data. Create model class below.

package com.akhari.myapplication;

public class MovieModel {
    private String title, genre, year;
    private Boolean isSelect;
    public MovieModel(String title, String genre, String year,
                Boolean isSelect) {
        this.title = title;
        this.genre = genre;
        this.year = year;
        this.isSelect=isSelect; 
    }
 
    public Boolean getIsSelect() {
        return isSelect;
    }

    public void setIsSelect(Boolean isSelect) {
        this.isSelect= isSelect;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String name) {
        this.title = name;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }
}
 
2. Step==> Create Simple adapter for set adapter of recycler View. 
With arrayList of MovieList Model class
 
 
package com.akhari.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MoviesListAdapter  extends  
RecyclerView.Adapter<MoviesListAdapter.MyViewHolder> {
    private ArrayList<MovieModel> modelArrayList;
    private Context mContext;

    public MoviesListAdapter(ArrayList<MovieModel> modelArrayList, 
Context mContext) {
        this.modelArrayList = modelArrayList;
        this.mContext = mContext;
    }

    @Override     
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_row, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override 
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        MovieModel movie = modelArrayList.get(position);
        holder.title.setText(movie.getTitle());
        holder.genre.setText(movie.getGenre());
        holder.year.setText(movie.getYear());
        holder.checkItem.setChecked(movie.getIsSelect());
 
        holder.checkItem.setOnCheckedChangeListener(new 
                CompoundButton.OnCheckedChangeListener() {
         @Override         public void onCheckedChanged(CompoundButton buttonView, 
               boolean isChecked) {
              movie.setIsSelect(isChecked); 
              notifyDataSetChanged(); 
           }
       }); 
 
    }

    @Override    public int getItemCount() {
        return modelArrayList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, year, genre;
        public CheckBox checkItem;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            genre = itemView.findViewById(R.id.genre);
            year = itemView.findViewById(R.id.year);
            checkItem=itemView.findViewById(R.id.check_item);
       }
    }
}
 
 
3. ==> Create Simple XML layout file for recycler view row layout. 
      Name of layout file list_row.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="top"
    android:gravity="top"
    android:padding="25dp"
    android:orientation="horizontal">

    <CheckBox android:id="@+id/check_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>  
 
<RelativeLayout  
    xmlns:android="http://schemas.android.com/apk/res/android"     
    android:layout_width="match_parent"     
    android:layout_height="wrap_content" 
    android:background="?android:attr/selectableItemBackground" 
    android:clickable="true" 
    android:focusable="true"     
    android:orientation="vertical"     
    android:paddingBottom="@dimen/row_padding_vertical" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/row_padding_vertical">

    <TextView         
       android:id="@+id/title" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_alignParentTop="true" 
       android:textColor="@color/title"         
       android:textSize="16dp" 
       android:textStyle="bold" />

    <TextView 
       android:id="@+id/genre"         
       android:layout_width="match_parent"         
       android:layout_height="wrap_content" 
       android:layout_below="@id/title" />

    <TextView         
       android:id="@+id/year"         
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"         
       android:layout_alignParentRight="true" 
       android:textColor="@color/year" />

</RelativeLayout> 

</LinearLayout>
4. ==> Create MainActivity file for recycler view show Movie list with title,
           subtitle, and year. Using Web API or web services and set data on list
package com.akhari.myapplication;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.akhari.myapplication.AppGlobals;
import com.akhari.myapplication.R;
import com.akhari.myapplication.adapter.NewsListAdapter;
import com.akhari.myapplication.database.DeoliLiveDatabase;
import com.akhari.myapplication.interactor.InteractorImpl;
import com.akhari.myapplication.interactor.ResponsePacket;
import com.akhari.myapplication.interfaces.IntegratorConst;
import com.akhari.myapplication.interfaces.OnResponseListener;
import com.akhari.myapplication.model.NewsInfo;
import com.google.gson.JsonObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ProgressDialog progress;
    private ArrayList<MovieModel> movieList = new ArrayList<>();
    private RecyclerView recyclerView;
    private MoviesListAdapter mMoviesListAdapter;

    @Override
    public View onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progress=new ProgressDialog(getActivity());

        recyclerView = findViewById(R.id.recycler_view);

        mMoviesListAdapter = new MoviesListAdapter(movieList,this);
        RecyclerView.LayoutManager mLayoutManager =

         new LinearLayoutManager(getApplicationContext());

        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mMoviesListAdapter);
        prepareMovieList();
    }

    private void prepareMovieList() {

    if(AppGlobals.getInstance().isOnline(getActivity())) {
            getList(true);
        }
    }

    public void getList(boolean isShowProgress){
        if(isShowProgress){
            progress.setMessage("Loading");
            progress.setProgressStyle(ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
            progress.setIndeterminate(true);
            progress.setCancelable(false);
            progress.show();
        }
        try {
            JsonObject jsonObject = new JsonObject();
            new InteractorImpl(getActivity(), this, IntegratorConst.Code_URL,
        IntegratorConst.Tag_URL)
                    .makeJsonPostRequest(IntegratorConst.Method_URL, jsonObject, false);

        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    @Override
    public void onSuccess(int requestCode, ResponsePacket responsePacket) {
        if(progress!=null && progress.isShowing()){
            progress.dismiss();
        }
        try {
             if(IntegratorConst.Code_DeoliWall==requestCode){
                if(responsePacket.getErrorCode()==0){
                    liveDatabase.deleteDeoliWalls();
                    for(int i=0;i<responsePacket.getValues().
                getMovieModelInfo().size();i++) {
            MovieModel movie = new MovieModel(
                responsePacket.getValues().
                getMovieModelInfo().get(i).getTitle(),
                               responsePacket.getValues().
                getMovieModelInfo().get(i).getDescription(),
               responsePacket.getValues().getMovieModelInfo().get(i).getYear());
                   movieList.add(movie);
                    }
        mMoviesListAdapter.notifyDataSetChanged();
                }
            }
        }catch (NullPointerException nxe){
            nxe.printStackTrace();
        }
    }

    @Override
    public void onError(int requestCode) {
        if(progress!=null && progress.isShowing()){
            progress.dismiss();
        }
        Toast.makeText(getActivity(),"Please check your internet or please try again",
    Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

Thanks