Monday 28 August 2017

Top 5 Android Libraries



Top 5 Android libraries every Android developer should know about




In the last year or so, Android development has really come of age. Android Studio with Gradle at its core is a dash of light after Eclipse. Besides that, there are quite a few open source libraries that we use on a daily basis.
Here is a selection of five of our favorite ones and a list of links where you can find others.

Top 5 Android libraries


1. GSON

Gson is a Java library used for serializing and deserializing Java objects from and into JSON. A task you will frequently need to do if you communicate with APIs. We mostly use JSON because it’s lightweight and much simpler than XML.
// Serialize 
String userJSON = new Gson().toJson(user);

// Deserialize
User user = new Gson().fromJson(userJSON, User.class);
It also plays nice with the next library:

2. RETROFIT

From their site: "Retrofit turns your REST API into a Java interface.” It’s an elegant solution for organizing API calls in a project. The request method and relative URL are added with an annotation, which makes code clean and simple.
With annotations, you can easily add a request body, manipulate the URL or headers and add query parameters.
Adding a return type to a method will make it synchronous, while adding a Callback will allow it to finish asynchronously with success or failure.
public interface RetrofitInterface {

    // asynchronously with a callback
    @GET("/api/user")
    User getUser(@Query("user_id") int userId, Callback<User> callback);

    // synchronously
    @POST("/api/user/register")
    User registerUser(@Body User user);
}


// example
RetrofitInterface retrofitInterface = new RestAdapter.Builder()
            .setEndpoint(API.API_URL).build().create(RetrofitInterface.class);

// fetch user with id 2048
retrofitInterface.getUser(2048, new Callback<User>() {
    @Override
    public void success(User user, Response response) {

    }

    @Override
    public void failure(RetrofitError retrofitError) {

    }
});
Retrofit uses Gson by default, so there is no need for custom parsing. Other converters are supported as well.

3. EVENTBUS

EventBus is a library that simplifies communication between different parts of your application. For example, sending something from an Activity to a running Service, or easy interaction between fragments. Here is an example we use if the Internet connection is lost, showing how to notify an activity:
public class NetworkStateReceiver extends BroadcastReceiver {

    // post event if there is no Internet connection
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        if(intent.getExtras()!=null) {
            NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
            if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
                // there is Internet connection
            } else if(intent
                .getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
                // no Internet connection, send network state changed
                EventBus.getDefault().post(new NetworkStateChanged(false));
            }
}

// event
public class NetworkStateChanged {

    private mIsInternetConnected;

    public NetworkStateChanged(boolean isInternetConnected) {
        this.mIsInternetConnected = isInternetConnected;
    }

    public boolean isInternetConnected() {
        return this.mIsInternetConnected;
    }
}

public class HomeActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EventBus.getDefault().register(this); // register EventBus
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this); // unregister EventBus
    }

    // method that will be called when someone posts an event NetworkStateChanged
    public void onEventMainThread(NetworkStateChanged event) {
        if (!event.isInternetConnected()) {
            Toast.makeText(this, "No Internet connection!", Toast.LENGTH_SHORT).show();
        }
    }

}
4. ACTIVEANDROID
ActiveAndroid is an ORM for Android. It’s an abstraction over SQLite which allows you to communicate with a database on a device without writing SQL statements. An Object that extends ActiveAndroid Model can be saved to the database like this:
user.save();
which can easily replace a big SQL statement like this:
INSERT INTO Users (Nickname, Name, Address, City, PostalCode, Country) VALUES ('Batman','Bruce W','Palisades 21','Gotham','40000','USA');
An example of retrieving all users:
List<User> users = new Select().from(User.class).execute();
of which SQL counterpart would look like this:
SELECT Nickname, Name, Address, City, PostalCode, Country FROM Users;
ActiveAndroid is a nice way to remove a lot of boilerplate code used for working with databases. There are other open source solutions like GreenDAO and ORMLite

5. UNIVERSAL IMAGE LOADER

UIL is a library which provides asynchronous, out of the box loading and caching of images. It’s pretty straightforward to use:
imageLoader.displayImage(imageUri, imageView);
Although Picasso has a nicer API, it lacks in customization. With the UIL configuration builder almost everything can be configured (important for fetching and caching of really large images, which Picasso fails to do).
Good open source libraries will make your development a hell of a lot easier and faster. Popular libraries are often well tested and simple to use. In most cases you can easily import them into your Android Studio project from Maven. Add them into dependencies in your build.gradle file like this:
dependencies {
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.squareup.okhttp:okhttp:1.3.0'
    compile 'com.squareup.retrofit:retrofit:1.3.0'
    compile 'de.greenrobot:eventbus:2.2.+'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.1'
}
and after syncing you will be good to go to implement them into your app.

Tuesday 30 May 2017

Draw Android Map Poly Line

Manifest:

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

<activity
    android:name=".activity.MapsActivity"
    android:label="@string/title_activity_maps" />

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="@string/google_maps_key" />

Java:


public class MapsActivity extends BaseActivity {

    private GoogleMap googleMap;

    private double fromLatitude = 1.306444;
    private double fromLongitude = 103.851109;

    private double toLatitude = 1.329356;
    private double toLongitude = 103.877889;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        googleMap.getUiSettings().setMapToolbarEnabled(false);

        List<LatLng> points = Arrays.asList(new LatLng(fromLatitude, fromLongitude),
                new LatLng(toLatitude, toLongitude));

        PolygonOptions options = new PolygonOptions();
        options.addAll(points);
        options.fillColor(getResources().getColor(R.color.app_theme_color));
        options.strokeColor(getResources().getColor(R.color.app_theme_color));
        googleMap.addPolygon(options);

        googleMap.addMarker(new MarkerOptions()
                .position(new LatLng(fromLatitude, fromLongitude))
                .title("You Are here")
                .snippet("Order placed"));
        googleMap.addMarker(new MarkerOptions()
                .position(new LatLng(toLatitude, toLongitude))
                .title("Destination Position")
                .snippet("Order placed"));

        midPoint(fromLatitude, fromLongitude, toLatitude, toLongitude);
    }

    public void midPoint(double lat1, double lon1, double lat2, double lon2) {

        double dLon = Math.toRadians(lon2 - lon1);

        //convert to radians
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
        lon1 = Math.toRadians(lon1);

        double Bx = Math.cos(lat2) * Math.cos(dLon);
        double By = Math.cos(lat2) * Math.sin(dLon);
        double lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt((Math.cos(lat1) + Bx) * (Math.cos(lat1) + Bx) + By * By));
        double lon3 = lon1 + Math.atan2(By, Math.cos(lat1) + Bx);

        //print out in degrees
        System.out.println(Math.toDegrees(lat3) + " " + Math.toDegrees(lon3));

        CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(Math.toDegrees(lat3), Math.toDegrees(lon3)));
        CameraUpdate zoom = CameraUpdateFactory.zoomTo(14);
        googleMap.moveCamera(center);
        googleMap.animateCamera(zoom);
    }

}



Xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:elevation="7dp"
    android:fitsSystemWindows="false"
    tools:context=".activity.MapsActivity">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">/>

        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="@drawable/editext_border_login"
            android:layout_margin="@dimen/margin10">

            <Button
                android:id="@+id/email_sign_in_button"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin20"
                android:background="@drawable/login_btn_selector"
                android:text="@string/action_view_direction"
                android:textAllCaps="false"
                android:textColor="@color/white"
                android:textStyle="bold" />
        </RelativeLayout>
  </RelativeLayout>
</RelativeLayout>


Images:

Screen Shot:

Android Components


Button:
java:
Button button = (Button ) findViewById(R.id.button );

button.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View view) {
        ///perform your code inside
    }
});
Xml:
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
Textview:
java:
TextView textview = (TextView ) findViewById(R.id.textview );
textview.setText("your label text");
Xml:
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />

EditText:
java:
EditText edittext= (EditText ) findViewById(R.id.edittext);
edittext.setText("your label text");
String getText=edittext.getText().toString();

Xml:
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="EditText" />


more matirial UI components:





Saturday 1 April 2017

Dyanamic ImageLoading in Android RecyclerView

Step 1:
gradle
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:design:25.0.1'
compile 'com.android.support:support-v4:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'




Step 2:

Manifests


<!-- if you want to load images from the internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- if you want to load images from a file OR from the internet -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


<application    android:name=".ApplicationName"
    android:allowBackup="true"    
android:icon="@mipmap/ic_launcher"  
  android:label="@string/app_name"
    android:supportsRtl="true"    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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




Step3:
Java File:
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.Log;

import com.fastxpo.android.fnbdelivery.utils.Utils;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;



/** * Created by karthic on 18-12-2015. */public class ApplicationName extends Application {
    public static String deviceId;

    @Override    public void onCreate() {
        super.onCreate();
        initImageLoader(getApplicationContext());
        LoadDeviceId();

        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.gurubhai.fast",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:",md+ Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
    }


    public static void initImageLoader(Context context) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new SHA256FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .build();
        ImageLoader.getInstance().init(config);
    }

}




ImageDownloaderListener.java:


import android.graphics.Bitmap;

public interface ImageDownloaderListener {
    public void imageDownloadComplete(Bitmap bitmap);

    public void imageDownloadFailed();
}




ImageLoader.java:
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import com.fastxpo.android.fnbdelivery.common.ApiConstants;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

public class ImageLoader {
    private com.nostra13.universalimageloader.core.ImageLoader imageLoader;
    private DisplayImageOptions options;
    private ImageDownloaderListener imageDownloaderListener;

    public ImageLoader(int onLoading, int onFailed) {
        try {
            imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
            options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(onLoading)
                    .showImageForEmptyUri(onFailed)
                    .showImageOnFail(onFailed)
                    .cacheInMemory(true)
                    .cacheOnDisc(true)
                    .considerExifParams(true)
                    .bitmapConfig(Bitmap.Config.ARGB_8888)
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void displayImage(String url, ImageView imageView) {
        imageLoader.displayImage(ApiConstants.SERVER_URL + ApiConstants.IMAGEPATH + url, imageView, options);
    }

    public Bitmap getBitmap(String imageUrl) {
        final Bitmap[] bitmap = {null};
        imageLoader.loadImage(imageUrl, new ImageLoadingListener() {

            @Override            public void onLoadingStarted(String imageUri, View view) {
            }

            @Override            public void onLoadingFailed(String imageUri, View view,
                                        FailReason failReason) {
                if (imageDownloaderListener != null) {
                    imageDownloaderListener.imageDownloadFailed();
                }
            }

            @Override            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                if (imageDownloaderListener != null) {
                    imageDownloaderListener.imageDownloadComplete(loadedImage);
                    bitmap[0] = loadedImage;
                }
            }

            @Override            public void onLoadingCancelled(String imageUri, View view) {
                if (imageDownloaderListener != null) {
                    imageDownloaderListener.imageDownloadFailed();
                }
            }
        });
        return bitmap[0];
    }

    public void pause() {
        imageLoader.pause();
    }

    public void resume() {
        imageLoader.resume();
    }

    public void clearCache() {
        imageLoader.clearDiscCache();
        imageLoader.clearMemoryCache();
    }

    public void stop() {
        imageLoader.stop();
    }


}


SHA256FileNameGenerator.java
import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.utils.L;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256FileNameGenerator implements FileNameGenerator {

   private static final String HASH_ALGORITHM = "SHA256";
   private static final int RADIX = 10 + 26; // 10 digits + 26 letters
   @Override   public String generate(String imageUri) {
      byte[] sha256 = getSHA256(imageUri.getBytes());
      BigInteger bi = new BigInteger(sha256).abs();
      return bi.toString(RADIX);
   }

   private byte[] getSHA256(byte[] data) {
      byte[] hash = null;
      try {
         MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
         digest.update(data);
         hash = digest.digest();
      } catch (NoSuchAlgorithmException e) {
         L.e(e);
      }
      return hash;
   }

}




MainActivity.java
package com.fastxpo.android.fnbdelivery.activity;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.fastxpo.android.fnbdelivery.R;
import com.fastxpo.android.fnbdelivery.adapter.CartAdapter;
import com.fastxpo.android.fnbdelivery.bean.orders.LineItem;
import com.fastxpo.android.fnbdelivery.sqlite.SqliteDBHandler;
import java.util.List;
public class MainActivityextends AppCompatActivity {

