OneTouchCode.com http://onetouchcode.com Blog for developers to improve coding skills Sun, 15 Oct 2017 11:19:36 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.5 111622670 Android – Limitations of SQLite http://onetouchcode.com/2017/10/15/android-limitations-sqlite/ http://onetouchcode.com/2017/10/15/android-limitations-sqlite/#respond Sun, 15 Oct 2017 11:19:35 +0000 http://onetouchcode.com/?p=842 SQLite support in Android is certainly very crucial for data driven enterprise applications. But SQLite for Android comes up with certain restrictions and limitations which is important for us to know as an Android...

The post Android – Limitations of SQLite appeared first on OneTouchCode.com.

]]>
SQLite support in Android is certainly very crucial for data driven enterprise applications. But SQLite for Android comes up with certain restrictions and limitations which is important for us to know as an Android developer. Here is the list which I found –

SQLite

Non-Integer Primary key handling

SQLite supports non-integer primary key but here is a catch you have to use NON NULL constraints too because SQLite allows null as a value to be hold by the non-integer primary key column and thus permits multiple rows in a table having null in primary key column.

 

Referential Integrity Support

By default, SQLite does not enforce foreign key constraints so even if you have use foreign key in your database design insert statements will not fail for entering wrong data. To enable referential integrity support in recent versions of Android, use pragma foreign_key = true

 

Alter statement for multiple columns

Alter statement is very useful in sql queries for changing the definition of Tables without dropping and recreating but unfortunately SQLite for Android support only one column per Alter statement. So if you have to alter single table with N columns then you have to  write N Alter statements.

Read also –

 

SQLite doesn’t use static typing

Any information in SQLite depeneds on the type of value inserted, not on the definition of the Table as per CREATE Table statement. To be more precise you can insert text inside an INTEGER column which is as per design of SQLite. So you have to very careful while inserting values than creating table.

 

Raw query flaws

In most cases where table join needed and if no ORM library is in use then Android developers end up writing raw sql queries using execSQL and rawQuery which accept bindArgs but developers ignores it. And the query looks like –

db.execSQL("delete from people where name='"+person+"' and added_date < "+ String.valueOf(System.currentTimeMillis() - HISTORY));

Now lets assume if the person parameter contains the value Robert'; .

Note that execSQL method ignores any text that appears after a semicolon. After the execution of above query the code will delete all the records for Robert instead just a few historical records. This kind of error can be avoided simply by using bindArgs.

 

SQLite Database managing strategies

There are two basic strategies for managing database from an Application:

  • Get it and keep it
  • Get it when you need it.

The first strategy is the simpler and a reasonable option as an open database is about few KBs of memory. An application with multiple activities, only one or few of which uses the database, then holding the database means that the memory it occupies cannot be re-purposed. Meanwhile if the application’s process terminated because it has been in the background for too long and several other new application started – the database, any connections and everything else that is part of application’s memory space are gone.

 

And if the code forgets to explicitly close the db connection, the garbage collector will collect the instance that will generate an error message – close() was never explicitly called on database.

 

To avoid this it better to open the database inside the Application instance variable or in a static class variable.

Few of the points I have referred from Enterprise Android book.

Happy coding!

The post Android – Limitations of SQLite appeared first on OneTouchCode.com.

]]>
http://onetouchcode.com/2017/10/15/android-limitations-sqlite/feed/ 0 842
Android – Attach a view on hamburger menu icon http://onetouchcode.com/2017/10/08/android-attach-view-hamburger-menu-icon/ http://onetouchcode.com/2017/10/08/android-attach-view-hamburger-menu-icon/#respond Sun, 08 Oct 2017 16:19:05 +0000 http://onetouchcode.com/?p=831 Hamburger menu icon is common to most of the Android developers. But have any one of you tried to overlay another view on top or side of this menu icon ? if not then...

The post Android – Attach a view on hamburger menu icon appeared first on OneTouchCode.com.

]]>
Hamburger menu icon is common to most of the Android developers. But have any one of you tried to overlay another view on top or side of this menu icon ? if not then this article will help you to achieve this with a simple trick. Lets have a look –

Prerequisites

  • You have to use android.support.v7.widget.Toolbar if not using it.
  • You have to use  android.support.v4.widget.DrawerLayout, NavigationView  and AppBarLayout too.

So Toolbar, DrawerLayout, NavigationView and AppBarLayout is required anyhow to implement side menus and which eventually shows the Hamburger menu icon.

How to overlay a view on Hamburger menu icon

Now the trick to overlay a view is very simple, we mostly use Toolbar before the Drawer layout so that NavigationView appears below the Toolbar, but now we just need to place the Toolbar inside a layout and use any other view of your choice within that layout proportionate to the Toolbar and you are done.

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/app_theme_light"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/tool_bar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:animateLayoutChanges="true"
            android:background="?attr/colorPrimary"
            android:elevation="2dp"
            android:transitionName="@string/transition.toolbar"
            app:layout_scrollFlags="snap|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:subtitleTextColor="@color/white"
            app:titleTextColor="@color/white">

        </android.support.v7.widget.Toolbar>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:elevation="2dp"
            android:src="@drawable/ic_info" />

    </RelativeLayout>

    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/dlMenus"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="false"
        tools:openDrawer="start">

        <android.support.design.widget.CoordinatorLayout
            android:id="@+id/main_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.design.widget.AppBarLayout
                android:id="@+id/appbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

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

            <!-- TODO add your layouts and views for main screen here-->
        </android.support.design.widget.CoordinatorLayout>

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true">

            <!-- TODO add your layouts and views  for side menus here-->
        </android.support.design.widget.NavigationView>
    </android.support.v4.widget.DrawerLayout>
</LinearLayout>

In the above code I have placed the Toolbar inside a RelativeLayout and then added an ImageView with a small margin and see how it looks.

hamburger menu

 

With similar technique you can also achieve this kind of customization. I hope this article will be helpful to the developers.

Happy coding!

The post Android – Attach a view on hamburger menu icon appeared first on OneTouchCode.com.

]]>
http://onetouchcode.com/2017/10/08/android-attach-view-hamburger-menu-icon/feed/ 0 831
Android: Display PDF using PdfRenderer http://onetouchcode.com/2017/08/20/android-display-pdf-using-pdfrenderer/ http://onetouchcode.com/2017/08/20/android-display-pdf-using-pdfrenderer/#respond Sun, 20 Aug 2017 07:35:51 +0000 http://onetouchcode.com/?p=819 In Android there was one much needed missing area i.e., displaying a pdf document within an Android app which currently solves with the introduction of PdfRenderer api from Api level 21 onwards.  I have...

The post Android: Display PDF using PdfRenderer appeared first on OneTouchCode.com.

]]>
In Android there was one much needed missing area i.e., displaying a pdf document within an Android app which currently solves with the introduction of PdfRenderer api from Api level 21 onwards.  I have added the source code link at the bottom of the article to try it out.

Display Pdf using PdfRenderer in Android apps

API’s needed to render PDF

Below is the list of bare minimum api’s needed to display a pdf document.

Steps to render PDF

There are three important steps to display a pdf document, these are as follows –

  • Step 1 : Initialization of PdfRenderer

The first and foremost step is to initialize PdfRenderer by opening the pdf file and passing FileDescriptor object to PdfRenderer  constructor.

/**
     * Sets up a {@link android.graphics.pdf.PdfRenderer} and related resources.
     */
    private void openRenderer(Context context) throws IOException {
        // In this sample, we read a PDF from the assets directory.
        File file = new File(context.getCacheDir(), FILENAME);
        if (!file.exists()) {
            // Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
            // the cache directory.
            InputStream asset = context.getAssets().open(FILENAME);
            FileOutputStream output = new FileOutputStream(file);
            final byte[] buffer = new byte[1024];
            int size;
            while ((size = asset.read(buffer)) != -1) {
                output.write(buffer, 0, size);
            }
            asset.close();
            output.close();
        }
        mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        // This is the PdfRenderer we use to render the PDF.
        if (mFileDescriptor != null) {
            mPdfRenderer = new PdfRenderer(mFileDescriptor);
        }
    }
  • Step 2: Show a Page

Next step is to show a particular page by getting Bitmap for that page and showing in an ImageView.

/**
 * Shows the specified page of PDF to the screen.
 *
 * @param index The page index.
 */
private void showPage(int index) {
    if (mPdfRenderer.getPageCount() <= index) {
        return;
    }
    // Make sure to close the current page before opening another one.
    if (null != mCurrentPage) {
        mCurrentPage.close();
    }
    // Use `openPage` to open a specific page in PDF.
    mCurrentPage = mPdfRenderer.openPage(index);
    // Important: the destination bitmap must be ARGB (not RGB).
    Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth(), mCurrentPage.getHeight(),
            Bitmap.Config.ARGB_8888);
    // Here, we render the page onto the Bitmap.
    // To render a portion of the page, use the second and third parameter. Pass nulls to get
    // the default result.
    // Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
    mCurrentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
    // We are ready to show the Bitmap to user.
    mImageView.setImageBitmap(bitmap);
    updateUi();
}
  • Step 3: Closing PdfRenderer

This is the last step that is once your fragment or activity get killed, make sure the renderer and related objects also get released from the memory.

/**
 * Closes the {@link android.graphics.pdf.PdfRenderer} and related resources.
 *
 * @throws java.io.IOException When the PDF file cannot be closed.
 */
private void closeRenderer() throws IOException {
    if (null != mCurrentPage) {
        mCurrentPage.close();
    }
    mPdfRenderer.close();
    mFileDescriptor.close();
}

If you also want to try, Google has already created a sample for it.

I hope this will be useful to all of you for displaying a pdf document in your respective Android app. So do not forget to share this with Android developers in your circle.

 

Happy coding!

The post Android: Display PDF using PdfRenderer appeared first on OneTouchCode.com.

]]>
http://onetouchcode.com/2017/08/20/android-display-pdf-using-pdfrenderer/feed/ 0 819
Java/Android – Handling multiple date formats using DateFormat http://onetouchcode.com/2017/06/24/java-android-dateformat/ http://onetouchcode.com/2017/06/24/java-android-dateformat/#respond Sat, 24 Jun 2017 16:14:46 +0000 http://onetouchcode.com/?p=803 Know to handle Date format in Java or Android is always a life saver, as Java libraries are not very easy to use when it comes to Date or Date formats. And one of...

The post Java/Android – Handling multiple date formats using DateFormat appeared first on OneTouchCode.com.

]]>
Know to handle Date format in Java or Android is always a life saver, as Java libraries are not very easy to use when it comes to Date or Date formats. And one of the common problem all the Java or Android developers face is handling multiple date formats. So let me help you all using java.text.DateFormat

Custom DateFormat class

To handle multiple date the first step is to create a custom java.text.DateFormat class

import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Shailendra at Onetouchcode.com
 */

public class CustomDateFormat extends java.text.DateFormat {
    static final String FORMAT1 = "yyyy-MM-dd HH:mm:ss.SSS";
    static final String FORMAT2 = "yyyy-MM-dd";
    static final String FORMAT3 = "dd/MM/yyyy";

    final SimpleDateFormat sdf1 = new SimpleDateFormat(FORMAT1);
    final SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT2);
    final SimpleDateFormat sdf3 = new SimpleDateFormat(FORMAT3);

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
        int difference = source.length() - pos.getIndex();
        if (difference == FORMAT1.length()) {
            return sdf1.parse(source, pos);
        } else if (difference == FORMAT2.length()) {
            return sdf2.parse(source, pos);
        } else {
            return sdf3.parse(source, pos);
        }
    }
}

 

Date Parsing

After the creation of CustomDateFormat class within your project, next or final step is to parse the date using this class

