Thursday, 3 May 2018

Simple example of using firestore in Android | Kotlin

Here is the simple example of maintaining database using Firebase instead of SQLite in Kotlin Programming Language.

Step 1.

Login into Firebase Console and create your project.

Step 2.

Navigate into Database and follow the steps given there.

Step 3.

Create your Android project and add the following classpath into root of the project's build.gradle.
classpath 'com.google.gms:google-services:3.1.1'

Step 4.

And then add the following plugin into your module's build.gradle.
apply plugin: 'com.google.gms.google-services'

Step 5.

And then add the following dependency into your module's build.gradle.
implementation 'com.firebaseui:firebase-ui-firestore:3.3.1'
That's all you wanted to access the Firebase's Firestore API in your project.
Here is the methods to create document(Like table in SQLite), Add data to document, edit data from document, delete data from document.

Add data to document using Hashmap.

        //Create employee using hashmap
        val employee = HashMap()
        employee.put("name", "Guna")
        employee.put("phoneNumber", "1144778855")
        employee.put("email", "Guna@gmail.com")

        //Add a new document with a generated ID
        mFirestore.collection("employees")
                 .add(employee)
                 .addOnSuccessListener({ documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.id) })
                 .addOnFailureListener({ e -> Log.w(TAG, "Error adding document", e) })

Add data to document using entity.

        //Create employee using entity
        val employee = Employee("Guna", "1144778855", "Guna@gmail.com")

        //Add a new document with a generated ID
        mFirestore.collection("employees")
                 .add(employee)
                 .addOnSuccessListener({ documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.id) })
                 .addOnFailureListener({ e -> Log.w(TAG, "Error adding document", e) })

Edit data from document using entity.

        //Create employee using entity
        val employee = Employee("Gunaseelan", "1144778866", "Gunaseelan@gmail.com")

        //Edit document with a generated ID
        mFirestore.collection("employees")
                 .document(documentReference.id)//Generated while adding employee
                 .addOnSuccessListener({ documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.id) })
                 .addOnFailureListener({ e -> Log.w(TAG, "Error adding document", e) })

Delete data from document

        //Add a new document with a generated ID
        mFirestore.collection("employees")
                 .document(documentReference.id)//Generated while adding employee
                 .delete()

Here is the video output of this source code


Interesting right?


If you are really interested in this code, then please share this post with your friends, also share your feedback as comment here.


Source code on GitHub


Thank You


Thursday, 19 April 2018

Simple Example of Firebase Authentication in Kotlin

Here is the simple example of Authentication process using Firebase in Kotlin Programming Language.

Step 1.

Login into Firebase Console and create your project.

Step 2.

Navigate into Authentication and enable your preferred login methods.

Step 3.

Create your Android project and add the following classpath into root of the project's build.gradle.
classpath 'com.google.gms:google-services:3.1.1'

Step 4.

And then add the following plugin into your module's build.gradle.
apply plugin: 'com.google.gms.google-services'

Step 5.

And then add the following dependency into your module's build.gradle.
implementation 'com.firebaseui:firebase-ui-auth:3.3.1'
That's you wanted to access the Firebase's Authentication API in your project.
Here is the methods to Sign In, Sign Out and delete the account.

Sign In

private fun signIn() {
    // Choose authentication providers
    val providers = Arrays.asList(AuthUI.IdpConfig.GoogleBuilder().build(),
            AuthUI.IdpConfig.PhoneBuilder().build(),
            AuthUI.IdpConfig.EmailBuilder().build())

    // Create and launch sign-in intent
    startActivityForResult(
            AuthUI.getInstance()
                    .createSignInIntentBuilder()
                    .setAvailableProviders(providers)
                    .build(),
            RC_SIGN_IN);
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == RC_SIGN_IN) {
        val response = IdpResponse.fromResultIntent(data)

        if (resultCode == RESULT_OK) {
            // Successfully signed in
        } else {
            // Sign in failed, check response for error code
        }
    }
}

Sign Out

private fun signOut() {
    AuthUI.getInstance()
                .signOut(this)
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        Toast.makeText(activity, getString(R.string.signed_out), LENGTH_LONG).show()
                    }
                }
}

Delete

