aerizostudios.com.cropshop.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for aerizostudios.com.cropshop.MainActivity.java

Source

package aerizostudios.com.cropshop;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemClickListener;
import com.yalantis.flipviewpager.adapter.BaseFlipAdapter;
import com.yalantis.flipviewpager.utils.FlipSettings;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jp.wasabeef.blurry.Blurry;
import mehdi.sakout.fancybuttons.FancyButton;

public class MainActivity extends AppCompatActivity implements OnMenuItemClickListener {
    private static int REQUEST_PICTURE = 1;
    private SlidingUpPanelLayout mLayout;
    private FragmentManager fragmentManager;
    private DialogFragment mMenuDialogFragment;
    private static int quality = 0;
    FancyButton cropButton, followButton;
    TextView toolbarText;
    Toolbar toolbar;
    RadioButton normal, high;
    AlertDialog AlertD;
    private SharedPreferences prefs;
    private String prefName = "photoquality";

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

        fragmentManager = getSupportFragmentManager();
        initMenuFragment();

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbarText = (TextView) findViewById(R.id.toolbarText);

        //shared pref
        if (isFirstTime()) {
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt("res", 300);
            editor.commit();

        }

        prefs = getSharedPreferences(prefName, MODE_PRIVATE);
        quality = prefs.getInt("res", 300);

        Typeface billabong = Typeface.createFromAsset(getAssets(), "fonts/Billabong.ttf");

        toolbarText.setTypeface(billabong);

        cropButton = (FancyButton) findViewById(R.id.OpenPhotoButton);
        followButton = (FancyButton) findViewById(R.id.FollowButton);

        followButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("http://instagram.com/_u/crop__shop");
                Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);

                likeIng.setPackage("com.instagram.android");

                try {
                    startActivity(likeIng);
                } catch (ActivityNotFoundException e) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://instagram.com/crop__shop")));
                }

            }
        });
        cropButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivityForResult(GetImageFromGallery.getPickImageIntent(MainActivity.this), REQUEST_PICTURE);

            }
        });

        mLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);

        mLayout.setTouchEnabled(true);
        mLayout.setPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
            @Override
            public void onPanelSlide(View panel, float slideOffset) {
                if (mLayout != null) {
                    if (mLayout.getAnchorPoint() == 1.0f) {
                        mLayout.setAnchorPoint(0.7f);
                        mLayout.setPanelState(SlidingUpPanelLayout.PanelState.ANCHORED);
                    } else {
                        mLayout.setAnchorPoint(1.0f);
                        mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
                    }
                }
            }

            @Override
            public void onPanelExpanded(View panel) {
                getSupportActionBar().hide();
            }

            @Override
            public void onPanelCollapsed(View panel) {
                getSupportActionBar().show();
            }

            @Override
            public void onPanelAnchored(View panel) {
                getSupportActionBar().show();
            }

            @Override
            public void onPanelHidden(View panel) {

            }
        });

        final ListView friends = (ListView) findViewById(R.id.flipAbout);

        FlipSettings settings = new FlipSettings.Builder().defaultPage(1).build();
        friends.setAdapter(new FriendsAdapter(this, Utils.friends, settings));

    }

    private void initMenuFragment() {
        MenuParams menuParams = new MenuParams();
        menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.toolbar_size));
        menuParams.setMenuObjects(getMenuObjects());
        menuParams.setClosableOutside(false);
        mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
    }

    private List<MenuObject> getMenuObjects() {

        List<MenuObject> menuObjects = new ArrayList<>();

        MenuObject close = new MenuObject();
        close.setResource(R.mipmap.ic_icn_close);
        close.setBgResource(R.color.dark_grey);

        MenuObject photoQ = new MenuObject("Photo Quality");
        photoQ.setResource(R.mipmap.ic_high_quality);
        photoQ.setBgResource(R.color.dark_grey);

        MenuObject rateUs = new MenuObject("Rate us");
        rateUs.setResource(R.mipmap.ic_rate);
        rateUs.setBgResource(R.color.dark_grey);

        MenuObject shareApp = new MenuObject("Share this App");
        shareApp.setResource(R.mipmap.ic_share_app);
        shareApp.setBgResource(R.color.dark_grey);

        MenuObject feedback = new MenuObject("Feedback");
        feedback.setResource(R.mipmap.ic_feedback);
        feedback.setBgResource(R.color.dark_grey);

        menuObjects.add(close);
        menuObjects.add(photoQ);
        menuObjects.add(rateUs);
        menuObjects.add(shareApp);
        menuObjects.add(feedback);
        return menuObjects;
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_settings:
            if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
                mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
            }
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onMenuItemClick(View clickedView, int position) {

        if (position == 1) {

            AlertDialog.Builder alert = new AlertDialog.Builder(this);

            LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflater.inflate(R.layout.photo_quality, null);
            alert.setView(v);

            alert.setTitle("Select Photo Quality");
            alert.setPositiveButton("OKAY", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    if (normal.isChecked()) {
                        prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putInt("res", 300);
                        editor.commit();

                    } else {
                        prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putInt("res", 400);
                        editor.commit();
                    }

                    prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                    quality = prefs.getInt("res", 0);

                }

            });
            alert.setNegativeButton("CANCEL", null);

            AlertD = alert.create();

            AlertD.show();
            normal = (RadioButton) AlertD.findViewById(R.id.normalQuality);
            high = (RadioButton) AlertD.findViewById(R.id.highQuality);

            Log.d("alert pref", "alert pref" + quality);

            if (quality == 300)
                normal.setChecked(true);
            else
                high.setChecked(true);
        }

        if (position == 2) {
            Uri uri = Uri.parse("market://details?id=" + getPackageName());
            Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);
            try {
                startActivity(myAppLinkToMarket);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, " unable to find market app", Toast.LENGTH_LONG).show();
            }
        }

        if (position == 3) {
            try {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_SUBJECT, "CROP SHOP");
                String sAux = "\nHey friends, Check out this COOL APP - CropShop - No Crop for Whatsapp and"
                        + " Instagram. This app helps you post images on Whatsapp and Instagram without any need "
                        + "of cropping them. It also adds Blur Effect to the Photos like Iphone and also"
                        + " Instagram filters." + "This app allows you to share the photos"
                        + " directly to Instagram,Facebook and Whatsapp from the App.\n"
                        + "Download this app from the play store.\n";
                sAux = sAux + "https://play.google.com/store/apps/details?id=aerizostudios.com.cropshop \n\n";
                i.putExtra(Intent.EXTRA_TEXT, sAux);
                startActivity(Intent.createChooser(i, "choose one"));
            } catch (Exception e) { //e.toString();
            }
        }

        if (position == 4) {
            startActivity(new Intent(this, Feedback.class));
        }
    }

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

        if ((requestCode == REQUEST_PICTURE) && (resultCode == RESULT_OK)) {

            final Uri selectedImageUri = data.getData();
            //Bitmap imgbitmap = (new UserPicture(selectedImageUri, getContentResolver()).getBitmap());
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {

                Blurry.with(MainActivity.this).radius(25).sampling(2)
                        .onto((RelativeLayout) findViewById(R.id.tobe));
            }
            Glide.with(getApplicationContext()).load(selectedImageUri).asBitmap()
                    .into(new SimpleTarget<Bitmap>(quality, quality) {//defines quality 100 low 400 high nearby 1060
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
                            Send(resource);
                        }
                    });//passing intent through bitmap
        }
    }

    public void Send(Bitmap imgbitmap) {
        try {
            //Write file
            String filename = "bitmap.png";
            FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
            imgbitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

            //Cleanup
            stream.close();
            imgbitmap.recycle();
            //Pop intent
            Intent in1 = new Intent(this, CropActivity.class);
            in1.putExtra("image", filename);
            startActivity(in1);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onBackPressed() {
        if (mLayout != null && (mLayout.getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED
                || mLayout.getPanelState() == SlidingUpPanelLayout.PanelState.ANCHORED)) {
            mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
        } else if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
            mMenuDialogFragment.dismiss();
        } else {
            super.onBackPressed();
        }
    }

    class FriendsAdapter extends BaseFlipAdapter<Friend> {

        private final int PAGES = 3;
        private int[] IDS_INTEREST = { R.id.interest_1, R.id.interest_2, R.id.interest_4, R.id.interest_5 };

        public FriendsAdapter(Context context, List<Friend> items, FlipSettings settings) {
            super(context, items, settings);
        }

        @Override
        public View getPage(int position, View convertView, ViewGroup parent, Friend friend1, Friend friend2) {
            final FriendsHolder holder;

            if (convertView == null) {
                holder = new FriendsHolder();
                convertView = getLayoutInflater().inflate(R.layout.about_us_flip, parent, false);
                holder.leftAvatar = (ImageView) convertView.findViewById(R.id.first);
                holder.rightAvatar = (ImageView) convertView.findViewById(R.id.second);
                holder.infoPage = getLayoutInflater().inflate(R.layout.about_us_info, parent, false);
                holder.nickName = (TextView) holder.infoPage.findViewById(R.id.nickname);

                for (int id : IDS_INTEREST)
                    holder.interests.add((TextView) holder.infoPage.findViewById(id));

                convertView.setTag(holder);
            } else {
                holder = (FriendsHolder) convertView.getTag();
            }

            switch (position) {
            // Merged page with 2 friends
            case 1:
                holder.leftAvatar.setImageResource(friend1.getAvatar());
                if (friend2 != null)
                    holder.rightAvatar.setImageResource(friend2.getAvatar());
                break;
            default:
                fillHolder(holder, position == 0 ? friend1 : friend2);
                holder.infoPage.setTag(holder);
                return holder.infoPage;
            }
            return convertView;
        }

        @Override
        public int getPagesCount() {
            return PAGES;
        }

        private void fillHolder(FriendsHolder holder, Friend friend) {
            if (friend == null)
                return;
            Iterator<TextView> iViews = holder.interests.iterator();
            Iterator<String> iInterests = friend.getInterests().iterator();
            while (iViews.hasNext() && iInterests.hasNext())
                iViews.next().setText(iInterests.next());
            holder.infoPage.setBackgroundColor(getResources().getColor(friend.getBackground()));
            holder.nickName.setText(friend.getNickname());
        }

        class FriendsHolder {
            ImageView leftAvatar;
            ImageView rightAvatar;
            View infoPage;

            List<TextView> interests = new ArrayList<>();
            TextView nickName;
        }
    }

    private boolean isFirstTime() {
        boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isfirstrun", true);
        if (isFirstRun) {
            getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isfirstrun", false).commit();
            return true;

        } else {
            return false;
        }
    }

    public void like_facebook(View v) {
        final String urlFb = "fb://page/" + "430860500445507";
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(urlFb));

        // If a Facebook app is installed, use it. Otherwise, launch
        // a browser
        final PackageManager packageManager = getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() == 0) {
            final String urlBrowser = "https://www.facebook.com/" + "cropshopofficial";
            intent.setData(Uri.parse(urlBrowser));
        }

        startActivity(intent);
    }

    public void RateUs(View v) {
        Uri uri = Uri.parse("market://details?id=" + getPackageName());
        Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);
        try {
            startActivity(myAppLinkToMarket);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, " unable to find market app", Toast.LENGTH_LONG).show();
        }
    }

    public void share_whatsapp(View v) {
        try {
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("text/plain");
            i.setPackage("com.whatsapp");
            i.putExtra(Intent.EXTRA_SUBJECT, "CROP SHOP");
            String sAux = "\nHey friends, Check out this COOL APP - CropShop - No Crop for Whatsapp and"
                    + " Instagram. This app helps you post images on Whatsapp and Instagram without any need "
                    + "of cropping them. It also adds Blur Effect to the Photos like Iphone and also"
                    + " Instagram filters." + "This app allows you to share the photos"
                    + " directly to Instagram,Facebook and Whatsapp from the App.\n"
                    + "Download this app from the play store.\n";
            sAux = sAux + "https://play.google.com/store/apps/details?id=aerizostudios.com.cropshop \n\n";
            i.putExtra(Intent.EXTRA_TEXT, sAux);
            startActivity(i);
        } catch (Exception e) {
            Intent check = new Intent(Intent.ACTION_VIEW);
            check.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            check.setData(Uri.parse("market://details?id=" + "com.whatsapp"));
            startActivity(check);
        }
    }

    public void licenses(View v) {
        startActivity(new Intent(MainActivity.this, Licenses.class));
    }
}