Sign Up

What is the capital of Egypt? ( Cairo )

Have an account? Sign In Now

Sign In

What is the capital of Egypt? ( Cairo )

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to share a Concept.

What is the capital of Egypt? ( Cairo )

Forgot Password?

Need An Account, Sign Up Here

You must login to share a Concept.

What is the capital of Egypt? ( Cairo )

Forgot Password?

Need An Account, Sign Up Here
Sign InSign Up

Camposha Android

Camposha Android Logo Camposha Android Logo

Camposha Android Navigation

  • Home
  • About Us
  • Blog
  • Contact Us
  • Buy Projects
Search
Share A Concept

Mobile menu

Close
Ask a Concept
  • Home
  • Buy Projects
  • Categories
  • Concepts
    • Newest Concepts
    • Trending
    • Most Popular
    • Hottest
  • Home
  • About Us
  • Blog
  • Contact Us
  • Buy Projects

Oclemy

Share Oclemy
0Followers
291Concepts
Home/ Oclemy/Answers
Adv
  • About
  • Questions
  • Polls
  • Answers
  • Best Answers
  • Groups
  1. Shared a concept on: September 17, 2020In: General

    Android URL Preview

    Oclemy

    Oclemy

    • Nairobi, Kenya
    • 291 Concepts
    • 108 Examples
    • 0 Best Examples
    • 0 Points
    View Profile
    Oclemy
    Added an example on September 30, 2020 at 8:56 am

    RxUnfurl RxUnfurl is a reactive extension to generate URL previews. This library parses available open graph data from the provided url and returns them as a simple model class. Otherwise, the library searches for other fallbacks and returns them instead. Image dimensions are read from its uri by feRead more

    RxUnfurl

    RxUnfurl is a reactive extension to generate URL previews.

    This library parses available open graph data from the provided url and returns them as a simple model class. Otherwise, the library searches for other fallbacks and returns them instead.

    Image dimensions are read from its uri by fetching the required bytes and then sorted according to their resolution. The library uses RxJava2 as of the time of pulishing this.

     

    Step 1 – Install

    To install the library add the following implementation statement in your module-level build.gradle:

    dependencies {
        implementation 'com.schinizer:rxunfurl:0.3.0'
    }

    Usage

    To generate previews, simply subscribe to RxUnfurl.generatePreview(yourURL)

    Here is an example:

     

    OkHttpClient okhttpClient = new OkHttpClient();
    
    RxUnfurl inst = new RxUnfurl.Builder()
            .client(okhttpClient) // You can supply your okhttp client here
            .scheduler(Schedulers.io())
            .build();
            
    inst.generatePreview("http://9gag.com")
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeWith(new DisposableSingleObserver<PreviewData>() {
            @Override
            public void onSuccess(PreviewData previewData) { // Observable has been changed to Single
    
            }
    
            @Override
            public void onError(Throwable e) {
    
            }
        });

     

    Find more here.

    See less
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  2. Adv
  3. Shared a concept on: March 28, 2019

    Android Firebase RecyclerView MasterDetail CRUD Images Text – Upload, READ, DELETE

    Oclemy

    Oclemy

    • Nairobi, Kenya
    • 291 Concepts
    • 108 Examples
    • 0 Best Examples
    • 0 Points
    View Profile
    Oclemy
    Replied to example on September 17, 2020 at 1:59 am

    Can you cnofirm that it is being uploaded?

    Can you cnofirm that it is being uploaded?

    See less
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  4. Adv
  5. Shared a concept on: September 8, 2020In: UI

    Android RatingBar

    Oclemy

    Oclemy

    • Nairobi, Kenya
    • 291 Concepts
    • 108 Examples
    • 0 Best Examples
    • 0 Points
    View Profile
    Oclemy
    Added an example on September 14, 2020 at 4:32 pm
    This example was edited.

    Android MaterialRatingBar Another way for you to use a rating bar is the usage of a third party library. Through this you get a more beautiful and customizable library than the standard ratingbar. One of those libraries is material rating bar. It's basically a material Design `RatingBar` with betterRead more

    Android MaterialRatingBar

    Another way for you to use a rating bar is the usage of a third party library. Through this you get a more beautiful and customizable library than the standard ratingbar.

    One of those libraries is material rating bar. It’s basically a material Design RatingBar with better appearance, compatible with Android 3.0+.

    Here are its features:

    1. Consistent appearance on Android 3.0+.
    2. Extends framework RatingBar.
    3. Get the 2dp star border background as in Material Icons and Google apps.
    4. Correct custom tinting across platforms.
    5. Able to render correctly when layout_width is set to match_parent, as in Google Play Store.
    6. Able to scale correctly when layout_height is set to values other than 16dp, 36dp and 48dp.
    7. Able to display ratings such as 4.3 correctly, which will be filled to 4.5 by framework’s incorrect implementation.
    8. Avoid framework’s sunken half star visual glitch.
    9. Used as a drop-in replacement for framework RatingBar.

    Here are the steps to use it:

    Step 1- Installation

    Install it from jcenter using the following statement:

    implementation 'me.zhanghai.android.materialratingbar:library:1.4.0'

    Step 2 – Layout

    Simply replace your RatingBar with MaterialRatingBar, and remember to apply a corresponding style for correct behavior.

    For example, to create a normal MaterialRatingBar:

    <me.zhanghai.android.materialratingbar.MaterialRatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Widget.MaterialRatingBar.RatingBar" />

    Demos

    Here is the demo:

    MaterialRatingBar

    Links

    1. Read more or find code here.
    2. Follow author here.
    See less
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  6. Adv
  7. Shared a concept on: September 13, 2020In: UI

    Best Android Swipe Cards Libraries and Examples

    Oclemy

    Oclemy

    • Nairobi, Kenya
    • 291 Concepts
    • 108 Examples
    • 0 Best Examples
    • 0 Points
    View Profile
    Oclemy
    Added an example on September 14, 2020 at 4:12 pm

    Swipe Cards with SwipeView SwipeView is a a Tinder style StackSwipeview gesture library. It supports android API 15 and above. Here is how to use it. Step 1 - Installation To Install the library first add jitpack in your project level's build.gradle: maven { url 'https://jitpack.io' } Then the depenRead more

    Swipe Cards with SwipeView

    SwipeView is a a Tinder style StackSwipeview gesture library. It supports android API 15 and above.

    Here is how to use it.

    Step 1 – Installation

    To Install the library first add jitpack in your project level’s build.gradle:

    maven { url 'https://jitpack.io' }

    Then the dependency statement in your app level’s build.gradle:

    dependencies {
      implementation 'com.github.umutsoysl:SwipeView:1.0'
    }

     

    Step 2 – Layout

    Add the SwipeView in your layout:

    <com.umut.soysal.swipelayoutview.ui.StackImageView
                   android:id="@+id/iv_avatar"
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:scaleType="centerCrop"
                   app:radius="10dp"
                   android:src="@drawable/img_avatar_01" />

    Step 3 – Code

    In your activity or fragment start by initializing your recyclerview as usual:

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setAdapter(...);

    then set CardLayoutManager for RecyclerView and CardItemTouchHelperCallback for ItemTouchHelper . In addition , don’t forget set OnSwipeListener for CardItemTouchHelperCallback :

    // dataList means dataSource for adapter
    CardItemTouchHelperCallback cardCallback = new CardItemTouchHelperCallback(recyclerView.getAdapter(), dataList);
    ItemTouchHelper touchHelper = new ItemTouchHelper(cardCallback); CardLayoutManager cardLayoutManager = new CardLayoutManager(recyclerView, touchHelper);
    recyclerView.setLayoutManager(cardLayoutManager);
    touchHelper.attachToRecyclerView(recyclerView);
    cardCallback.setOnSwipedListener(new OnSwipeListener<T>() {
    
        @Override
        public void onSwiping(RecyclerView.ViewHolder viewHolder, float ratio, int direction) {
            /**
             * will callback when the card are swiping by user
             * viewHolder : thee viewHolder of swiping card
             * ratio : the ratio of swiping , you can add some animation by the ratio
             * direction : CardConfig.SWIPING_LEFT means swiping from left;CardConfig.SWIPING_RIGHT means swiping from right
             *             CardConfig.SWIPING_NONE means not left nor right
             */
        }
    
        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, T t, int direction) {
            /**
             *  will callback when the card swiped from screen by user
             *  you can also clean animation from the itemview of viewHolder in this method
             *  viewHolder : the viewHolder of swiped cards
             *  t : the data of swiped cards from dataList
             *  direction : CardConfig.SWIPED_LEFT means swiped from left;CardConfig.SWIPED_RIGHT means swiped from right
             */
        }
    
        @Override
        public void onSwipedClear() {
            /**
             *  will callback when all cards swiped clear
             *  you can load more data 
             */
        }
    
    });
    
    
    ### step 3
     java
    /*
    *Create stack photoview list
    */
     private void initData() {
            list.add(R.drawable.img_avatar_01);
            list.add(R.drawable.img_avatar_02);
            list.add(R.drawable.img_avatar_03);
            list.add(R.drawable.img_avatar_04);
            list.add(R.drawable.img_avatar_05);
            list.add(R.drawable.img_avatar_06);
            list.add(R.drawable.img_avatar_07);
    
        }

    Full Example

    Here is a full example of how to use swipe view.

    (a). MainActivity

    Here is the code for our only class, the main activity.

    public class MainActivity extends AppCompatActivity {
    
        private List<Integer> list = new ArrayList<>();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initView();
            initData();
        }
    
        private void initView() {
            final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(new StackViewAdapter());
            StackItemTouchHelperCallback cardCallback = new StackItemTouchHelperCallback(recyclerView.getAdapter(), list);
            cardCallback.setOnSwipedListener(new OnSwipeListener<Integer>() {
    
                @Override
                public void onSwiping(RecyclerView.ViewHolder viewHolder, float ratio, int direction) {
                    StackViewAdapter.MyViewHolder myHolder = (StackViewAdapter.MyViewHolder) viewHolder;
                    viewHolder.itemView.setAlpha(1 - Math.abs(ratio) * 0.2f);
                    if (direction == Utility.SWIPING_LEFT) {
                        myHolder.dislikeImageView.setAlpha(Math.abs(ratio));
                    } else if (direction == Utility.SWIPING_RIGHT) {
                        myHolder.likeImageView.setAlpha(Math.abs(ratio));
                    } else {
                        myHolder.dislikeImageView.setAlpha(0f);
                        myHolder.likeImageView.setAlpha(0f);
                    }
                }
    
                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, Integer o, int direction) {
                    StackViewAdapter.MyViewHolder myHolder = (StackViewAdapter.MyViewHolder) viewHolder;
                    viewHolder.itemView.setAlpha(1f);
                    myHolder.dislikeImageView.setAlpha(0f);
                    myHolder.likeImageView.setAlpha(0f);
                    Toast.makeText(MainActivity.this, direction == Utility.SWIPED_LEFT ? "dislike" : "like", Toast.LENGTH_SHORT).show();
                }
    
                @Override
                public void onSwipedClear() {
                    Toast.makeText(MainActivity.this, "finish data", Toast.LENGTH_SHORT).show();
                    recyclerView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            initData();
                            recyclerView.getAdapter().notifyDataSetChanged();
                        }
                    }, 3000L);
                }
    
            });
            final ItemTouchHelper touchHelper = new ItemTouchHelper(cardCallback);
            final StackLayoutViewManager cardLayoutManager = new StackLayoutViewManager(recyclerView, touchHelper);
            recyclerView.setLayoutManager(cardLayoutManager);
            touchHelper.attachToRecyclerView(recyclerView);
        }
    
        private void initData() {
            list.add(R.drawable.img_avatar_01);
            list.add(R.drawable.img_avatar_02);
            list.add(R.drawable.img_avatar_03);
            list.add(R.drawable.img_avatar_04);
            list.add(R.drawable.img_avatar_05);
            list.add(R.drawable.img_avatar_06);
            list.add(R.drawable.img_avatar_07);
    
        }
    
        private class StackViewAdapter extends RecyclerView.Adapter {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
                return new MyViewHolder(view);
            }
    
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                ImageView avatarImageView = ((MyViewHolder) holder).avatarImageView;
                avatarImageView.setImageResource(list.get(position));
            }
    
            @Override
            public int getItemCount() {
                return list.size();
            }
    
            class MyViewHolder extends RecyclerView.ViewHolder {
    
                StackImageView avatarImageView;
                ImageView likeImageView;
                ImageView dislikeImageView;
    
                MyViewHolder(View itemView) {
                    super(itemView);
                    avatarImageView = (StackImageView) itemView.findViewById(R.id.iv_avatar);
                    likeImageView = (ImageView) itemView.findViewById(R.id.iv_like);
                    dislikeImageView = (ImageView) itemView.findViewById(R.id.iv_dislike);
                }
    
            }
        }
    
    }

     

    Run

    If you run the project you get the following:

    Android SwipeView

    See less
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  8. Adv
  9. Shared a concept on: September 14, 2020

    Android Shared Element Transition

    Oclemy

    Oclemy

    • Nairobi, Kenya
    • 291 Concepts
    • 108 Examples
    • 0 Best Examples
    • 0 Points
    View Profile
    Oclemy
    Added an example on September 14, 2020 at 4:44 am

    Easily Implement Shared Transition on Images You can easily implement shared element transition on images using this library known as Transitional ImageView. Let's show you how to. Step 1 - Install the Library First register jitpack as a repository in your app level build.gradle: allprojects { reposRead more

    Easily Implement Shared Transition on Images

    You can easily implement shared element transition on images using this library known as Transitional ImageView.

    Let’s show you how to.

    Step 1 – Install the Library

    First register jitpack as a repository in your app level build.gradle:

    allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

    Then install the library:

    implementation 'com.github.mostafaaryan:transitional-imageview:v0.2.2'
    }

    Step 2

    Create Transitional ImageView in your layout by pasting the following code:

    <com.mostafaaryan.transitionalimageview.TransitionalImageView
            android:id="@+id/transitional_image"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:scaleType="fitXY"
            android:adjustViewBounds="true"
            app:res_id="@drawable/sample_image" />

    Step 3

    Now build a TransitionImageObject and set it to the TransitionalImageView:

    TransitionalImageView transitionalImageView = (TransitionalImageView) findViewById(R.id.transitional_image);
    TransitionalImage transitionalImage = new TransitionalImage.Builder()
                                        .duration(500)
                                        .backgroundColor(ContextCompat.getColor(MainActivity.this, R.color.color))
                                        .image(R.drawable.sample_image)
                                        /* or */
                                        .image(bitmap)
                                        .create();
    transitionalImageView.setTransitionalImage(transitionalImage);

    Full Example

    Here is a beautiful example for using this library.

    (a). Shoe.java

    The model class to define a single shoe.

    public class Shoe {
    
        private String Title;
        private String imageUrl;
    
        public Shoe(String title, String imageUrl) {
            Title = title;
            this.imageUrl = imageUrl;
        }
    
        public String getTitle() {
            return Title;
        }
    
        public String getImageUrl() {
            return imageUrl;
        }
    
    }

     

    (b). ShoeAdapter.java

    Then the recyclerview adapter.

    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.os.AsyncTask;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.widget.RecyclerView;
    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.ariannejad.mostafa.transitional_imageview_implementation.R;
    import com.ariannejad.mostafa.transitional_imageview_implementation.controller.MainActivity;
    import com.ariannejad.mostafa.transitional_imageview_implementation.model.Shoe;
    import com.mostafaaryan.transitionalimageview.TransitionalImageView;
    import com.mostafaaryan.transitionalimageview.model.TransitionalImage;
    import com.squareup.picasso.Picasso;
    
    
    import java.io.IOException;
    import java.util.ArrayList;
    
    /**
     * Created by Mostafa Aryan Nejad on 8/11/17.
     */
    
    public class ShoeAdapter extends RecyclerView.Adapter<ShoeAdapter.ViewHolder> {
    
        Context mContext;
        ArrayList<Shoe> shoes = new ArrayList<>();
    
        public ShoeAdapter(Context context, ArrayList<Shoe> shoes) {
            mContext = context;
            this.shoes = shoes;
        }
    
    
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_shoe, parent, false);
    
            return new ViewHolder(view);
        }
    
        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
    
            final Shoe shoe = shoes.get(position);
    
            AsyncTask.execute(new Runnable() {
                @Override
                public void run() {
                    try{
    
                        final Bitmap bitmap = Picasso.with(mContext).load(shoe.getImageUrl()).get();
                        ((Activity) mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                TransitionalImage transitionalImage = new TransitionalImage.Builder()
                                        .duration(500)
                                /*.backgroundColor(ContextCompat.getColor(, R.color.colorAccent))*/
                                        /*.image(R.drawable.sample_image)*/
                                        .image(bitmap)
                                        .create();
                                holder.image.setTransitionalImage(transitionalImage);
                                bitmap.recycle();
                            }
                        });
                    } catch (IOException e){e.printStackTrace();}
                }
            });
    
    
            holder.title.setText(shoe.getTitle());
            holder.sizes.setText("37,38,39,40");
    
    
        }
    
        @Override
        public int getItemCount() {
            return shoes.size();
        }
    
        public static class ViewHolder extends RecyclerView.ViewHolder {
    
            public TextView title;
            public TextView sizes;
            public TransitionalImageView image;
    
    
            public ViewHolder(View itemView) {
                super(itemView);
    
                title = (TextView) itemView.findViewById(R.id.shoe_title);
                sizes = (TextView) itemView.findViewById(R.id.shoe_sizes);
                image = (TransitionalImageView) itemView.findViewById(R.id.shoe_image);
    
            }
    
        }
    
    
    }

     

    (c). ShoeListActivity.java

    The shoe list activity:

    import android.support.design.widget.AppBarLayout;
    import android.support.design.widget.CollapsingToolbarLayout;
    import android.support.design.widget.TabLayout;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.Toolbar;
    
    import com.ariannejad.mostafa.transitional_imageview_implementation.R;
    import com.ariannejad.mostafa.transitional_imageview_implementation.adapter.ShoeAdapter;
    import com.ariannejad.mostafa.transitional_imageview_implementation.model.Shoe;
    
    import java.util.ArrayList;
    
    public class ShoeListActivity extends AppCompatActivity {
    
        private RecyclerView shoeRecyclerView;
        private ArrayList<Shoe> shoes = new ArrayList<>();
        private ActionBar actionBar;
        private AppBarLayout appBarLayout;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_shoe_list);
    
            shoeRecyclerView = (RecyclerView) findViewById(R.id.shoe_recycler_view);
            CollapsingToolbarLayout collapsingToolbar =
                    (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
            appBarLayout = (AppBarLayout) findViewById(R.id.app_bar_layout);
            setOnOffsetChangedListener();
            collapsingToolbar.setTitleEnabled(false);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            actionBar = getSupportActionBar();
            if(actionBar != null) actionBar.setTitle("");
    
    
            populateList();
    
        }
    
        private void populateList() {
            shoes.add(new Shoe("Skechers Relaxed Fit Empire Game On Walking Shoe",
                    "https://www.shoes.com/pm/skech/skech800828_42965_hd2.jpg"));
    
            shoes.add(new Shoe("Skechers After Burn Memory Fit Geardo High Top Trainer",
                    "https://www.shoes.com//pm/skech/skech798492_42965_hd2.jpg"));
    
            shoes.add(new Shoe("New Balance Fresh Foam Zante v3 Running Shoe",
                    "https://www.shoes.com/pi/newba/hd/newba805216_436896_hd.jpg"));
    
            for(int i = 0 ; i <= 5 ; i++ ) {
                shoes.addAll(shoes);
            }
    
            displayList();
        }
    
        private void displayList() {
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
            RecyclerView.Adapter adapter = new ShoeAdapter(this, shoes);
            shoeRecyclerView.setLayoutManager(layoutManager);
            shoeRecyclerView.setAdapter(adapter);
        }
    
        private void setOnOffsetChangedListener() {
    
            appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    
                boolean isDisplayed = false;
    
                @Override
                public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                    int totalScroll = appBarLayout.getTotalScrollRange();
    
                    if (totalScroll + verticalOffset == 0) {
                        if (actionBar != null) {
                            actionBar.setTitle("Sneakers");
                        }
                        isDisplayed = true;
                    } else if (isDisplayed) {
                        if (actionBar != null)
                            actionBar.setTitle("");
                        isDisplayed = false;
                    }
                }
    
            });
    
        }
    
    
    }

     

    (d). MainActivity.java

    And finally the main activity.

    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.os.AsyncTask;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    
    import com.ariannejad.mostafa.transitional_imageview_implementation.R;
    import com.mostafaaryan.transitionalimageview.TransitionalImageView;
    import com.mostafaaryan.transitionalimageview.model.TransitionalImage;
    import com.squareup.picasso.Picasso;
    
    import java.io.IOException;
    
    
    public class MainActivity extends AppCompatActivity {
    
        private String imageUrl = "https://image.freepik.com/free-icon/android-logo_318-54237.jpg";
        TransitionalImageView tiv;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            tiv = (TransitionalImageView) findViewById(R.id.sample_image);
    
            loadImage();
    
        }
    
        private void loadImage() {
    
            /*
            ImageLoader imageLoader;
            imageLoader = ImageLoader.getInstance();
            imageLoader.init(ImageLoaderConfiguration.createDefault(this));
            AsyncTask.execute(new Runnable() {
                @Override
                public void run() {
                    DisplayImageOptions dio = new DisplayImageOptions.Builder()
                            .cacheInMemory(false).build();
                    final Bitmap bmp = imageLoader.loadImageSync(imageUrl, dio);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tiv.setImage(bmp);
                        }
                    });
                }
            });*/
    
    
            /* Glide.with(this).asBitmap().load(imageUrl).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    tiv.setImage(resource);
                }
            }); */
    
            AsyncTask.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        final Bitmap b = Picasso.with(MainActivity.this).load(imageUrl).get();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
    //                            tiv.setImage(b);
                                TransitionalImage transitionalImage = new TransitionalImage.Builder()
                                        .duration(500)
                                        .backgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorAccent))
                                        //.image(R.drawable.sample_image)
                                        .image(b)
                                        .create();
                                tiv.setTransitionalImage(transitionalImage);
                            }
                        });
    
                    } catch (IOException e) {e.printStackTrace();}
                }
            });
    
    
        }
    
    
        public void onClickShoes(View view) {
            startActivity(new Intent(this, ShoeListActivity.class));
        }
    
    
    
    }

     

    Demo

    Here is the demo of what you get when you run the project.

    Android Shared Element Image Transition Example

    Download

    Here are the download links.

    1. Direct Download here.
    2. Follow Author here.
    See less
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  10. Adv
  11. Shared a concept on: September 14, 2020

    Android Shared Element Transition

    Oclemy

    Oclemy

    • Nairobi, Kenya
    • 291 Concepts
    • 108 Examples
    • 0 Best Examples
    • 0 Points
    View Profile
    Oclemy
    Added an example on September 14, 2020 at 4:26 am

    Kotlin Shared Transition RecyclerView and Fragments This is also a simple shared transitions example written in Kotlin. This time round however a recyclerview is the shared element among two fragments. Tools Here are the things to keep in mind: Programming Language - Kotlin Minimum SDK - 21 1. CreatRead more

    Kotlin Shared Transition RecyclerView and Fragments

    This is also a simple shared transitions example written in Kotlin. This time round however a recyclerview is the shared element among two fragments.

    Tools

    Here are the things to keep in mind:

    • Programming Language – Kotlin
    • Minimum SDK – 21

    1. Create Transitions

    In  a folder known as transitions under resources add the following:

    (a). change_bounds.xml

    <?xml version="1.0" encoding="utf-8"?>
    <transitionSet>
        <changeBounds />
    </transitionSet>

     

    (b). change_image_transform.xml

    Then:

    <?xml version="1.0" encoding="utf-8"?>
    <transitionSet>
        <changeImageTransform />
    </transitionSet>

     

    2. Design Layouts

    You will find the layouts in the code.

    3. Write Code

    Code is written in Kotlin in this case.

    (a). Fragment1.kt

    Here is the code for the first fragment.

    import android.os.Bundle
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import androidx.fragment.app.Fragment
    import androidx.recyclerview.widget.LinearLayoutManager
    import kotlinx.android.synthetic.main.activity_main.*
    import android.transition.ChangeBounds
    import android.transition.ChangeImageTransform
    
    
    class Fragment1: Fragment() {
    
        private lateinit var lm: LinearLayoutManager
    
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return inflater.inflate(R.layout.activity_main, container, false)
        }
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            lm = LinearLayoutManager(context, LinearLayoutManager.VERTICAL,
                false)
            rv.layoutManager = lm
            val adapter = MainActivity.Adapter()
            rv.adapter = adapter
            btn.setOnClickListener {
    
    //            val changeImageTransform =
    //                TransitionInflater.from(context).inflateTransition(R.transition.change_image_transform)
    //            val changeBoundsTransform =
    //                TransitionInflater.from(context).inflateTransition(R.transition.change_bounds)
    
                sharedElementReturnTransition = ChangeBounds()
                sharedElementEnterTransition = ChangeImageTransform()
                exitTransition = ChangeBounds()
    
                val fragment2 = Fragment2()
                // Setup transition on second fragment
                fragment2.sharedElementEnterTransition = ChangeBounds()
                fragment2.enterTransition = ChangeBounds();
    
                val firstVisiblePosition = lm.findFirstVisibleItemPosition()
                val lastVisiblePosition = lm.findLastVisibleItemPosition()
                val transaction = fragmentManager!!.beginTransaction()
                    .replace(R.id.container, fragment2, fragment2::class.java.simpleName)
                    .addToBackStack("name")
                for (i in firstVisiblePosition..lastVisiblePosition) {
                    val holderForAdapterPosition =
                        rv.findViewHolderForAdapterPosition(i) as MainActivity.Adapter.Holder
                    val itemView = holderForAdapterPosition.itemView
                    transaction.addSharedElement(itemView, "unique_key_$i")
                }
                transaction.commit()
            }
        }
    }

     

    (b). Fragment2.kt

    Add the following code in second fragment.

    import android.os.Bundle
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import androidx.fragment.app.Fragment
    import androidx.recyclerview.widget.LinearLayoutManager
    import kotlinx.android.synthetic.main.activity_main.*
    
    class Fragment2: Fragment() {
    
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return inflater.inflate(R.layout.activity_main, container, false)
        }
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            val lm = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL,
                false)
            rv.layoutManager = lm
            val adapter = MainActivity.Adapter()
            rv.adapter = adapter
            btn.setOnClickListener {
            }
            postponeEnterTransition()
        }
    
        override fun onStart() {
            super.onStart()
            rv.post {
                startPostponedEnterTransition()
            }
        }
    }

     

    (c). ScndActivity.kt

    Then the second activity.

    import android.os.Bundle
    import android.os.PersistableBundle
    import androidx.appcompat.app.AppCompatActivity
    import androidx.recyclerview.widget.LinearLayoutManager
    import kotlinx.android.synthetic.main.activity_main.*
    
    class ScndActivity: AppCompatActivity() {
    
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            val lm = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,
                false)
            rv.layoutManager = lm
            val adapter = MainActivity.Adapter()
            rv.adapter = adapter
            btn.setOnClickListener {
    
                //            val currentOrientation = lm.orientation
    //            if (currentOrientation == LinearLayoutManager.VERTICAL) {
    //                lm.orientation = LinearLayoutManager.HORIZONTAL
    //            } else {
    //                lm.orientation = LinearLayoutManager.VERTICAL
    //            }
    //            adapter.notifyItemRangeChanged(1, adapter?.itemCount ?: 0)
            }
            supportPostponeEnterTransition()
            rv.post {
                supportStartPostponedEnterTransition()
            }
        }
    }

     

    (d). MainActivity.kt

    And lastly the main activity,

    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import androidx.recyclerview.widget.LinearLayoutManager
    import androidx.recyclerview.widget.RecyclerView
    
    
    class MainActivity : AppCompatActivity() {
    
        private lateinit var lm: LinearLayoutManager
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.cont)
            val fragment1 = Fragment1()
            supportFragmentManager.beginTransaction()
                .add(R.id.container, fragment1, Fragment1::class.java.simpleName)
                .commit()
    //        lm = LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
    //            false)
    //        rv.layoutManager = lm
    //        val adapter = Adapter()
    //        rv.adapter = adapter
    //        btn.setOnClickListener {
    //            val firstVisiblePosition = lm.findFirstVisibleItemPosition()
    //            val lastVisiblePosition = lm.findLastVisibleItemPosition()
    //            val pairs = ArrayList<Pair<View, String>>()
    //            for (i in firstVisiblePosition..lastVisiblePosition) {
    //                val holderForAdapterPosition =
    //                    rv.findViewHolderForAdapterPosition(i) as Adapter.Holder
    //                val itemView = holderForAdapterPosition.itemView
    //                pairs.add(Pair(itemView, "unique_key_$i"))
    //            }
    //            val bundle = ActivityOptions.makeSceneTransitionAnimation(
    //                this,
    //                *pairs.toTypedArray()
    //            ).toBundle()
    //            val fragment1 = Fragment1()
    //            supportFragmentManager.beginTransaction()
    //                .add(fragment1, Fragment1::class.java.simpleName)
    //                .commit()
    //            startActivity(Intent(this, ScndActivity::class.java), bundle)
    //        }
        }
    
        override fun onResume() {
            super.onResume()
        }
    
        class Adapter : RecyclerView.Adapter<Adapter.Holder>() {
    
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder =
                Holder(
                    LayoutInflater.from(parent.context).inflate(
                        R.layout.item_item,
                        parent,
                        false
                    )
                )
    
            override fun getItemCount(): Int = 10
    
            override fun onBindViewHolder(holder: Holder, position: Int) {
                holder.bind(position)
            }
    
            class Holder(view: View) : RecyclerView.ViewHolder(view) {
    
                fun bind(position: Int) {
                    itemView.transitionName = "unique_key_$position"
                }
            }
        }
    }

     

    Demo

    Here is what you get when you run the project.

    Android Kotlin Shared Transition Example RecyclerView

    Download

    1. Direct Download here.
    2. Follow Author here.
    See less
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  12. Adv
  13. Shared a concept on: September 14, 2020

    Android Shared Element Transition

    Oclemy

    Oclemy

    • Nairobi, Kenya
    • 291 Concepts
    • 108 Examples
    • 0 Best Examples
    • 0 Points
    View Profile
    Oclemy
    Added an example on September 14, 2020 at 4:07 am

    Java Shared Transition with Fragments and FloatingActionButton This is a simple one-class example to utilize a shared element transition within fragments in an android activity. The programming language is Java. While it is not written in androidx, you can easily update it to androidx fragments andRead more

    Java Shared Transition with Fragments and FloatingActionButton

    This is a simple one-class example to utilize a shared element transition within fragments in an android activity. The programming language is Java. While it is not written in androidx, you can easily update it to androidx fragments and it doesn’t utilize any third partt library.

    shared

    Transitions

    These are written in XML.  Tyically you create a transition resource directory and place the XML.

    (a). shared_enter_transition.xml

    Here is the code:

    <?xml version="1.0" encoding="utf-8"?>
    <transitionSet xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="@integer/default_anim_duration">
    
        <changeTransform/>
        <arcMotion
            android:minimumHorizontalAngle="0"
            android:minimumVerticalAngle="15"
            android:maximumAngle="90" />
        <changeBounds />
    
    </transitionSet>

     

    Activities

    Here are the activities

    (a). MainActivity.java

    Here is the main activity:

    import android.animation.Animator;
    import android.app.Fragment;
    import android.os.Bundle;
    import android.support.v4.view.ViewCompat;
    import android.support.v7.app.ActionBarActivity;
    import android.transition.Fade;
    import android.transition.Transition;
    import android.transition.TransitionInflater;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewAnimationUtils;
    import android.view.ViewGroup;
    import android.view.animation.AccelerateInterpolator;
    
    public class FabActivity extends ActionBarActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_fab);
    
            getFragmentManager()
                    .beginTransaction()
                    .add(R.id.frag_content, TitleFragment.newInstance())
                    .commit();
        }
    
    
        public static class TitleFragment extends Fragment {
            public static TitleFragment newInstance() {
                return new TitleFragment();
            }
    
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                final View view = inflater.inflate(R.layout.fragment_fab_title, container, false);
                final View fabbutton = view.findViewById(R.id.fab);
                fabbutton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final ControlsFragment controlsFragment = ControlsFragment.newInstance();
    
                        setupSharedElementTransition(controlsFragment);
                        Fade f = new Fade();
                        f.setStartDelay(250);
                        setExitTransition(f);
    
                        getFragmentManager()
                                .beginTransaction()
                                .replace(R.id.frag_content, controlsFragment)
                                .addToBackStack("controls")
                                .addSharedElement(fabbutton, "pause_button")
                                .commit();
                    }
                });
                return view;
            }
    
            private void setupSharedElementTransition(final ControlsFragment controlsFragment) {
                Transition sharedTransition = TransitionInflater.from(getActivity()).inflateTransition(R.transition.shared_enter_transition);
                controlsFragment.setSharedElementEnterTransition(sharedTransition);
                controlsFragment.setSharedElementReturnTransition(sharedTransition);
                sharedTransition.addListener(new Transition.TransitionListener() {
                    @Override
                    public void onTransitionEnd(Transition transition) {
                        controlsFragment.revealContent();
                    }
    
                    @Override
                    public void onTransitionStart(Transition transition) {
                    }
    
                    @Override
                    public void onTransitionCancel(Transition transition) {
                    }
    
                    @Override
                    public void onTransitionPause(Transition transition) {
                    }
    
                    @Override
                    public void onTransitionResume(Transition transition) {
                    }
                });
    
            }
    
    
        }
    
        public static class ControlsFragment extends Fragment {
    
            public static ControlsFragment newInstance() {
                return new ControlsFragment();
            }
    
    
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                return inflater.inflate(R.layout.fragment_fab_controls, container, false);
            }
    
    
            public void revealContent() {
                View layout = getView().findViewById(R.id.controls_layout);
                animateRevealColor(layout);
            }
    
            private void animateRevealColor(View targetView) {
                int cx = (targetView.getLeft() + targetView.getRight()) / 2;
                int cy = (targetView.getTop() + targetView.getBottom()) / 2;
    
                cx += targetView.getTranslationX();
                cy += targetView.getTranslationY();
                int finalRadius = Math.max(targetView.getWidth(), targetView.getHeight());
    
                Animator anim = ViewAnimationUtils.createCircularReveal(targetView, cx, cy, 0, finalRadius);
                targetView.setBackgroundColor(getResources().getColor(R.color.accent_material_light));
                anim.setDuration(getResources().getInteger(R.integer.default_anim_duration));
                anim.setInterpolator(new AccelerateInterpolator());
                anim.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationEnd(Animator animator) {
                        animateScaleButton(getView().findViewById(R.id.ff_button));
                        animateScaleButton(getView().findViewById(R.id.rew_button));
                    }
    
                    @Override
                    public void onAnimationStart(Animator animator) {
                    }
    
                    @Override
                    public void onAnimationCancel(Animator animator) {
                    }
    
                    @Override
                    public void onAnimationRepeat(Animator animator) {
                    }
                });
                anim.start();
            }
    
            private void animateScaleButton(View view) {
                ViewCompat.animate(view)
                        .scaleX(1)
                        .scaleY(1)
                        .setDuration(250)
                        .start();
            }
        }
    
    }

    Demo

    Here is the demo of what you get when you run the project.

    Fragments Shared Element Transition

    Download Links

    1. Directly download the code here. (Please update it to androidx and reshare your code)
    2. Follow Author here.
    See less
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  14. Adv
  15. Shared a concept on: September 13, 2020In: Communication

    Android Email

    Oclemy

    Oclemy

    • Nairobi, Kenya
    • 291 Concepts
    • 108 Examples
    • 0 Best Examples
    • 0 Points
    View Profile
    Oclemy
    Added an example on September 13, 2020 at 8:42 am

    EmailIntentBuilder This an Android Library for the creation of SendTo Intents with mailto: URI. Step 1 - Installation Install the library by adding the following statement in your build.gradle  file: implementation 'de.cketti.mailto:email-intent-builder:2.0.0'   Step 2 Then set the appropriateRead more

    EmailIntentBuilder

    This an Android Library for the creation of SendTo Intents with mailto: URI.

    Step 1 – Installation

    Install the library by adding the following statement in your build.gradle  file:

    implementation 'de.cketti.mailto:email-intent-builder:2.0.0'

     

    Step 2

    Then set the appropriate fields to be sent:

    EmailIntentBuilder.from(activity)
            .to("alice@example.org")
            .cc("bob@example.org")
            .bcc("charles@example.org")
            .subject("Message from an app")
            .body("Some text here")
            .start();

    FULL EXAMPLE

    Here is a full example to use this library to send email:

    (a). MainActivity.java

    import android.os.Bundle;
    import android.text.TextUtils;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.EditText;
    
    import androidx.appcompat.app.AppCompatActivity;
    import com.google.android.material.snackbar.Snackbar;
    import de.cketti.mailto.EmailIntentBuilder;
    
    
    public class MainActivity extends AppCompatActivity {
        private View mainContent;
        private EditText emailTo;
        private EditText emailCc;
        private EditText emailBcc;
        private EditText emailSubject;
        private EditText emailBody;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mainContent = findViewById(R.id.main_content);
            emailTo = findViewById(R.id.email_to);
            emailCc = findViewById(R.id.email_cc);
            emailBcc = findViewById(R.id.email_bcc);
            emailSubject = findViewById(R.id.email_subject);
            emailBody = findViewById(R.id.email_body);
    
            findViewById(R.id.button_send_email).setOnClickListener(v -> sendEmail());
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == R.id.menu_feedback) {
                sendFeedback();
            }
            return true;
        }
    
        private void sendFeedback() {
            boolean success = EmailIntentBuilder.from(this)
                    .to("cketti@gmail.com")
                    .subject(getString(R.string.feedback_subject))
                    .body(getString(R.string.feedback_body))
                    .start();
    
            if (!success) {
                Snackbar.make(mainContent, R.string.error_no_email_app, Snackbar.LENGTH_LONG).show();
            }
        }
    
        void sendEmail() {
            String to = emailTo.getText().toString();
            String cc = emailCc.getText().toString();
            String bcc = emailBcc.getText().toString();
            String subject = emailSubject.getText().toString();
            String body = emailBody.getText().toString();
    
            EmailIntentBuilder builder = EmailIntentBuilder.from(this);
    
            try {
                if (!TextUtils.isEmpty(to)) {
                    builder.to(to);
                }
                if (!TextUtils.isEmpty(cc)) {
                    builder.cc(cc);
                }
                if (!TextUtils.isEmpty(bcc)) {
                    builder.bcc(bcc);
                }
                if (!TextUtils.isEmpty(subject)) {
                    builder.subject(subject);
                }
                if (!TextUtils.isEmpty(body)) {
                    builder.body(body);
                }
    
                boolean success = builder.start();
                if (!success) {
                    Snackbar.make(mainContent, R.string.error_no_email_app, Snackbar.LENGTH_LONG).show();
                }
            } catch (IllegalArgumentException e) {
                String errorMessage = getString(R.string.argument_error, e.getMessage());
                Snackbar.make(mainContent, errorMessage, Snackbar.LENGTH_LONG).show();
            }
        }
    }

     

    Download

    Here are the links:

    1. Directly Download the code here.
    2. Browse through the code or read more here.
    3. Follow Author here.
    See less
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  16. Adv
  17. Shared a concept on: September 12, 2020

    Android Uri

    Oclemy

    Oclemy

    • Nairobi, Kenya
    • 291 Concepts
    • 108 Examples
    • 0 Best Examples
    • 0 Points
    View Profile
    Oclemy
    Added an example on September 13, 2020 at 8:09 am

    PickiT This is an Android library that  you can use to return real paths from Uri's. Follow the following steps to use it. Step 1 - Installation The library is hosted in jitpack so go to your project-level build.gradle and specify jitpack URL:   allprojects { repositories { ... maven { url 'httRead more

    PickiT

    This is an Android library that  you can use to return real paths from Uri’s.

    Follow the following steps to use it.

    Step 1 – Installation

    The library is hosted in jitpack so go to your project-level build.gradle and specify jitpack URL:

     

    allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

     

    Then go to your app level build.gradle and add the dependency then sync:

     

    implementation 'com.github.HBiSoft:PickiT:0.1.14'

     

    Step 2 – Usage

    Implement PickiTCallback as follows:

     

    public class MainActivity extends AppCompatActivity implements PickiTCallbacks {
    

    Then:

     

        //Declare PickiT
        PickiT pickiT;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //Initialize PickiT
            //context, listener, activity
            pickiT = new PickiT(this, this, this);
    
        }
    }

     

    So for example assume that using your Filepicker you’ve selected the file and now you want to convert the Uri to a real path inside the onActivityResult:

     

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_VIDEO_REQUEST) {
            if (resultCode == RESULT_OK) {
                pickiT.getPath(data.getData(), Build.VERSION.SDK_INT);
    
            }
        }
    }

     

    NB/= If you are targeting SDK 29> add android:requestLegacyExternalStorage="true" in your manifest:

     

    <manifest ... >
      <application 
        android:requestLegacyExternalStorage="true" 
      </application>
    </manifest>

    The reason for this is, in Android 10 file path access was removed and it returned in Android 11.
    If you are targiting SDK 29> and you do not add this, you will get EACCES (Permission denied)

    FULL EXAMPLE

    Here is a full example.

    (a). MainActivity.java

     

    import android.Manifest;
    import android.annotation.SuppressLint;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.os.Build;
    import android.os.Environment;
    
    import androidx.annotation.NonNull;
    import androidx.appcompat.app.AlertDialog;
    import androidx.appcompat.view.ContextThemeWrapper;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.hbisoft.pickit.PickiT;
    import com.hbisoft.pickit.PickiTCallbacks;
    
    public class MainActivity extends AppCompatActivity implements PickiTCallbacks {
        //Permissions
        private static final int SELECT_VIDEO_REQUEST = 777;
        private static final int PERMISSION_REQ_ID_RECORD_AUDIO = 22;
        private static final int PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE = PERMISSION_REQ_ID_RECORD_AUDIO + 1;
    
        //Declare PickiT
        PickiT pickiT;
    
        //Views
        Button button_pick;
        TextView pickitTv, originalTv, originalTitle, pickitTitle;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            init();
            buttonClickEvent();
    
            //Initialize PickiT
            pickiT = new PickiT(this, this, this);
    
        }
    
        //Show Toast
        private void showLongToast(final String msg) {
            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
        }
    
        private void init() {
            button_pick = findViewById(R.id.button_pick);
            pickitTv = findViewById(R.id.pickitTv);
            originalTv = findViewById(R.id.originalTv);
            originalTitle = findViewById(R.id.originalTitle);
            pickitTitle = findViewById(R.id.pickitTitle);
        }
    
        private void buttonClickEvent() {
            button_pick.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    openGallery();
    
                    //  Make TextView's invisible
                    originalTitle.setVisibility(View.INVISIBLE);
                    originalTv.setVisibility(View.INVISIBLE);
                    pickitTitle.setVisibility(View.INVISIBLE);
                    pickitTv.setVisibility(View.INVISIBLE);
                }
            });
        }
    
        private void openGallery() {
            //  first check if permissions was granted
            if (checkSelfPermission()) {
                Intent intent;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                } else {
                    intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI);
                }
                //  In this example we will set the type to video
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.putExtra("return-data", true);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivityForResult(intent, SELECT_VIDEO_REQUEST);
            }
        }
    
        //  Check if permissions was granted
        private boolean checkSelfPermission() {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MainActivity.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE);
                return false;
            }
            return true;
        }
    
        //  Handle permissions
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            if (requestCode == PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //  Permissions was granted, open the gallery
                    openGallery();
                }
                //  Permissions was not granted
                else {
                    showLongToast("No permission for " + Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
            }
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == SELECT_VIDEO_REQUEST) {
                if (resultCode == RESULT_OK) {
    
                    //  Get path from PickiT (The path will be returned in PickiTonCompleteListener)
                    //
                    //  If the selected file is from Dropbox/Google Drive or OnDrive:
                    //  Then it will be "copied" to your app directory (see path example below) and when done the path will be returned in PickiTonCompleteListener
                    //  /storage/emulated/0/Android/data/your.package.name/files/Temp/tempDriveFile.mp4
                    //
                    //  else the path will directly be returned in PickiTonCompleteListener
                    pickiT.getPath(data.getData(), Build.VERSION.SDK_INT);
    
                    originalTv.setText(String.valueOf(data.getData()));
    
                }
            }
        }
    
        //
        //  PickiT Listeners
        //
        //  The listeners can be used to display a Dialog when a file is selected from Dropbox/Google Drive or OnDrive.
        //  The listeners are callbacks from an AsyncTask that creates a new File of the original in /storage/emulated/0/Android/data/your.package.name/files/Temp/
        //
        //  PickiTonUriReturned()
        //  When selecting a file from Google Drive, for example, the Uri will be returned before the file is available(if it has not yet been cached/downloaded).
        //  Google Drive will first have to download the file before we have access to it.
        //  This can be used to let the user know that we(the application), are waiting for the file to be returned.
        //
        //  PickiTonStartListener()
        //  This will be call once the file creations starts and will only be called if the selected file is not local
        //
        //  PickiTonProgressUpdate(int progress)
        //  This will return the progress of the file creation (in percentage) and will only be called if the selected file is not local
        //
        //  PickiTonCompleteListener(String path, boolean wasDriveFile)
        //  If the selected file was from Dropbox/Google Drive or OnDrive, then this will be called after the file was created.
        //  If the selected file was a local file then this will be called directly, returning the path as a String
        //  Additionally, a boolean will be returned letting you know if the file selected was from Dropbox/Google Drive or OnDrive.
    
        ProgressBar mProgressBar;
        TextView percentText;
        private AlertDialog mdialog;
        ProgressDialog progressBar;
    
        @Override
        public void PickiTonUriReturned() {
            progressBar = new ProgressDialog(this);
            progressBar.setMessage("Waiting to receive file...");
            progressBar.setCancelable(false);
            progressBar.show();
        }
    
        @Override
        public void PickiTonStartListener() {
            if (progressBar.isShowing()){
                progressBar.cancel();
            }
            final AlertDialog.Builder mPro = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.myDialog));
            @SuppressLint("InflateParams") final View mPView = LayoutInflater.from(this).inflate(R.layout.dailog_layout, null);
            percentText = mPView.findViewById(R.id.percentText);
    
            percentText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    pickiT.cancelTask();
                    if (mdialog != null && mdialog.isShowing()) {
                        mdialog.cancel();
                    }
                }
            });
    
            mProgressBar = mPView.findViewById(R.id.mProgressBar);
            mProgressBar.setMax(100);
            mPro.setView(mPView);
            mdialog = mPro.create();
            mdialog.show();
    
        }
    
        @Override
        public void PickiTonProgressUpdate(int progress) {
            String progressPlusPercent = progress + "%";
            percentText.setText(progressPlusPercent);
            mProgressBar.setProgress(progress);
        }
    
        @Override
        public void PickiTonCompleteListener(String path, boolean wasDriveFile, boolean wasUnknownProvider, boolean wasSuccessful, String reason) {
    
            if (mdialog != null && mdialog.isShowing()) {
                mdialog.cancel();
            }
    
            //  Check if it was a Drive/local/unknown provider file and display a Toast
            if (wasDriveFile){
                showLongToast("Drive file was selected");
            }else if (wasUnknownProvider){
                showLongToast("File was selected from unknown provider");
            }else {
                showLongToast("Local file was selected");
            }
    
            //  Chick if it was successful
            if (wasSuccessful) {
                //  Set returned path to TextView
                pickitTv.setText(path);
    
                //  Make TextView's visible
                originalTitle.setVisibility(View.VISIBLE);
                originalTv.setVisibility(View.VISIBLE);
                pickitTitle.setVisibility(View.VISIBLE);
                pickitTv.setVisibility(View.VISIBLE);
            }else {
                showLongToast("Error, please see the log..");
                pickitTv.setVisibility(View.VISIBLE);
                pickitTv.setText(reason);
            }
        }
    
    
        //
        //  Lifecycle methods
        //
    
        //  Deleting the temporary file if it exists
        @Override
        public void onBackPressed() {
            pickiT.deleteTemporaryFile(this);
            super.onBackPressed();
        }
    
        //  Deleting the temporary file if it exists
        //  As we know, this might not even be called if the system kills the application before onDestroy is called
        //  So, it is best to call pickiT.deleteTemporaryFile(); as soon as you are done with the file
        @Override
        public void onDestroy() {
            super.onDestroy();
            if (!isChangingConfigurations()) {
                pickiT.deleteTemporaryFile(this);
            }
        }
    
    }

    Demo

    Download

    Here are the links:

    1. Direct Download here.
    2. Read more here.
    3. Follow author here.
    See less
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  18. Adv
  19. Shared a concept on: September 12, 2020

    Android Uri

    Oclemy

    Oclemy

    • Nairobi, Kenya
    • 291 Concepts
    • 108 Examples
    • 0 Best Examples
    • 0 Points
    View Profile
    Oclemy
    Added an example on September 13, 2020 at 7:49 am

    Some Utility Uri Examples Here are some important utility methods you may need when coding. (a). Get Path from Uri You need to return a real path as a string and you have a Uri. public static String getPath(final Context context, final Uri uri) { //check for KITKAT or above final boolean isKitKat =Read more

    Some Utility Uri Examples

    Here are some important utility methods you may need when coding.

    (a). Get Path from Uri

    You need to return a real path as a string and you have a Uri.

    public static String getPath(final Context context, final Uri uri) {
                //check for KITKAT or above
                final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    
                // DocumentProvider
                if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                    // ExternalStorageProvider
                    if (isExternalStorageDocument(uri)) {
                        final String docId = DocumentsContract.getDocumentId(uri);
                        final String[] split = docId.split(":");
                        final String type = split[0];
    
                        if ("primary".equalsIgnoreCase(type)) {
                            return Environment.getExternalStorageDirectory() + "/" + split[1];
                        }
                    }
                    // DownloadsProvider
                    else if (isDownloadsDocument(uri)) {
                        return getDownloadFilePath(context, uri);
                    }
                    // MediaProvider
                    else if (isMediaDocument(uri)) {
                        final String docId = DocumentsContract.getDocumentId(uri);
                        final String[] split = docId.split(":");
                        final String type = split[0];
    
                        Uri contentUri = null;
                        if ("image".equals(type)) {
                            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                        } else if ("video".equals(type)) {
                            contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                        } else if ("audio".equals(type)) {
                            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                        }
    
                        final String selection = "_id=?";
                        final String[] selectionArgs = new String[] {
                                split[1]
                        };
    
                        return getDataColumn(context, contentUri, selection, selectionArgs);
                    }
                }
    
                // MediaStore (and general)
                else if ("content".equalsIgnoreCase(uri.getScheme())) {
                    // Return the remote address
                    if (isGooglePhotosUri(uri))
                        return uri.getLastPathSegment();
    
                    return getDataColumn(context, uri, null, null);
                }
                // File
                else if ("file".equalsIgnoreCase(uri.getScheme())) {
                    return uri.getPath();
                }
    
                return null;
            }

     

    (b). Get Data Column when given Uri

     

    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {
    
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

     

    (c). Get Downloads Path

    You have a Uri and you want to return the downloads path.

     

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static String getDownloadFilePath(Context context, Uri uri){
        Cursor cursor = null;
        final String[] projection = {
                MediaStore.MediaColumns.DISPLAY_NAME
        };
        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                String fileName=cursor.getString(0);
                String path =Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
                if (!TextUtils.isEmpty(path)){
                    return path;
                }
            }
        } finally {
            cursor.close();
        }
        String id = DocumentsContract.getDocumentId(uri);
        if (id.startsWith("raw:")) {
            return id.replaceFirst("raw:", "");
        }
        Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads"), java.lang.Long.valueOf(id));
    
        return getDataColumn(context, contentUri, null, null);
    }

     

    Here are more examples:

     

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
    
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }
    
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
    
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

     

    Download

    Here are the links:

    1. Direct Download this java file here.
    2. Follow Author here.
    See less
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
1 2 3 … 11
Adv

Sidebar

Adv 250x250

Adv

Recent Examples

  • Oclemy on Android URL Preview
  • Oclemy on Android Firebase RecyclerView MasterDetail CRUD Images Text – Upload, READ, DELETE
  • nill on Android Firebase RecyclerView MasterDetail CRUD Images Text – Upload, READ, DELETE
  • Oclemy on Android RatingBar
  • Oclemy on Best Android Swipe Cards Libraries and Examples

Adv 250x250

Adv

Explore

  • Home
  • Buy Projects
  • Categories
  • Concepts
    • Newest Concepts
    • Trending
    • Most Popular
    • Hottest

Footer

Follow Me in Github

Follow @Oclemy

© 2020 Sedan InfoTech. All Rights Reserved
.