private fun delete() {
    AuthUI.getInstance()
                .delete(this)
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        Toast.makeText(activity, getString(R.string.deleted), LENGTH_LONG).show()
                    }
                 }
}

Screenshot





Interesting right?


If you are really interested in this code, then please share this post with your friends, also share your feedback as comment here.



Source code on GitHub


Thank You


Tuesday, 20 March 2018

Simple example of OCRReader in Android.

Hi Friends, Maybe you all heard/used text scanning using camera feature or extracting text from Image. But this sample made it very easy for you. You can made it in very simple line of code.

You can download the source code from OCRSample and import the library as a module into your project.

Example usage : MainActivity.java
public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private final int CAMERA_SCAN_TEXT = 0;
    private final int LOAD_IMAGE_RESULTS = 1;

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.actionCamera:
                //Scan text from camera.
                OCRCapture.Builder(this)
                        .setUseFlash(true)
                        .setAutoFocus(true)
                        .buildWithRequestCode(CAMERA_SCAN_TEXT);
                break;
            case R.id.actionPhoto:
                Intent intentGallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intentGallery, LOAD_IMAGE_RESULTS);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == CAMERA_SCAN_TEXT) {
                if (resultCode == CommonStatusCodes.SUCCESS) {
                    textView.setText(data.getStringExtra(TextBlockObject));
                }
            } else if (requestCode == LOAD_IMAGE_RESULTS) {
                Uri pickedImage = data.getData();
                try {
                    //Extract text from image.
                    String text = OCRCapture.Builder(this).getTextFromUri(pickedImage);
                    //You can also use getTextFromBitmap(Bitmap bitmap) or getTextFromImage(String imagePath) buplic APIs from ibrary. 
                    textView.setText(text);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Here is the video output of this source code


Interesting right?


If you are really interested in this code, then please share this post with your friends, also share your feedback as comment here.


Get it on Google Play

Source code on GitHub


Thank You


Tuesday, 20 February 2018

Simple example of using RadioGroup, RadioButton in Kotlin | Android

Here is the simple example of using RadioGroup, RadioButton in Android Kotlin.

  
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/radioGroup"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.guna.kotlinapplication.BlankFragment">

    <RadioButton
        android:id="@+id/radioMale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/male" />

    <RadioButton
        android:id="@+id/radioFemale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/female" />
</RadioGroup>

OnCheckedChangeListener
  
radioGroup.setOnCheckedChangeListener({ group, checkedId ->
    val radioButton = view.findViewById<RadioButton>(checkedId)
    Toast.makeText(activity, radioButton.text.toString() + " is checked", Toast.LENGTH_LONG).show()
})


Here is the full video tutorial


Interesting right?


If you are really interested in this code, then please share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You


Monday, 19 February 2018

Simple example of using Fragments in Kotlin | Android

Here is the simple example of using Fragments with Activity in Android.

MainActivity.kt
  
class MainActivity : AppCompatActivity(), BlankFragment.OnFragmentInteractionListener {

    override fun onFragmentInteraction(uri: Uri) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction().
                    add(R.id.fragment, BlankFragment.newInstance("Param1", "Param2"), "Second").commit()
        }

        fab.setOnClickListener { view ->
            //Here we will replace the BlanckFragment with SecondFragment.
            supportFragmentManager.beginTransaction().replace(R.id.fragment, SecondFragment(), "Second").commit()
        }
    }
}

activity_main.xml
  
<android.support.design.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="com.guna.kotlinapplication.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.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" />

    </android.support.design.widget.AppBarLayout>

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

    <android.support.design.widget.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" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml
  
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment"
    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:context="com.guna.kotlinapplication.MainActivity"
    tools:showIn="@layout/activity_main"/>

We can add static fragment like this. content_main.xml
  
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment"
    class="com.guna.kotlinapplication.BlankFragment"
    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:context="com.guna.kotlinapplication.MainActivity"
    tools:showIn="@layout/activity_main"/>

BlankFragment.kt
 
