Skip to content

Instantly share code, notes, and snippets.

@SanthoshVijayabaskar
Last active September 13, 2016 05:23
Show Gist options
  • Select an option

  • Save SanthoshVijayabaskar/4fe315ae1b6cdf55e8ca to your computer and use it in GitHub Desktop.

Select an option

Save SanthoshVijayabaskar/4fe315ae1b6cdf55e8ca to your computer and use it in GitHub Desktop.
Getting Started with Android

7 Lifecycle methods of an Activity

  • onCreate
  • onStart
  • onResume
  • onPause
  • onStop
  • onRestart
  • onDestroy

activity_lifecycle

Toast Messages

Toast is a small message displayed on the screen, similar to a tool tip or other similar popup notification. A Toast is displayed on top of the main content of an activity, and only remains visible for a short time period.

Toast.makeText( getApplicationContext(), "Sample Message within Toast", Toast.LENGTH_LONG).show();

Buttons and Event Listener

Creating a Button

```java Button btnToast; ```

Binding the Button with UI View

```java btnToast=(Button)findViewById(R.id.btnToast); ```

Adding Event Listeners to the Button

```java btnToast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(),"Toast Created!!!",Toast.LENGTH_LONG).show();
        }
    });
# Create New Activity

Right Click the Java Package --> New --> Activity --> Empty Activity </br>

The following happens when we try to add a new activity,

* A New <b>XML Layout </b>is created to degin the UI of the Activity <b>(layout folder)</b>
* A New <b>Activity Java File </b>is created to handle the business logic <b>(java folder)</b>
* A New <b>manifest entry</b> is made in AndroidManifest.xml File <b>(manifest folder)</b>

# Intents
An Intent is a messaging object you can use to request an action from another app component. 

<h3> Explicit Intent </h3>
This specify the component to start by name (the fully-qualified class name).

```java
    Intent myIntent = new Intent(SourceActivity.this,DestinationActivity.class);
    startActivity(myIntent);

Passing Data within Explicit Intent

You have to use intentName.putExtras() method to pass data (packaged in Bundle Objects)
   Intent myIntent = new Intent(MainActivity.this,SecondActivity.class);

                Bundle data = new Bundle();
                data.putString("name","Message");
                myIntent.putExtras(data);
                
   startActivity(myIntent);

Retriving data from Explicit Intent

The first step is to receive the Intent using getIntent() and You can extract the data bundle from the Intent using intentName.getExtras(). The below code extracts the data from intent and writes it to TextView (txtWelcome) in the Activity.
   Intent deliveredIntent = getIntent();

        Bundle receivedData = deliveredIntent.getExtras();
        String msg = "Welcome ";
        if(receivedData.containsKey("name")){
            msg = receivedData.getString("name");
        }
        if(msg!=null){
            txtWelcome.setText("Welcome " + msg);
        }

Impilicit Intent

Declare a general action to perform
Tell What action to perform, without worying about who can perform it.

intent-filters 2x

4 Pieces of Implicit Intent

* Action : Defines what you want to do [eg. Place a call]
* Data : Type of Data to work with [eg. URL, Images]
* Extras : Additional Information [eg. Phone No. as key value pair]
* Categories : Grouping Activities of similar Action [eg. LauncherActivity]

Implicit Intent can be used to call Activity, Services or Broadcast Receivers

Intent myImplicitIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.santhoshthepro.in"));
startActivity(myImplicitIntent);

Services

A Service is an application component that can perform long-running operations in the background and does not provide a user interface.

Lifecycle of Services