public Date parseDate(final String dateString){ 
  CustomDateFormat cdf = new UniversalDateFormat();
  //TODO change the timezone as per your requirement.
  cdf.setTimeZone(TimeZone.getDefault());
  try {
      return udf.parse(dateString);
   } catch (ParseException e) {
       e.printStackTrace();
   }
  return null;
}

So the above class is able to handle three different date formats and if the the format is not among them the above method will return null but you can add another new format in the class and your parse methods will start supporting that newly added date format too.

That’s it.

Please share this article with your colleagues and friends.

Happy coding!!!

The post Java/Android – Handling multiple date formats using DateFormat appeared first on OneTouchCode.com.

]]>
http://onetouchcode.com/2017/06/24/java-android-dateformat/feed/ 0 803
Android – Continuous Integration with Gitlab CI http://onetouchcode.com/2017/06/11/android-continuous-integration-gitlab-ci/ http://onetouchcode.com/2017/06/11/android-continuous-integration-gitlab-ci/#respond Sun, 11 Jun 2017 10:47:58 +0000 http://onetouchcode.com/?p=794 In this article, I am going to explain basic setup for Gitlab CI integration for your Android projects. GitLab CI It is a built-in continuous integration solution by Gitlab. To do the Gitlab CI integration...

The post Android – Continuous Integration with Gitlab CI appeared first on OneTouchCode.com.

]]>
In this article, I am going to explain basic setup for Gitlab CI integration for your Android projects.

GitLab CI

It is a built-in continuous integration solution by Gitlab. To do the Gitlab CI integration first of all we need to add .gitlab-ci.yml within the project and then you have to setup this configuration file to execute your project whenever your team will push the code to master or development or any other branch to ensure your Android app compiles and passes unit and functional tests.

Read also –

Basic configuration

There is so much we can do with any continuous integration solutions available, but here I am going to show you the basic setup which just verifies whether the code is in condition to compile with no lint warnings.

image: openjdk:8-jdk

variables:
  ANDROID_COMPILE_SDK: "25"
  ANDROID_BUILD_TOOLS: "24.0.0"
  ANDROID_SDK_TOOLS: "24.4.1"

before_script:
  - echo Start CI
  - setx ANDROID_HOME  "%cd%/android-sdk"
  - setx PATH "%PATH%:%cd%/android-sdk/platform-tools/"

stages:
  - build
  - test

build:
  stage: build
  script:
    - ./gradlew assembleDebug
  artifacts:
    paths:
    - app/build/outputs/
   
# Use the generated build output to run the tests.
unitTests:
  stage: test
  script:
    - ./gradlew test
    
after_script:
  - echo End CI

Note: The path mentioned are based on Windows O.S, so if your Gitlab CI is running on Linux/Unix based system you need to change the path.

 

I hope this basic script will be helpful for you if you already using Gitlab and want to do continuous integration with Gitlab CI.

Do not forget to share this with your friends and colleagues working on Android or DevOps.

Happy coding!!!

 

The post Android – Continuous Integration with Gitlab CI appeared first on OneTouchCode.com.

]]>
http://onetouchcode.com/2017/06/11/android-continuous-integration-gitlab-ci/feed/ 0 794
Could not find class GradleWrapperMain http://onetouchcode.com/2017/06/10/gradlewrappermain/ http://onetouchcode.com/2017/06/10/gradlewrappermain/#respond Sat, 10 Jun 2017 16:41:09 +0000 http://onetouchcode.com/?p=789 If you have a Gradle project like an Android app and want to do CI(Continuous integration) with any CI platforms like Jenkins, Gitlab CI etc, then most of the time script work smoothly but sometimes...

The post Could not find class GradleWrapperMain appeared first on OneTouchCode.com.

]]>
GradleWrapperMain

If you have a Gradle project like an Android app and want to do CI(Continuous integration) with any CI platforms like Jenkins, Gitlab CI etc, then most of the time script work smoothly but sometimes it drives you like nuts. One of the common problem is –

Problem

Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain
Running after script...
End CI
ERROR: Build failed: exit status 1

 Solution

And the solution of this error is your project either doesn’t have gradle-wrapper.jar or you have missed it to add to you version control system tools like Git, Mercurial. Make sure you add the following files and directory into your project and into your version control system.

|---gradle
    |---wrapper
        |---gradle-wrapper.jar
        |---gradle-wrapper.properties

And you are done.

 

Do not forget to share it with your friends and colleagues.

Happy coding!!!

The post Could not find class GradleWrapperMain appeared first on OneTouchCode.com.

]]>
http://onetouchcode.com/2017/06/10/gradlewrappermain/feed/ 0 789
Android – android.os.FileUriExposedException and all about it http://onetouchcode.com/2017/05/24/android-android-os-fileuriexposedexception-reason/ http://onetouchcode.com/2017/05/24/android-android-os-fileuriexposedexception-reason/#respond Wed, 24 May 2017 16:35:24 +0000 http://onetouchcode.com/?p=783 If you as an Android developer working on an App and which is calling implicit Intents using a Uri, you will encounter FileUriExposedException on API 24+. This exception starts occurring if your app will run...

The post Android – android.os.FileUriExposedException and all about it appeared first on OneTouchCode.com.

]]>
If you as an Android developer working on an App and which is calling implicit Intents using a Uri, you will encounter FileUriExposedException on API 24+.

This exception starts occurring if your app will run in Android Nougat due to the fact that using file:// Uri’s are discouraged because it makes some assumptions about the destination app. For one thing, we assume that the destination app has READ_EXTERNAL_PERMISSION which may not be the case. If the destination app does not have the permission, this may result in unexpected behaviour which ends up with a crash.

android.os.fileuriexposedexception

Lets see how we can make it work –

In Android Nougat we have to use FileProvider to get rid of FileUriExposedException. Which can be done in 3 simple steps

Step 1

First of all, add the provider tag inside the application tag within AndroidManifest.xml

<application>
<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>

...
</application>

Read also –

Step 2

Once the provider get added in AndroidManifest.xml, next we need to create an xml file res/xml/provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

 Step 3

Now comes the final step that is the code change

//Old approach
 private void callIntent(File file) {
        if (file.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);            
            intent.setDataAndType(Uri.fromFile(file), getString(R.string.mimetype));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(intent);
        }
    }


//New Approach
 private void callIntent(File file) {
        if (file.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri apkURI = FileProvider.getUriForFile(
                    this, app.getPackageName() + ".provider", file);
            intent.setDataAndType(apkURI, getString(R.string.mimetype));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(intent);
        }
    }

And that’s it, you are done. If you like this, do not forget to share it with fellow Android developers

Keep on reading other articles to build great apps.

 

Happy coding!!!

The post Android – android.os.FileUriExposedException and all about it appeared first on OneTouchCode.com.

]]>
http://onetouchcode.com/2017/05/24/android-android-os-fileuriexposedexception-reason/feed/ 0 783
Google Analytics Dashboards Limitations http://onetouchcode.com/2017/04/16/google-analytics-dashboards-limitations/ http://onetouchcode.com/2017/04/16/google-analytics-dashboards-limitations/#respond Sun, 16 Apr 2017 05:04:45 +0000 http://onetouchcode.com/?p=774 In my last few articles, I have explained about basics of Google Analytics(GA) which helps anyone to setup GA account for their Android app and additionally which helps to do segmentations or custom reports . Now...

The post Google Analytics Dashboards Limitations appeared first on OneTouchCode.com.

]]>
google analytics dashboad

In my last few articles, I have explained about basics of Google Analytics(GA) which helps anyone to setup GA account for their Android app and additionally which helps to do segmentations or custom reports . Now let me explain limitations of the Google Analytics dashboards as per their support document.

Google Analytics Dashboards have the following limitations and constraints –

  • Each Analytics view can contain up to 20 private Dashboards per user.
  • Each Analytics account can contain up to 50 shared Dashboards per view.
  • Each Dashboard can contain up to 12 widgets.
  • You must have Edit permission to share Dashboards and data with the current view. Users with Read permission can still share Dashboard templates via a link or in the Solutions Gallery.

