Saturday 23 June 2018

Android Live Data Tutorial | Live Data | Data Binding | Architecture Components

Hello Friends,
              Today I am going to share me small tutorial of LiveData with Data Binding.

-What is LiveData?
     LiveData is an observable data holder class that can be observed within
     a given lifecycle. It lets the components in your app, usually the UI,
     observe LiveData objects for changes.

-The advantages of using LiveData

  •      Ensures your UI matches your data state
  •      No memory leaks
  •      No crashes due to stopped activities
  •      No more manual lifecycle handling
  •      Always up to date data
  •      Proper configuration changes
  •      Sharing resources
-How to use it in our app

   a. Add below dependency in app/build.gradle

implementation "android.arch.lifecycle:extensions:1.1.1" 


   
   b. UserViewModel.java : Creating a ViewModel class

package com.android.developer.livedatademo.model;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;

/**
 * Created by mukesh on 13/6/18.
 */
public class UserViewModel extends ViewModel {

    // Create a LiveData with a String
    private MutableLiveData mUser;

    public MutableLiveData getUser() {
        if (mUser == null) {
            mUser = new MutableLiveData();
        }
        return mUser;
    }
} 

In Activity class we creates an observer which updates the ui.
final Observer nameObserver = new Observer() {
      @Override
      public void onChanged(@Nullable final User user) {
      // Update the UI, in this case, a TextView.
      binding.tvUserName.setText(user.getName());
    }
};

Next step is observe the livedata, passing in the activity as a LifecycleOwner and the Observer.
userViewModel.getUser().observe(this, nameObserver);
binding.btnClick.setOnClickListener(this); 

The complete code,

package com.android.developer.livedatademo;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.databinding.DataBindingUtil;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.android.developer.livedatademo.databinding.ActivityMainBinding;
import com.android.developer.livedatademo.model.User;
import com.android.developer.livedatademo.model.UserViewModel;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    UserViewModel userViewModel;
    ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        // Get the ViewModel.
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        // Create the observer which updates the UI.
        final Observer nameObserver = new Observer() {
            @Override
            public void onChanged(@Nullable final User user) {
                // Update the UI, in this case, a TextView.
                binding.tvUserName.setText(user.getName());
            }
        };

        // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
        userViewModel.getUser().observe(this, nameObserver);
        binding.btnClick.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        User user = new User();
        user.setName("Mukesh Yadav");
        user.setAge("25");
        userViewModel.getUser().setValue(user);
    }
} 

Download the complete code here

Hope this will helps someone.
Enjoy Coding... :)

Sunday 17 December 2017

Android MVP for Beginners | Android MVP tutorial | Model-View-Presenter: Android | Android Architecture with MVP

Hello Friends,
          Today I am  going to share a very simple example of Android MVP.
In this sample I am using MVP pattern for network call and and user
form(login form) data validation which is mainly used in most of the android
application.

Model View Presenter divides application into three layers i.e: Model, View and Presenter.
  1. Model: This handles the data part of our application
  2. Presenter: It acts as a bridge that connects a Model and a View.
  3. View: This is responsible for laying out views with the relevant data as instructed by the Presenter     

Note: The View never communicates with Model directly

1. LoginActivity.java 
package android.developer.solutions.androidmvp.activity.login.view;

import android.content.Intent;
import android.developer.solutions.androidmvp.R;
import android.developer.solutions.androidmvp.activity.home.view.HomeActivity;
import android.developer.solutions.androidmvp.activity.login.interactor.LoginInteractorImpl;
import android.developer.solutions.androidmvp.activity.login.presenter.ILoginPresenter;
import android.developer.solutions.androidmvp.activity.login.presenter.LoginPresenterImpl;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class LoginActivity extends AppCompatActivity implements ILoginView {
    EditText username;
    EditText password;
    ProgressBar progress;
    Button button;
    private ILoginPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        progress = (ProgressBar) findViewById(R.id.progress);
        button = (Button) findViewById(R.id.btnLogin);
        password = (EditText) findViewById(R.id.password);
        username = (EditText) findViewById(R.id.username);
        presenter = new LoginPresenterImpl(this, new LoginInteractorImpl());
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                presenter.validateCredentials(username.getText().toString(), password.getText().toString());
            }
        });
    }

    @Override
    protected void onDestroy() {
        presenter.onDestroy();
        super.onDestroy();
    }

    @Override
    public void showProgress() {
        progress.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        progress.setVisibility(View.GONE);
    }

    @Override
    public void setUsernameError() {
        username.setError("Invalid user name");
    }

    @Override
    public void setPasswordError() {
        password.setError("Invalid password");
    }

    @Override
    public void navigateToHome() {
        startActivity(new Intent(this, HomeActivity.class));
        finish();
    }
}


2. ILoginView.java

package android.developer.solutions.androidmvp.activity.login.view;

/**
 * Created by Mukesh on 12/16/2017.
 * androiddevelopersolutions.com
 */
public interface ILoginView {
    void showProgress();
    void hideProgress();
    void setUsernameError();
    void setPasswordError();
    void navigateToHome();
}


Download complete code from here

Hope this will helps some one.
Enjoy Coding............ :)

Monday 27 November 2017

Android O: Fonts – Part 1 | Working with custom font Android O | Custom font | Fonts in XML

Hello Friends,
              Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. You can add the font file in the res/font/ folder to bundle fonts as resources. These fonts are compiled in your R file and are automatically available in Android Studio. You can access the font resources with the help of a new resource type, font. For example, to access a font resource, use @font/myfont, or R.font.myfont.

To use the Fonts in XML feature on devices running Android API version 14 and higher, use the Support Library 26. For more information on using the support library, refer to the Using the support library section.

Steps

  • To add fonts as resources, perform the following steps in the Android Studio

    • Right-click the res folder and go to New > Android resource directory       
    • The New Resource Directory window appears.


    • In the Resource type list, select font, and then click OK.






      Note: The name of the resource directory must be font.

  • Using fonts in XML layouts 
    • In the layout XML file, set the font Family attribute to the font file you want to access.






    Download Complete code from here.
    Hope this will help some one.
    Enjoy coding..................  ;)   

 

Copyright @ 2013 Android Developers Blog.