/**
 * A simple [Fragment] subclass.
 * Activities that contain this fragment must implement the
 * [BlankFragment.OnFragmentInteractionListener] interface
 * to handle interaction events.
 * Use the [BlankFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class BlankFragment : Fragment() {

    // TODO: Rename and change types of parameters
    private var mParam1: String? = null
    private var mParam2: String? = null

    private var mListener: OnFragmentInteractionListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null) {
            mParam1 = arguments!!.getString(ARG_PARAM1)
            mParam2 = arguments!!.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false)
    }

    // TODO: Rename method, update argument and hook method into UI event
    fun onButtonPressed(uri: Uri) {
        if (mListener != null) {
            mListener!!.onFragmentInteraction(uri)
        }
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        if (context is OnFragmentInteractionListener) {
            mListener = context
        } else {
            throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener")
        }
    }

    override fun onDetach() {
        super.onDetach()
        mListener = null
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *
     *
     * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
     */
    interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        fun onFragmentInteraction(uri: Uri)
    }

    companion object {
        // TODO: Rename parameter arguments, choose names that match
        // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
        private val ARG_PARAM1 = "param1"
        private val ARG_PARAM2 = "param2"

        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment BlankFragment.
         */
        // TODO: Rename and change types and number of parameters
        fun newInstance(param1: String, param2: String): BlankFragment {
            val fragment = BlankFragment()
            val args = Bundle()
            args.putString(ARG_PARAM1, param1)
            args.putString(ARG_PARAM2, param2)
            fragment.arguments = args
            return fragment
        }
    }
}// Required empty public constructor

fragment_blank.xml
  
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context="com.guna.kotlinapplication.BlankFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/hello_blank_fragment"
        android:textColor="#fff" />

</FrameLayout>

SecondFragment.kt
 
/**
 * A simple [Fragment] subclass.
 */
class SecondFragment : Fragment() {


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second, container, false)
    }

}// Required empty public constructor

fragment_second.xml
  
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#567891"
    tools:context="com.guna.kotlinapplication.SecondFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/hello_blank_fragment"
        android:textColor="#fff" />

</FrameLayout>


Here is the full video tutorial


Interesting right?


If you are really interested in this code, then please share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You


Friday, 22 December 2017

Simple example of SeekBarPreference in Android

There is no predefined SeekBarPreference in Android. But we can make our own SeekBarPreference very simply. Here is simple example of making and using SeekBarPreference in Android.

SeekBarPreference.java
  
public class SeekBarPreference extends Preference implements SeekBar.OnSeekBarChangeListener {
    private TextView textValue;

    public SeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public SeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public SeekBarPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SeekBarPreference(Context context) {
        super(context);
    }

    @Override
    protected View onCreateView(ViewGroup parent) {
        super.onCreateView(parent);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.seekbar, parent, false);
        textValue = view.findViewById(R.id.textValue);
        TextView textTitle = view.findViewById(R.id.textTitle);
        textTitle.setText(getTitle());
        SeekBar seekBar = view.findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(this);

        SharedPreferences preferences = getSharedPreferences();
        int value = preferences.getInt(getKey(), 0);
        textValue.setText(String.format(Locale.getDefault(), "%d", value));
        seekBar.setProgress(value);
        return view;
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        textValue.setText(String.format(Locale.getDefault(), "%d", i));
        SharedPreferences.Editor editor = getEditor();
        editor.putInt(getKey(), i);
        editor.apply();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}
seekbar.xml
  
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    android:paddingBottom="5dp"
    android:paddingTop="5dp">

    <TextView
        android:id="@+id/textTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:textColor="#000"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textTitle" />

    <TextView
        android:id="@+id/textValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="10dp"
        android:textColor="#000"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/seekBar" />
</android.support.constraint.ConstraintLayout>

Here is the settings.xml used in SettingsActivityFragment.
  
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <com.guna.testapplication.widgets.SeekBarPreference
        android:defaultValue="50"
        android:key="seekBar"
        android:title="Seek Bar" />
</PreferenceScreen>
SettingsActivity.java
 
public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

}
SettingsActivityFragment.java
 
public class SettingsActivityFragment extends PreferenceFragment {

    public SettingsActivityFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
    }
}

Here is the full video tutorial


Interesting right?


If you are really interested in this code, then please share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You


Wednesday, 20 December 2017

Simple example of Using JobScheduler in Android

JobScheduler is the Android framework API for scheduling tasks or work. It first became available in Android 5.0 (API level 21), and remains under active development. Notably, Android 7.0 (API level 24) added the ability to trigger jobs based on ContentProvider changes.

If your app targets Android 5.0 (API level 21), we recommend that you use the JobScheduler to execute background tasks.

Here is the simple example of Scheduling and Cancelling the scheduled job. MainActivity.java
  
public class MainActivity extends AppCompatActivity {

    int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    public void addJob(View view) {
        count++;
        JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        ComponentName componentName = new ComponentName(this, MyJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(count, componentName);
        builder.setMinimumLatency(15000);//Start after 15 seconds
        PersistableBundle bundle = new PersistableBundle();
        bundle.putString("Title", "Job " + count);
        builder.setExtras(bundle);
        if (scheduler != null) {
            int result = scheduler.schedule(builder.build());
            if (result == JobScheduler.RESULT_SUCCESS) {
                showToast("Job scheduled successfully");
            } else {
                showToast("Job scheduling failed");
            }
        }
    }

    private void showToast(String s) {
        Toast.makeText(this, s, Toast.LENGTH_LONG).show();
    }

    public void allJobs(View view) {
        startActivity(new Intent(this, AllJobsActivity.class));
    }
}


content_main.xml
  
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="@layout/activity_main">

    <Button
        android:id="@+id/buttonAddJob"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="addJob"
        android:text="Add Job"
        app:layout_constraintBottom_toTopOf="@id/buttonShowAllJob"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonShowAllJob"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="allJobs"
        android:text="All Jobs"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/buttonAddJob" />
</android.support.constraint.ConstraintLayout>


MyJobService.java
public class MyJobService extends JobService {
    private static final String TAG = MyJobService.class.getSimpleName();

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        PersistableBundle bundle = jobParameters.getExtras();
        Log.v(TAG, bundle.getString("Title") + " started");
        jobFinished(jobParameters, false);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        Log.v(TAG, "Job completed");
        return true;
    }
}
MyJobService should be registered in manifest as below.
<service
    android:name=".MyJobService"
    android:permission="android.permission.BIND_JOB_SERVICE" />
MyJobService.java
public class AllJobsActivity extends AppCompatActivity {

    private List<JobInfo> pendingJobs = null;
    private JobsAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_jobs);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        RecyclerView recyclerView = findViewById(R.id.myJobList);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        final JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        if (scheduler != null) {
            pendingJobs = scheduler.getAllPendingJobs();
            adapter = new JobsAdapter(pendingJobs);
            recyclerView.setAdapter(adapter);
        }

        ItemTouchHelper.SimpleCallback callback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
                AlertDialog.Builder builder = new AlertDialog.Builder(AllJobsActivity.this);
                builder.setTitle("Cancel Job");
                builder.setMessage("Are you sure to cancel this Job");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        JobInfo info = pendingJobs.get(viewHolder.getAdapterPosition());
                        scheduler.cancel(info.getId());
                        pendingJobs.remove(viewHolder.getAdapterPosition());
                        dialogInterface.dismiss();
                        adapter.notifyDataSetChanged();
                    }
                });
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        adapter.notifyDataSetChanged();
                    }
                });
                builder.create().show();
            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                View view = viewHolder.itemView;
                Paint p = new Paint();
                p.setColor(Color.RED);
                RectF rectF;
                if (dX > 0) {
                    rectF = new RectF(view.getLeft(), view.getTop(), dX, view.getBottom());
                } else {
                    rectF = new RectF(view.getRight() + dX, view.getTop(), view.getRight(), view.getBottom());
                }
                c.drawRect(rectF, p);
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        };
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recyclerView);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

}
JobsAdapter.java
public class JobsAdapter extends RecyclerView.Adapter {
    private List pendingJobs;

    public JobsAdapter(List pendingJobs) {
        this.pendingJobs = pendingJobs;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_list_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.bind(position);
    }

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

    class ViewHolder extends RecyclerView.ViewHolder {
        private TextView textView;

        ViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.text);
        }

        void bind(int position) {
            JobInfo info = pendingJobs.get(position);
            PersistableBundle bundle = info.getExtras();
            textView.setText(bundle.get("Title").toString());
        }
    }
}

Here is the full video tutorial


Interesting right?


If you are really interested in this code, then please share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You