    RecyclerView cartRecyclerView;
    Activity activity;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;
        mainRecyclerView = (RecyclerView) findViewById(R.id.mainRecyclerView);
       
        List<LineItem> allLineItems = getAllList();
        if (allLineItems.size() > 0) {
            mainRecyclerView.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
            MainAdapter mainAdapter = new MainAdapter(activity, allLineItems);
            mainRecyclerView.setAdapter(mainAdapter );
        } else {
            Toast.makeText(activity, "main List Empty", Toast.LENGTH_SHORT).show();
        }
    }
}
MainAdapter.java
package com.fastxpo.android.fnbdelivery.adapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.fastxpo.android.fnbdelivery.R;
import com.fastxpo.android.fnbdelivery.api.manager.ImageLoader;
import com.fastxpo.android.fnbdelivery.bean.orders.LineItem;
import java.util.List;

/** * Created by karthic on 1/4/2017. */
public class MainAdapterextends RecyclerView.Adapter<MainAdapter.MyViewHolder> {

    private Context context;
    private List<LineItem> lineItemList = null;
    private ImageLoader imageLoader;

    public MainAdapter(Context context, List<LineItem> mainDataList) {

        this.context = context;
        this.lineItemList = mainDataList;
        imageLoader = new ImageLoader(R.drawable.loading, R.drawable.loading);
    }


    public static class MyViewHolder extends RecyclerView.ViewHolder {

        protected TextView name;
        protected TextView number;
        protected ImageView image;
        protected LinearLayout relativeLayout;

        public MyViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.productnameTable);
            number = (TextView) itemView.findViewById(R.id.priceTv);
            image = (ImageView) itemView.findViewById(R.id.contactimage);
            relativeLayout = (LinearLayout) itemView.findViewById(R.id.llRelativeLayout);
        }
    }

    @Override    public MainAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_row, parent, false);
        MainAdapter.MyViewHolder myViewHolder = new MainAdapter.MyViewHolder(view);

        return myViewHolder;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override    public void onBindViewHolder(final MainAdapter.MyViewHolder holder, final int position) {

   
        holder.name.setText(lineItemList.get(position).getItemname());
        holder.number.setText("S$" + lineItemList.get(position).getSellprice());

        if (!TextUtils.isEmpty(lineItemList.get(position).getImagename())) {
            String imgURL = lineItemList.get(position).getImagename();
            imageLoader.displayImage(imgURL, holder.image);
        } else {
            holder.image.setImageDrawable(context.getResources().getDrawable(R.drawable.loading));
        }

    }

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

}


product_row.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llRelativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp"
android:background="@color/white"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="80dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:id="@+id/imagell"
android:layout_alignParentLeft="true"
android:layout_height="80dp">
<ImageView
android:id="@+id/contactimage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="@dimen/margin5dp"
android:contentDescription="@string/app_name" />
<TextView
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:background="@drawable/circle"
android:textColor="@color/white"
android:gravity="center"
android:textStyle="bold"
android:text="New"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_toLeftOf="@+id/checkedimageLL"
android:layout_toRightOf="@+id/imagell">
<TextView
android:id="@+id/productnameTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textIsSelectable="false"
android:textSize="15dp"
android:textStyle="bold" />
<TextView
android:id="@+id/priceTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/productnameTable"
android:singleLine="true"
android:textColor="@color/blactransparent"
android:textIsSelectable="false"
android:textSize="12dp" />
</RelativeLayout>
</RelativeLayout>
</LinearLayout>






Send Whatsapp Message via PHP Code

  How to Send and Receive Messages in WhatsApp using PHP In this tutorial you will see How to Send and Receive Messages in WhatsApp using PH...