There are some limits in using linked reports –

  • When linking a report to a Dashboard, you can only embed the Data view of that report. If you try to add a report that uses another view of the table (e.g., Percentage, Performance, Comparison or Pivot), you will see a warning icon. Mouse over the icon to see the warning message. You can still add the report, but it will display only the Data view.
  • Linked reports can’t have metric filters or secondary dimensions. If you try to add a report with a metric filter or secondary dimension, you will see a warning icon. Mouse over the icon to see the warning message. You can still add the report, but it will not include the filter or secondary dimension.
  • Linked reports display only the first two metric columns from your reports. If your report contains more than two metrics, additional metrics will not be displayed in the Dashboard.

I hope this will be useful for people using Google Analytics, so do not forget to share it with your friends and colleagues.

Happy coding!!!

The post Google Analytics Dashboards Limitations appeared first on OneTouchCode.com.

]]>
http://onetouchcode.com/2017/04/16/google-analytics-dashboards-limitations/feed/ 0 774
Android – Download and save images to SD card using Picasso http://onetouchcode.com/2017/04/09/android-save-images-using-picasso/ http://onetouchcode.com/2017/04/09/android-save-images-using-picasso/#respond Sun, 09 Apr 2017 08:31:07 +0000 http://onetouchcode.com/?p=764 In my blog I always try to address pain points of developers, so does most of the naive developers face difficulty to download and save images for their respective Android apps into SD card....

The post Android – Download and save images to SD card using Picasso appeared first on OneTouchCode.com.

]]>
In my blog I always try to address pain points of developers, so does most of the naive developers face difficulty to download and save images for their respective Android apps into SD card. And they ended up writing more complicated logic and which may create other issues, for that reason only I am going to explain a simple and robust way to downloading and saving images in SD card using Picasso.

picasso

Picasso is a famous library from Square, used by developers for downloading images and displaying them but many do not know that it has capability of not only downloading but also saving those images as per individual’s requirement, let’s have a look on how one can achieve this.

Include Picasso into Gradle

First of all we need to include the library to the build.gradle file of the App module.

dependencies {
    //other libraries
    compile "com.squareup.picasso:picasso:2.4.0"
}

Use of Target

Picasso has an Interface called Target, you just need to create another class which implements this Interface and you can save the downloaded image bitmap to a file of your required location in SD Card. Here is a sample class for your reference. Once your class is ready you just need to call while downloading images.

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.File;
import java.io.FileOutputStream;

public class PhotoLoader implements Target {
    private final String name;
    private ImageView imageView;

    public PhotoLoader(String name, ImageView imageView) {
        this.name = name;
        this.imageView = imageView;
    }

    @Override
    public void onPrepareLoad(Drawable arg0) {
    }

    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + name);
        try {
            file.createNewFile();
            FileOutputStream ostream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, ostream);
            ostream.close();

            imageView.setImageBitmap(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBitmapFailed(Drawable arg0) {
    }
}

Read about other libraries from Square –

 Downloading images

Now to download the image to display you need to call Picasso class which actually downloads the images –

String url = "https://www.w3schools.com/css/trolltunga.jpg";
String imageName = "trolltunga.jpg";
Picasso.with(mContext)
                    .load(url)
                    .into(new PhotoLoader(imageName , mImageView));

As you can see I am using PhotoLoader class which implements Target Interface.

 

So it is pretty easy to download and save images in SD card using Picasso, and another good part of using it is a very small library compare to other image downloading libraries available.

I hope this article will be helpful for you, so do not forget to subscribe and if you are already subscribed then share this post to you friends and colleagues so they can also take advantage.

 

Keep coding!!!

The post Android – Download and save images to SD card using Picasso appeared first on OneTouchCode.com.

]]>
http://onetouchcode.com/2017/04/09/android-save-images-using-picasso/feed/ 0 764
Android – Sharing data from your app using Intent.ACTION_SEND http://onetouchcode.com/2017/03/30/android-sharing-data-app-intent-action_send/ http://onetouchcode.com/2017/03/30/android-sharing-data-app-intent-action_send/#respond Thu, 30 Mar 2017 17:45:15 +0000 http://onetouchcode.com/?p=753 Sharing data or content from an app to another is a common requirement but with a twist. So today I am going to discuss several type of content sharing in this article.   There...