![service_lifecycle](https://cloud.githubusercontent.com/assets/1716894/11445418/e45b1ea6-9551-11e5-9825-5ffb0b3f4527.png)

Ways of Creating Services

Services can be created using two ways,

  • Extends Service Class (Runs in UI Thread - Resource Intense Service may slow down UI)
  • Extends IntentService Class (Uses a Seperate Work Thread to do the background work - Frees the UI Thread)

Steps to Create Services

  • STEP 1: Create a Class and extends Service / IntentService base Class

  • STEP 2: Implement the Un-implemented methods
    When Using Service Class
    --> onCreate(), onStartCommand(), onDestroy()
    --> We need to Stop the Service using stopSelf() or StopService(intent)

    When Using IntentService Class
    --> onCreate(), onStartCommand(), onIntentHandle(), onDestroy()
    --> We don't want to stop this service as it does by itself

  • STEP 3: Add the Service to the Mainfest File

Overview

There are many third-party libraries for Android but several of them are "must have" libraries that are extremely popular and are often used in almost any Android project. Each has different purposes but all of them make life as a developer much more pleasant. The major libraries are listed below in a few categories.

Standard Pack

This "standard pack" listed below are libraries that are quite popular, widely applicable and should probably be setup within most Android apps:

Name Description
[[Retrofit Consuming-APIs-with-Retrofit]]
[[Glide Displaying-Images-with-the-Glide-Library]]
[[ButterKnife Reducing-View-Boilerplate-with-Butterknife]]
[[Parceler Using-Parceler]]
IcePick Android Instance State made easy
LeakCanary Catch memory leaks in your apps
[[Espresso UI-Testing-with-Espresso]]
[[Robolectric Unit-Testing-with-Robolectric]]

Advanced Pack

The "advanced pack" listed below are additional libraries that are more advanced to use but are popular amongst some of the best Android teams. Note that these libraries may not be suitable for your first app. These advanced libraries include:

Name Description
[[Dagger 2 Dependency-Injection-with-Dagger-2]]
[[RxJava RxJava]]
[[EventBus Communicating-with-an-Event-Bus]]
AndroidAnnotations Powerful annotations to reduce boilerplate code.
[[Retrolambda Lambda Expressions]]

Keep in mind that the combination of these libraries may not always play nicely with each other. The following section highlights some of these issues.

Parceler and IcePick

Note that you cannot use IcePick at the current time to save state of Parceler objects. See this GitHub issue for more context on why they are incompatible. You will need to use explicitly Parcelable objects with IcePick. You may consider replacing Parceler with AutoParcel which works seamlessly with IcePick.

ButterKnife and Parceler

Using the Butterknife library with the Parceler library causes multiple declarations of javax.annotation.processing.Processor. In this case, you have to exclude this conflict in your app/build.gradle file:

   packagingOptions {
        exclude 'META-INF/services/javax.annotation.processing.Processor'  // butterknife
    }

ButterKnife and Custom Views

Often you may find that using ButterKnife or Dagger injections defined in your constructor prevent Android Studio to preview your Custom View layout. You may see an error about needing isEditMode() defined. Essentially this method is used to enable your code to short-circuit before executing a section of code that might be used for run-time but cannot be executed within the preview window.

  public ContentEditorView(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        inflater.inflate(R.layout.view_custom, this, true);

        // short circuit here inside the layout editor
        if(isInEditMode()) {
            return;
        }

        ButterKnife.bind(this);

Convenience

  • Dagger - A fast dependency injector for Android and Java. See this video intro from Square.
  • Spork - Spork is an annotation processing library to speed up development on your projects. It allows you to write less boilerplate code to make your code more readable and maintainable.
  • AutoParcel - Port of Google AutoValue for Android with Parcelable generation goodies.
  • Hugo - Easier logging within your app
  • Logger - Much cleaner and easier logcat trace messages
  • LeakCanary - Easily catch memory leaks as they occur
  • AndroidAnnotations - Framework that speeds up Android development. It takes care of the plumbing, and lets you concentrate on what's really important. By simplifying your code, it facilitates its maintenance
  • Calligraphy - Custom fonts made easy
  • EasyFonts - Easy preloaded custom fonts in your app
  • AndroidViewAnimations - Common property animations made easy
  • AboutLibraries - Automatically generates an About this app section, with a list of used libraries
  • SDK Manager Plugin - Helpful plugin especially for group projects if you're missing an SDK version, haven't downloaded an API version, or your support library is updated.
  • EasyDeviceInfo - Get device information in a super easy way

Extensions

Networking

  • Retrofit - A type-safe REST client for Android and Java which intelligently maps an API into a client interface using annotations.
  • Picasso - A powerful image downloading and caching library for Android.
  • Ion - Powerful asynchronous networking library. Download as a jar here.
  • Android Async HTTP - Asynchronous networking client for loading remote content such as JSON.
  • Volley - Google's HTTP library that makes networking for Android apps easier and most importantly, faster.
  • [[OkHttp|Using OkHttp]] - Square's underlying networking library with support for asynchronous requests.
  • [[Glide|Displaying-Images-with-the-Glide-Library]] - Picasso image loading alternative endorsed by Google
  • Android Universal Image Loader - Popular alternative for image loading that can replace Picasso or Glide.
  • Fresco - An image management library from Facebook.
  • Fast Android Networking -Fast Android Networking is a powerful library for doing any type of networking in Android applications which is made on top of OkHttp Networking Layer.

ListView

RecyclerView

  • UltimateRecyclerView - Augmented RecyclerView with refreshing, loading more, animation and many other features.
  • AdvRecyclerView - Extended RecyclerView with swipe to dismiss, and draggable or expanding items.
  • android-parallax-recyclerview - An adapter which could be used to achieve a parallax effect on RecyclerView.
  • sticky-headers-recyclerview - Sticky Headers decorator for Android's RecyclerView.
  • FastAdapter - Simplify and speed up the process of filling your RecyclerView with data
  • ItemAnimators - RecyclerView animators to animate item add/remove/add/move
  • GreedoLayout - Full aspect ratio grid LayoutManager for Android's RecyclerView
  • RecyclerViewHelper - Provides the most common functions around recycler view like Swipe to dismiss, Drag and Drop, Divider in the ui, events for when item selected and when not selected, on-click listener for items.

Easy Navigation

UI Components

Drawing

  • MPAndroidChart - A powerful Android chart view / graph view library, supporting line- bar- pie- radar- bubble- and candlestick charts as well as scaling, dragging and animations.
  • HoloGraphLibrary - Newer graphing library
  • EazeGraph - Another newer library with potential
  • AndroidCharts - Easy to use charts
  • AndroidGraphView - library to create flexible and nice-looking diagrams.
  • AndroidPlot - plotting library for Android
  • WilliamChart - Flexible charting library with useful motion capabilities.
  • HelloCharts - Charts/graphs library for Android with support for scaling, scrolling and animations.
  • Leonids - Simple and easy particle effects (See Tutorial)
  • Confetti - Newer particle effects library.
  • AChartEngine - This is a charting software library for Android applications

Image Processing

Scanning

Persistence

  • [[ActiveAndroid|ActiveAndroid-Guide]]
  • [[DBFlow|DBFlow Guide]] - A robust, powerful, and very simple ORM android database library with annotation processing.
  • greenDAO
  • SugarORM
  • RxCache - Reactive caching library for Android
  • ORMLite
  • SQLBrite - Lightweight wrapper around SQLiteOpenHelper
  • [[Cupboard|Easier-SQL-with-Cupboard]] - Popular take on SQL wrapper
  • StorIO - Fresh take on a light SQL wrapper
  • Realm
  • NexusData
  • Hawk - Persistent secure key/value store
  • Poetry - Persist JSON directly into SQLite
  • JDXA - The KISS ORM for Android - Simple, Non-intrusive, and Flexible

Compatibility

Scrolling and Parallax

This is a list of popular scrolling and parallax libraries:

Debugging

  • Stetho - A debug bridge for Android applications which could be used for multiple purposes not limited to Network Inspection, Database Inspection and Javascript Console.
  • Bugfender - Cloud storage for your app logs, track user behaviour to find problems in your mobile apps.

Resources

Check out the following resources for finding libraries:

References

##SharedPreference

Writing data to SharedPreference

    SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();

      editor.putString("username",edtUserName.getText().toString());
      editor.putString("password",edtPassword.getText().toString());
      editor.apply();
  Toast.makeText(getApplicationContext(),"Data Saved!", Toast.LENGTH_LONG).show();

Reading data to SharedPreference

    SharedPreferences sharedPref = getSharedPreferences("userInfo",Context.MODE_PRIVATE);

       String name=sharedPref.getString("username","");
       String password=sharedPref.getString("password","");
       
        txtDisplay.setText(name + " " + password);
    Toast.makeText(getApplicationContext(),"Data Retrived..!", Toast.LENGTH_LONG).show();

#SQLite Database

Lightweight Open Source Database built-inside android OS. SQLite is an RDBMS which is used for Store Structured data

#Demo Application

screenshot_20160911-144903

###STEP 1 Create the UI as mentioned above in activity_mail.xml Inflate all the Views in Java (MainActivity.java) and set the corresponding onClick Listeners for the Buttons Create a new Class as mentioned in STEP 2 and declare an Object for the new Class within (MainActivity.java)

DatabaseHelper myDB;

Write the Insert logic within btnSave Button (calling the insertData() method which is defined in STEP 2)

boolean isInserted = myDB.insertData(edtName.getText().toString(),edtRole.getText().toString(),Integer.parseInt(edtRating.getText().toString()));

                if(isInserted == true){
                    Toast.makeText(getApplicationContext(),"Data Inserted!",Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(),"Data not Inserted!",Toast.LENGTH_LONG).show();
                }

###STEP 2 Create a Separate Class "DatabaseHelper" extends SQLiteOpenHelper where the following is performed,

  1. Class Constructor - Creates the Database
  2. onCreate() is called for the first time and it creates the table
  3. onUpgrade() is called when there is a change in database version
  4. CustomMethods() like insertData() - Takes the Input values and Inserts the Value using ContentValues
package sqlitedatabasedemo.santhoshthepro.com.sqlitedatabasedemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by santhosh1 on 9/11/16.
 */
public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "Employee.db";
    public static final String TABLE_NAME = "employee_table";
    public static final String COL_1 ="ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "ROLE";
    public static final String COL_4 = "RATING";

    public DatabaseHelper(Context context){
        super(context,DATABASE_NAME,null,1);

    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE "+ TABLE_NAME + "(ID INTEGER PRIMARY_KEY AUTOINCREMENT, NAME TEXT, ROLE TEXT, RATING INTEGER)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
        onCreate(db);
    }

    public boolean insertData(String name, String role, int rating){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentvalues = new ContentValues();
        contentvalues.put(COL_2,name);
        contentvalues.put(COL_3,role);
        contentvalues.put(COL_4,rating);
        long result = db.insert(TABLE_NAME,null,contentvalues);

        if(result == -1){
            return false;
        }else{
            return true;
        }
    }
}

@SanthoshVijayabaskar

Copy link
Copy Markdown
Author

Please follow the instruction here to solve and understand HAXM Error.
http://stackoverflow.com/questions/26355645/error-in-launching-avd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment