Thursday 5 January 2017

Twitter Integration In Android


                          

                          


MainActivity

package com.zt.twitterintegration;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
import com.twitter.sdk.android.core.models.User;

import io.fabric.sdk.android.Fabric;

public class MainActivity extends AppCompatActivity {

    private static final String TWITTER_KEY = "r5oW9FVgiXUULcUWMFFDCdCVU";
    private static final String TWITTER_SECRET = "JUAhg9xGxBvjMPINiT8X7kHrkJ01Da2owWq1cHRhsa7Wiiu2rg";
    private TwitterLoginButton twitterLoginButton;
    //
    private TextView tvName, tvEmail;
    private ImageView imgProfilePicture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
        Fabric.with(this, new Twitter(authConfig));
        setContentView(R.layout.activity_main);

        initUI();
    }

    public void initUI() {
        twitterLoginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
        tvName = (TextView) findViewById(R.id.tvName);
        tvEmail = (TextView) findViewById(R.id.tvEmail);
        imgProfilePicture = (ImageView) findViewById(R.id.imgProfilePicture);

        twitterLoginButton.setCallback(new Callback<TwitterSession>() {
            @Override
            public void success(Result<TwitterSession> result) {
                getUserInformation(result);
            }

            @Override
            public void failure(TwitterException exception) {
                Utils.showToast(MainActivity.this, "Login failed.");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        twitterLoginButton.onActivityResult(requestCode, resultCode, data);
    }

    public void getUserInformation(Result<TwitterSession> result) {
        TwitterSession session = result.data;
        Twitter.getApiClient(session).getAccountService()
                .verifyCredentials(true, false, new Callback<User>() {
                    @Override
                    public void failure(TwitterException e) {
                        Utils.showToast(MainActivity.this, "Login failed.");
                    }

                    @Override
                    public void success(Result<User> userResult) {
                        try {
                            User user = userResult.data;
                            String name = user.name;
                            String email = user.email;
                            String followers = String.valueOf(user.followersCount);
                            String strProfilePicture = user.profileImageUrl;
                            Utils.showToast(MainActivity.this, "Login Successfully.");
                            //Name
                            if (name != null) {
                                tvName.setVisibility(View.VISIBLE);
                                tvName.setText("Name : " + name);
                            }
                            //Email
                            if (followers != null) {
                                tvEmail.setVisibility(View.VISIBLE);
                                tvEmail.setText("Followers : " + String.valueOf(followers));
                            }
                            //Profile Picture
                            if (strProfilePicture != null) {
                                imgProfilePicture.setVisibility(View.VISIBLE);
                                Picasso.with(MainActivity.this).load(strProfilePicture).into(imgProfilePicture);
                            }

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

                });

       /* //Get User Email
        TwitterAuthClient authClient = new TwitterAuthClient();
        authClient.requestEmail(session, new Callback<String>() {
            @Override
            public void success(Result<String> result) {
            }

            @Override
            public void failure(TwitterException exception) {
            }
        });*/
    }

}

Utils

package com.zt.twitterintegration;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.Gravity;
import android.widget.Toast;

public class Utils {

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
        return isConnected;
    }

    public static void showToast(Context context, String strMsg) {
        Toast toast = Toast.makeText(context, strMsg, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }
}

activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <com.twitter.sdk.android.core.identity.TwitterLoginButton
        android:id="@+id/twitter_login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp" />


    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/twitter_login_button"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:textColor="@color/colorPrimary"
        android:textSize="20sp"
        android:visibility="gone" />

    <TextView
        android:id="@+id/tvEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tvName"
        android:layout_below="@+id/tvName"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:textColor="@color/colorPrimary"
        android:textSize="20sp"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/imgProfilePicture"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_below="@+id/tvEmail"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:visibility="gone" />

    <Button
        android:id="@+id/btnSignOut"
        android:layout_width="200dp"
        android:layout_height="45dp"
        android:layout_below="@+id/imgProfilePicture"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@color/colorPrimary"
        android:onClick="onClickSignOut"
        android:text="Sign Out"
        android:textAllCaps="false"
        android:textColor="#FFFFFF"
        android:visibility="gone" />
</RelativeLayout>

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zt.twitterintegration">

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

    <application
        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>
        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="b8b6b71c0f6d73b606ea38a444c847acb4176328" />
    </application>

</manifest>

Full Source Code Download Here

Wednesday 4 January 2017

Take Picture From Camera And Gallery In Android


                                


                          


Full Source Code Download Here
MainActivity

package com.takepicturefromcameraandgallery.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.takepicturefromcameraandgallery.R;

public class MainActivity extends AppCompatActivity {

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

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

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


SingleImageActivity

package com.takepicturefromcameraandgallery.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.DexterError;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import com.kbeanie.multipicker.api.CacheLocation;
import com.kbeanie.multipicker.api.CameraImagePicker;
import com.kbeanie.multipicker.api.ImagePicker;
import com.kbeanie.multipicker.api.Picker;
import com.kbeanie.multipicker.api.callbacks.ImagePickerCallback;
import com.kbeanie.multipicker.api.entity.ChosenImage;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.takepicturefromcameraandgallery.R;

import java.io.ByteArrayOutputStream;
import java.util.List;

public class SingleImageActivity extends AppCompatActivity implements ImagePickerCallback {

    private ImageView img_profile;
    private DisplayImageOptions options;
    //Image
    private ImagePicker imagePicker;
    private CameraImagePicker cameraPicker;
    private String picturePath = "", picture_path_base64 = "";

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

        //Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("");
        //
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.default_user)
                .showImageForEmptyUri(R.drawable.default_user)
                .showImageOnFail(R.drawable.default_user)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .build();

        initUI();
    }

    private void initUI() {
        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText(getResources().getString(R.string.single_image));
        img_profile = findViewById(R.id.img_profile);
    }

    //---------------------- Image Dialog ----------------------//
    public void onClickProfilePicture(View view) {
        final CharSequence[] optionsChoose = new
                CharSequence[]{"Take Photo", "Choose from Gallery", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(SingleImageActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(optionsChoose, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (optionsChoose[item].equals("Take Photo")) {
                    if (Build.VERSION.SDK_INT >= 23) {
                        requestStoragePermission(1);
                    } else {
                        takePicture();
                    }
                } else if (optionsChoose[item].equals("Choose from Gallery")) {
                    if (Build.VERSION.SDK_INT >= 23) {
                        requestStoragePermission(2);
                    } else {
                        chooseImage();
                    }
                } else if (optionsChoose[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    private void takePicture() {
        cameraPicker = new CameraImagePicker(this);
        cameraPicker.setDebugglable(true);
        cameraPicker.setCacheLocation(CacheLocation.EXTERNAL_STORAGE_APP_DIR);
        cameraPicker.setImagePickerCallback(this);
        cameraPicker.shouldGenerateMetadata(true);
        cameraPicker.shouldGenerateThumbnails(true);
        picturePath = cameraPicker.pickImage();
    }

    private void chooseImage() {
        imagePicker = new ImagePicker(this);
        imagePicker.setRequestId(1234);
        imagePicker.shouldGenerateMetadata(true);
        imagePicker.shouldGenerateThumbnails(true);
        imagePicker.setImagePickerCallback(this);
        Bundle bundle = new Bundle();
        bundle.putInt("android.intent.extras.CAMERA_FACING", 1);
        imagePicker.pickImage();
    }

    @Override
    public void onImagesChosen(List<ChosenImage> images) {
        picturePath = images.get(0).getThumbnailPath();
        loadPicture();
    }

    @Override
    public void onError(String s) {
    }

    private void loadPicture() {
        ImageLoader.getInstance().displayImage("file://" + picturePath, img_profile, options);
        //File file = new File(picturePath);
        Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
        picture_path_base64 = bitmapToString(bitmap);
    }

    public String bitmapToString(Bitmap bmp) {
        if (bmp == null) {
            return "";
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    /* image selection */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (resultCode == SingleImageActivity.RESULT_OK) {
                if (requestCode == Picker.PICK_IMAGE_DEVICE) {
                    if (imagePicker == null) {
                        imagePicker = new ImagePicker(this);
                        imagePicker.setImagePickerCallback(this);
                    }
                    imagePicker.submit(data);
                } else if (requestCode == Picker.PICK_IMAGE_CAMERA) {
                    if (cameraPicker == null) {
                        cameraPicker = new CameraImagePicker(this);
                        cameraPicker.setImagePickerCallback(this);
                        cameraPicker.reinitialize(picturePath);
                    }
                    cameraPicker.submit(data);
                }
            }
        }
    }

    // request storage permission
    private void requestStoragePermission(final int type) {
        Dexter.withActivity(this)
                .withPermissions(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        if (report.areAllPermissionsGranted()) {
                            if (type == 1) {
                                takePicture();
                            } else {
                                chooseImage();
                            }
                        }
                        if (report.isAnyPermissionPermanentlyDenied()) {
                            showSettingsDialog();
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(
                            List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).
                withErrorListener(new PermissionRequestErrorListener() {
                    @Override
                    public void onError(DexterError error) {
                        Toast.makeText(getApplicationContext(), "Error occurred! ",
                                Toast.LENGTH_SHORT).show();
                    }
                })
                .onSameThread()
                .check();
    }

    private void showSettingsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Need Permissions");
        builder.setMessage("This app needs permission to use this feature." +
                " You can grant them in app settings.");
        builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                openSettings();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();

    }

    // navigating user to app settings
    private void openSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 101);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}


MultipleImageActivity

package com.takepicturefromcameraandgallery.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.DexterError;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import com.nguyenhoanglam.imagepicker.model.Config;
import com.nguyenhoanglam.imagepicker.model.Image;
import com.nguyenhoanglam.imagepicker.ui.imagepicker.ImagePicker;
import com.takepicturefromcameraandgallery.R;
import com.takepicturefromcameraandgallery.adapter.GridViewAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MultipleImageActivity extends AppCompatActivity {

    private GridView grid_view;
    private ArrayList<HashMap<String, String>> imageList = new ArrayList<>();

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

        //Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("");

        initUI();
    }

    private void initUI() {
        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText(getResources().getString(R.string.multiple_image));
        grid_view = findViewById(R.id.grid_view);
    }

    //---------------------- Image Dialog ----------------------//
    public void onClickMultipleImage(View view) {
        if (Build.VERSION.SDK_INT >= 23) {
            requestStoragePermission();
        } else {
            imagePicker();
        }
    }

    private void imagePicker() {
        ImagePicker.with(this)
                .setFolderMode(true)
                .setCameraOnly(false)
                .setFolderTitle("Album")
                .setMultipleMode(true)
                .setMaxSize(9)
                .setKeepScreenOn(true)
                .start();

        /*ImagePicker.with(this)                         //  Initialize ImagePicker with activity or fragment context
           .setToolbarColor("#212121")         //  Toolbar color
           .setStatusBarColor("#000000")       //  StatusBar color (works with SDK >= 21  )
           .setToolbarTextColor("#FFFFFF")     //  Toolbar text color (Title and Done button)
           .setToolbarIconColor("#FFFFFF")     //  Toolbar icon color (Back and Camera button)
           .setProgressBarColor("#4CAF50")     //  ProgressBar color
           .setBackgroundColor("#212121")      //  Background color
           .setCameraOnly(false)               //  Camera mode
           .setMultipleMode(true)              //  Select multiple images or single image
           .setFolderMode(true)                //  Folder mode
           .setShowCamera(true)                //  Show camera button
           .setFolderTitle("Albums")           //  Folder title (works with FolderMode = true)
           .setImageTitle("Galleries")         //  Image title (works with FolderMode = false)
           .setDoneTitle("Done")               //  Done button title
           .setLimitMessage("You have reached selection limit")    // Selection limit message
           .setMaxSize(10)                     //  Max images can be selected
           .setSavePath("ImagePicker")         //  Image capture folder name
           .setSelectedImages(images)          //  Selected images
           .setKeepScreenOn(true)              //  Keep screen on when selecting images
           .start();                           //  Start ImagePicker */
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Config.RC_PICK_IMAGES && resultCode == RESULT_OK && data != null) {
            ArrayList<Image> images = data.getParcelableArrayListExtra(Config.EXTRA_IMAGES);
            if (images != null && images.size() > 0) {
                imageList.clear();
                for (Image image : images) {
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("image_path", image.getPath());
                    imageList.add(hashMap);
                }
                grid_view.setAdapter(new GridViewAdapter(this, imageList));
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    // request storage permission
    private void requestStoragePermission() {
        Dexter.withActivity(this)
                .withPermissions(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        if (report.areAllPermissionsGranted()) {
                            imagePicker();
                        }
                        if (report.isAnyPermissionPermanentlyDenied()) {
                            showSettingsDialog();
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(
                            List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).
                withErrorListener(new PermissionRequestErrorListener() {
                    @Override
                    public void onError(DexterError error) {
                        Toast.makeText(getApplicationContext(), "Error occurred! ",
                                Toast.LENGTH_SHORT).show();
                    }
                })
                .onSameThread()
                .check();
    }

    private void showSettingsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Need Permissions");
        builder.setMessage("This app needs permission to use this feature." +
                " You can grant them in app settings.");
        builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                openSettings();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    }

    // navigating user to app settings
    private void openSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 101);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}


GridViewAdapter

package com.takepicturefromcameraandgallery.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.takepicturefromcameraandgallery.R;

import java.util.ArrayList;
import java.util.HashMap;

public class GridViewAdapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<HashMap<String, String>> imageList;
    private DisplayImageOptions options;

    public GridViewAdapter(Context context, ArrayList<HashMap<String, String>> list) {
        mContext = context;
        imageList = list;
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.default_user)
                .showImageForEmptyUri(R.drawable.default_user)
                .showImageOnFail(R.drawable.default_user)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .build();
    }

    @Override
    public int getCount() {
        return imageList.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            view = new View(mContext);
            view = inflater.inflate(R.layout.row_gridview, null);
            ImageView img_row = view.findViewById(R.id.img_row);
            String picturePath = imageList.get(position).get("image_path");
            ImageLoader.getInstance().displayImage("file://" + picturePath, img_row, options);
        } else {
            view = convertView;
        }
        return view;
    }
}


GlobalApp

package com.takepicturefromcameraandgallery.global;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class GlobalApp extends MultiDexApplication {
    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initImageLoader(this);
    }

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

build.gradle(project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'
        

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://maven.google.com" }
        //Multiple Image
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


build.gradle(module: app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.takepicturefromcameraandgallery"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    //Support Design
    implementation 'com.android.support:design:27+'
    //MultiDex
    implementation 'com.android.support:multidex:1.0.1'
    /* Single image selection library */
    implementation 'com.kbeanie:multipicker:1.1.31@aar'
    /* Multiple image selection library */
    implementation 'com.github.nguyenhoanglam:ImagePicker:1.2.1'
    /* Universal-image-loader */
    implementation files('libs/universal-image-loader-1.9.5.jar')
    /* Circle ImageView */
    implementation 'de.hdodenhof:circleimageview:2.2.0'
    /* Runtime permissions  */
    implementation 'com.karumi:dexter:4.2.0'
}


activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:background="@color/white"
    android:fitsSystemWindows="true">

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

    <ScrollView
        android:id="@+id/scrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <RelativeLayout
            android:id="@+id/rl_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/margin_16">

            <Button
                android:id="@+id/btn_single_image"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="60dp"
                android:background="@color/colorPrimary"
                android:onClick="onClickSingleImage"
                android:padding="15dp"
                android:text="@string/single_image"
                android:textColor="@color/white" />

            <Button
                android:id="@+id/btn_multiple_image"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/btn_single_image"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp"
                android:background="@color/colorPrimary"
                android:onClick="onClickMultipleImage"
                android:padding="15dp"
                android:text="@string/multiple_image"
                android:textColor="@color/white" />

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


single_image.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:background="@color/white"
    android:fitsSystemWindows="true">

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

    <ScrollView
        android:id="@+id/scrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <RelativeLayout
            android:id="@+id/rl_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/margin_16">

            <TextView
                android:id="@+id/tv_tap"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="@dimen/margin_50"
                android:text="@string/tap_profile_picture"
                android:textColor="@color/colorPrimary"
                android:textSize="25sp"
                android:textStyle="bold" />

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/img_profile"
                android:layout_width="150dp"
                android:layout_height="150dp"
                android:layout_below="@+id/tv_tap"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="@dimen/margin_20"
                android:onClick="onClickProfilePicture"
                android:src="@drawable/default_user"
                app:civ_border_color="@color/colorAccent"
                app:civ_border_width="3dp" />
        </RelativeLayout>
    </ScrollView>

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


multiple_image.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:background="@color/white"
    android:fitsSystemWindows="true">

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

    <RelativeLayout
        android:id="@+id/rl_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/margin_16"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <Button
            android:id="@+id/btn_multiple_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn_single_image"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:background="@color/colorPrimary"
            android:onClick="onClickMultipleImage"
            android:padding="15dp"
            android:text="Multiple  Image"
            android:textColor="@color/white" />

        <GridView
            android:id="@+id/grid_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/btn_multiple_image"
            android:layout_marginTop="@dimen/margin_20"
            android:horizontalSpacing="@dimen/margin_20"
            android:numColumns="3"
            android:verticalSpacing="@dimen/margin_20" />
    </RelativeLayout>
</android.support.design.widget.CoordinatorLayout>


row_gridview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/img_row"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:scaleType="centerCrop" />

</RelativeLayout>


toolbar.xml

<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/app_bar_layout"
    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">

        <TextView
            android:id="@+id/tv_title"
            style="@style/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name" />
    </android.support.v7.widget.Toolbar>

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


AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.takepicturefromcameraandgallery">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name=".global.GlobalApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activity.MainActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden|adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.SingleImageActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden|adjustResize" />
        <activity
            android:name=".activity.MultipleImageActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden|adjustResize" />
    </application>
</manifest>

<resources>


styles.xml

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimary</item>
        <item name="colorAccent">@color/colorPrimary</item>
        <item name="windowActionBar">true</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="tv_title">
        <item name="android:layout_gravity">center</item>
        <item name="android:textColor">@color/white</item>
        <item name="android:textSize">20sp</item>
        <item name="android:textAllCaps">false</item>
        <item name="android:textStyle">normal</item>
    </style>

    <style name="tv_adapter">
        <item name="android:singleLine">true</item>
        <item name="android:textAllCaps">false</item>
        <item name="android:textSize">18sp</item>
        <item name="android:textColor">@color/white</item>
    </style>
</resources>

Firebase Authentication And Chat Module In Android

                                   
                          

                          


MainActivity

package com.firebaseintegration.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ProgressBar;

import com.firebaseintegration.R;
import com.firebaseintegration.adapter.FriendsAdapter;
import com.firebaseintegration.controller.ConstantData;
import com.firebaseintegration.controller.RecyclerItemClickListener;
import com.firebaseintegration.controller.Utils;
import com.firebaseintegration.conversation.ConversationActivity;
import com.google.firebase.crash.FirebaseCrash;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private SharedPreferences preferences;
    private RecyclerView recyclerView;
    private CoordinatorLayout coordinatorLayout;
    private DatabaseReference databaseReference;
    private Boolean isBoolean = false;
    private List<HashMap<String, String>> listOfAllFriends = new ArrayList<>();
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setTitle("All Friends");

        preferences = getSharedPreferences(ConstantData.PREFERENCES, MODE_PRIVATE);
        FirebaseCrash.report(new Exception("MainActivity"));
        databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(ConstantData.URL);

        initUI();
        isBoolean = true;
        getAllFriends();
        onLineOffLine(true);

    }

    private void initUI() {
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Intent intent = new Intent(MainActivity.this, ConversationActivity.class);
                        intent.putExtra("map", listOfAllFriends.get(position));
                        startActivity(intent);
                    }
                })
        );
    }

    private void getAllFriends() {
        if (Utils.isNetworkAvailable(this)) {
            progressBar.setVisibility(View.VISIBLE);
            databaseReference.child("user").addValueEventListener(
                    new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            if (isBoolean) {
                                isBoolean = false;
                                if (dataSnapshot.getValue() != null) {
                                    for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
                                        HashMap<String, String> map = new HashMap<>();
                                        map.put("dob", (String) messageSnapshot.child("dob").getValue());
                                        map.put("email", (String) messageSnapshot.child("email").getValue());
                                        map.put("gender", (String) messageSnapshot.child("gender").getValue());
                                        map.put("name", (String) messageSnapshot.child("name").getValue());
                                        map.put("phone", (String) messageSnapshot.child("phone").getValue());
                                        map.put("profile_picture", (String) messageSnapshot.child("profile_picture").getValue());
                                        map.put("status", (String) messageSnapshot.child("status").getValue());
                                        String userEmail = preferences.getString("email", "");
                                        String email = (String) messageSnapshot.child("email").getValue();
                                        if (!userEmail.equals(email)) {
                                            listOfAllFriends.add(map);
                                        }
                                    }
                                    setData();
                                } else {
                                    progressBar.setVisibility(View.GONE);
                                    Utils.showSnackbar(coordinatorLayout, "Friends not found.");
                                }
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            progressBar.setVisibility(View.GONE);
                            Utils.showSnackbar(coordinatorLayout, "" + databaseError);
                        }
                    });
        } else {
            Utils.showSnackbar(coordinatorLayout, getResources().getString(R.string.internet_error));
        }
    }

    public void setData() {
        progressBar.setVisibility(View.GONE);
        if (listOfAllFriends.size() != 0) {
            FriendsAdapter friendsAdapter = new FriendsAdapter(this, listOfAllFriends);
            recyclerView.setAdapter(friendsAdapter);
        } else {
            Utils.showSnackbar(coordinatorLayout, "Friends not found.");
        }
    }

    @Override
    public void onBackPressed() {
        onLineOffLine(false);
        super.onBackPressed();
    }

    public void onLineOffLine(boolean isBoolean) {
        String key = preferences.getString("key", "");
        if (!Utils.isStringNull(key)) {
            if (isBoolean) {
                databaseReference.child("user").child(key).child("status").setValue("1");
            } else {
                databaseReference.child("user").child(key).child("status").setValue("0");
            }
        }
    }
}


activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:fitsSystemWindows="true">

    <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>

    <RelativeLayout
        android:id="@+id/rlMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="1"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:clipToPadding="false"
            android:divider="@null"
            android:dividerHeight="5dp"
            android:overScrollMode="never"
            android:scrollbars="vertical" />

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


AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.firebaseintegration">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.CALL_PHONE" />

    <application
        android:name=".activity.App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">
        <activity
            android:name=".activity.SplashScreen"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="stateHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.LoginActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="stateHidden" />
        <activity
            android:name=".activity.RegisterActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="stateHidden" />
        <activity
            android:name=".activity.ForgotPasswordActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="stateHidden" />
        <activity
            android:name=".activity.MainActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="stateHidden" />
        <activity
            android:name=".conversation.ConversationActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="stateHidden" />
        <activity
            android:name=".conversation.FullScreenImageActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="stateHidden" />

        <!-- Firebase push notification -->
        <service android:name=".pushnotification.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".pushnotification.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
    </application>

</manifest>

Full Source Code Download Here




Marvel Api Integration In Android

                              Full Source Code Download Here: https://github.com/sanjaymangaroliya/MarvelApiIntegration.git MainA...