The post Android – Sharing data from your app using Intent.ACTION_SEND appeared first on OneTouchCode.com.

]]>
Sharing data or content from an app to another is a common requirement but with a twist. So today I am going to discuss several type of content sharing in this article.

 

There are mainly three ways to share data which depends on requirement, let’s have a look –

  • Sharing to all the available apps using Intent.ACTION_SEND

    Intent.ACTION_SENDThis means your app can share content to all the available apps of an Android device those can accept your content, and to implement it you have to use the following code –

    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.setType("text/plain");
    share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    share.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
    // Add data to the intent, the receiving app will decide
    // what to do with it.
    share.putExtra(Intent.EXTRA_SUBJECT,  "Enter your title here");
    share.putExtra(Intent.EXTRA_TEXT, "Enter your description here");
    activity.startActivity(Intent.createChooser(share, "Share"));
  • Sharing to a specific app

    In some cases we only wants to share content to a specific app like Facebook, Twitter,LinkedIn etc. To achieve this use the below mentioned code –

    String packageName = "com.facebook.katana";
    String fullUrl = "https://m.facebook.com/sharer.php?u=..";
    
            Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
            if (intent == null) {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(fullUrl));
                startActivity(i);
            } else {
                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setClassName(packageName ,
                        "com.facebook.katana.ShareLinkActivity");
                sharingIntent.putExtra(Intent.EXTRA_TEXT, "your title text");
                startActivity(sharingIntent);
            }

    The above code is good to share to Facebook, Twitter or Linked like social apps, whereas if you want to share your app’s data to another app and you know the URI of the other app you can still share without mentioning the activity name using implicit intent similar to the following code –

    String packageName = "com.sample";
            Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
            if (intent == null) {
                intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id=" + packageName));
            } else {
                String url = "sample://app/uri";
                try {
                    intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

    This code will also take care if your intended app is not installed

     

     

    Read also –

  • Sharing to specific apps using Intent.ACTION_SEND

    Now this is the rarely used requirement where developer only want to show only a few set of apps to share content from their app and to achieve this you have to write little lengthy code

    List<Intent> targetShareIntents=new ArrayList<Intent>();
        Intent shareIntent=new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        List<ResolveInfo> resInfos=getPackageManager().queryIntentActivities(shareIntent, 0);
        if(!resInfos.isEmpty()){
            System.out.println("Have package");
            for(ResolveInfo resInfo : resInfos){
                String packageName=resInfo.activityInfo.packageName;
                Log.i("Package Name", packageName);
                if(packageName.contains("com.twitter.android") || packageName.contains("com.facebook.katana") || packageName.contains("com.kakao.story")){
                    Intent intent=new Intent();
                    intent.setComponent(new ComponentName(packageName, resInfo.activityInfo.name));
                    intent.setAction(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    intent.putExtra(Intent.EXTRA_TEXT, "Text");
                    intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
                    intent.setPackage(packageName);
                    targetShareIntents.add(intent);
                }
            }
            if(!targetShareIntents.isEmpty()){
                System.out.println("Have Intent");
                Intent chooserIntent=Intent.createChooser(targetShareIntents.remove(0), "Choose app to share");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetShareIntents.toArray(new Parcelable[]{}));
                startActivity(chooserIntent);
            }else{
                System.out.println("Do not Have Intent");
            }
        }

    The above code will show Facebook, Twitter, Kakao app in the intent chooser to share content.

 

I hope this article will be helpful to all of you, so do not forget to share it with your friends and colleagues.

Happy coding!!!

The post Android – Sharing data from your app using Intent.ACTION_SEND appeared first on OneTouchCode.com.

]]>
http://onetouchcode.com/2017/03/30/android-sharing-data-app-intent-action_send/feed/ 0 753