14 Tips On How To Improve Android App Performance

Users expect apps that respond quickly and consume minimal system resources. Slow, resource-intensive apps can lead to poor user experiences and high uninstall rates. To keep your users engaged and satisfied, it’s crucial to optimize your Android app performance.

In this blog post, we’ll explore the top tips and techniques to help you achieve just that.

  1. Profile Your App

Profile Your App

Before you dive into optimization, it’s essential to understand your app’s performance bottlenecks.

Use profiling tools like Android Profiler and third-party tools like Firebase Performance Monitoring to identify areas of concern.

Profiling can reveal CPU and memory usage, network latency, and more, helping you pinpoint performance issues.

  1. Minimize Network Requests

Minimize Network Requests

Excessive network requests can slow down your app and drain the user’s data plan.

Reduce API calls by implementing effective caching strategies, combining multiple requests into one, and optimizing the payload size by removing redundant data.

  1. Optimize Image Loading

Optimize Image Loading

Images are often the heaviest assets in an app. To optimize image loading, use tools like Picasso, Glide, or Fresco, which handle image caching, scaling, and decoding efficiently.

Compress images to reduce file size without sacrificing quality.

  1. Lazy Loading and Pagination

For content-heavy apps, implement lazy loading and pagination.

Load data only when it’s needed, and load it in smaller chunks to reduce the initial load time.

This technique can significantly improve the perceived app performance.

  1. Background Tasks and Threading

Offload resource-intensive tasks to background threads or worker queues to prevent the main UI thread from becoming unresponsive.

Use AsyncTask, Threads, or Kotlin Coroutines to handle background operations efficiently.

  1. Reduce Overdraw

Overdraw occurs when the Android system has to redraw the same pixel multiple times in a single frame.

Minimize overdraw by using the Hierarchy Viewer tool to inspect your app’s view hierarchy and reduce unnecessary layers.

  1. Optimize Memory Usage

Memory leaks can lead to app crashes and degraded performance. Use tools like Leak Canary to detect and fix memory leaks.

Additionally, release resources (e.g., bitmaps, cursors) when they are no longer needed and implement a smart caching strategy.

  1. Proguard and Code Shrinking

Use Proguard to obfuscate and shrink your app’s code. This reduces the APK size and improves startup performance.

Code shrinking tools like R8 further optimize your app’s bytecode.

  1. Enable Hardware Acceleration

Leverage hardware acceleration for graphics-intensive tasks by setting the android:hardwareAccelerated attribute to “true” in your app’s manifest.

This offloads rendering tasks to the GPU, improving performance.

  1. Keep Up with Android Updates

Stay up-to-date with the latest Android SDK versions and platform updates.

Google continuously optimizes the OS, and using the latest tools and features can improve your app’s performance and compatibility.

  1. Test on Real Devices

Don’t rely solely on emulators for testing. Real devices can behave differently due to variations in hardware and software.

Regularly test your app on a range of devices to ensure optimal performance across the board.

  1. Optimize UI Rendering

Minimize the number of views and layouts in your UI hierarchy. Use Constraint Layout to create efficient and flexible layouts.

Avoid nested layouts whenever possible, as they can lead to slower rendering times.

  1. Implement App Bundles

Migrate to the App Bundle format for publishing your app.

This format allows Google Play to deliver optimized APKs tailored to each user’s device configuration, reducing unnecessary bloat.

  1. Monitor and Iterate

After implementing these performance optimizations, continue monitoring your app’s performance using profiling tools and user feedback.

Be ready to iterate and make further improvements as necessary to keep your app running smoothly.

Top 10 Technologies For Android App Development

Android app development has evolved significantly over the years, and developers now have access to a wide range of technologies and tools to create powerful and feature-rich apps.

Here are the top 10 technologies for Android app development:

Java:

Java has been a traditional and widely used programming language for app development.

It provides a robust, versatile, and mature platform for building Android apps.

Kotlin:

Kotlin is the official programming language for app development recommended by Google.

It offers concise syntax, enhanced safety features, and excellent interoperability with Java.

Android Studio:

Android Studio is the official integrated development environment (IDE) for Android app development.

It provides a comprehensive set of tools, including code editors, debugging, testing, and performance profiling.

XML:

XML (Extensible Markup Language) is used extensively for defining layouts and UI elements in Android app development.

It allows developers to create user interfaces that adapt to different screen sizes and orientations.

Gradle:

Gradle is the build automation tool used in Android Studio. It simplifies the build process, manages dependencies, and allows for customizations through build.gradle files.

Android Jetpack:

Android Jetpack is a collection of libraries, tools, and architectural guidance provided by Google to simplify app development.

Are you looking for a Android developer

Contact Us

It includes components for navigation, UI, database management, and more.

Retrofit:

Retrofit is a popular HTTP client library for Android that simplifies network requests.

It supports various data formats, such as JSON and XML, and provides an easy-to-use API for making RESTful API calls.

Room Database:

Room is an Android architecture component that provides an abstraction layer over SQLite databases.

It simplifies database operations and ensures data consistency and security.

Firebase:

Firebase is a comprehensive mobile and web application development platform by Google.

It offers various services, including real-time database, authentication, cloud storage, and analytics, which can be integrated into Android apps.

Flutter:

While primarily associated with iOS app development, Flutter is gaining popularity in the Android app development world.

It’s a UI toolkit from Google for building natively compiled applications for mobile, web, and desktop from a single codebase.

Conclusion

Optimizing Android app performance is an ongoing process that requires vigilance and dedication.

By following these tips and techniques, you can create a snappy and responsive app that delights users and keeps them engaged for the long term.

Remember that a fast and efficient app is more likely to garner positive reviews and high user retention rates.

FAQs

What is Material Design in Android app development?

Material Design is a design language developed by Google that emphasizes visual and motion design principles. It provides a consistent and visually pleasing user experience across Android apps, focusing on responsive layouts, smooth animations, and intuitive navigation.

What is the Android API level, and why is it important?

The Android API level represents the version of the Android operating system that an app is compatible with. It’s essential to set the minimum API level in your app’s manifest file to ensure compatibility with a wide range of devices.

How can I publish my Android app on the Google Play Store?

To publish your Android app on the Google Play Store, you need to create a Google Play Developer account, prepare your app for release, generate a signed APK, and complete the submission process by providing app details, screenshots, and pricing information.

What is the difference between Android Studio and Eclipse for app development?

Android Studio is the official integrated development environment (IDE) recommended by Google for Android app development. Eclipse was previously used but is no longer officially supported.

Android Studio offers a more robust and feature-rich development environment.

What is the Android SDK?

The Android Software Development Kit (SDK) is a collection of software tools and libraries provided by Google to facilitate Android app development. It includes APIs, debugging tools, and emulator images for various Android versions.

Major Android Features to Enhance Your App Development

After much speculation, finally, Android 11 made its debut on September 8th, 2020, and the whole Android application world is going gaga over it.

Undoubtedly, the Android 10 operating system witnessed a great deal of success in the past. The most common and highly acceptable platform Android constantly improves the functionalities and user-experience every single year.

This time around, Android 11 is making headlines everywhere owing to its advanced features, seamless integration with multiple devices, and commendable performance.

The latest version Android 11 has impact Android application development services giving a new path of success to developers and proficiency to users.

Never miss an update from us. Join 10,000+ marketers and leaders.

In this blog post, we will look at the major android features to enhance your app development.

Let’s get started.

Major Highlights Of Android 11 Operating System

1. Chat Bubbles

Chat Bubble did not make any impact in the earlier version of Android 10 and got faded away in the background. But the Android 11 version is all about improving communication and notifications.

If you have ever used a Facebook Messenger on Android, then you must know what we are talking about.

Just like in Facebook Messenger, you see a conversation floats like a bubble on your smartphone screen, you tap it to send replies or read the message, or can close the icon as well.

Similarly, the Chat Bubble feature is now available with all the communication apps in Android 11. It allows users to do other tasks on the device and see a chat bubble appears if anyone sent you a message or receive a notification.

2. One Time Permission

Google has introduced several privacy settings in Android 11 including the One-Time Permission feature. It allows users to install an application and provide accessibility in just one tap.

Earlier, when you installed a mobile app, you have to permit access to your media, location, camera, and more.

Now, with the newly launched feature of One-time permission, you can allow access only one time and have more control over the privacy settings.

3. Notification Control

For the first time, Android’s latest operating system Android 11 comes packed with the feature of three notification categories including Conversation, Alerting, and Silence.

While the latter two were already available in Android 10, but the new version offers major improvements in them.

Conversation notification allows you to see all the chat notifications on the screen including chat apps, text messages, and Instagram. On the other side, you can silence notifications with the Silent feature.

4. 5G Support

5G network support has already made a blast in the marketplace. A lot of brands offer foldable devices fully incorporated with a high-speed 5G network.

Thus, to match the pace of higher speed and efficient connectivity, Android 11 also supports 5G for video streaming, network accessing, and data sharing.

You can all for this new update along with Android application development services.

5. Built-In Screen Recorder

There is no need to download a third-party app to record the screen functionalities. The new Android 11 comes with in-built screen recorders that allow users to drag and drop the feature to record the screen with utter ease and comfort.

It also features an in-built audio recording without connecting your mic to record the sound simultaneously.

6. Smart Controls

Smart Home controls have changed the concept of managing devices to control temperature, switch on/off lights, and other operations.

For accessing the same, you have to install a Smart Home application to control electrical devices.

Android 11 brings new advancements in such technology. In this, you will find an in-built app to add home services and have full control over the same.

You can add up to 6 devices like lights, air condition, smart-TV, security cameras, smart doors, and more.

7. Dark Theme Scheduling

The earlier version of Android 10 made an impact with its Dark Theme feature to enable the dark mode manually.

Android 11 appears with the advanced feature of selecting two different metrics to enable/disable the dark screen mode. It could be during selected hours of usage or sunrise/sunset as per your requirements.

8. Better Media Controls

An Android user had to switch to different audio modes for listening to the favored choice of music. Sometimes, you select the Bluetooth device mode, in-built speaker, or Smart-TV inputs for listening to the desired choice of songs.

Now, Android 11 does create such a ruckus of switching to different audio modes. The new operating system lets you select the mode from the notification section itself without enabling or disabling the mode from the application itself.

9. Live Location Using Pixel

Sharing one’s location eases up the burden of finding ways and directions to reach your friend/relative or any person. But how about you see the real picture of that shared location?

It will be beneficial for users to locate the area using the location shared coordinates and picture.

In Android 11, the pixel does the commendable job of sharing live location along with the exact pace to respective respondents.

10. Privacy for Enterprise Usage

If you have received a separate smartphone from the office for official use only, then you must know its limitations to commercial usage only.

Generally, enterprise IT guy has a close eye on such enterprise devices to track locations, usage, issues, and updates. Thus, one has to carry a personal device also for regular usage.

I’ve worked with the team at Andolasoft on multiple websites. They are professional, responsive, & easy to work with. I’ve had great experiences & would recommend their services to anyone.

Ruthie Miller, Sr. Mktg. Specialist

Salesforce, Houston, Texas

LEARN MORE

Now with Android 11 comes into place, there is no need to carry two devices at a time. Android smartphones endowed with the new operating system features a personal profile and work profile mode.

You can switch to any mode for the desired usage without having any effect on the other mode.

It brings comfort to carry a single device only having accessibility to both personal and official information.

Wrapping Up

Experience a new and advanced mobile application user experience with Android 11 that is the 18th version of Android. It is the future of enterprise applications endowed with innovative features and functionalities.

If you are thinking to develop Android 11 powered apps for business then hire android app developer and jump-start your enterprise development process.

How AI Can Bring a Modern Revolution in Mobile App Development

The emerging technology like Virtual Reality (VR), Augmented Reality (AR), IoT, and Artificial Intelligence have been covering up for the marketing next-generation mobility elucidation.

Out of all these technologies, AI has found a separate place on mobile application development because of the increasing popularity of mobile app users around the globe.

And the trend to integrate this popular feature in the business app has been emerging among entrepreneurs on the global market as well.

So let’s see what actually AI is and the role in your business mobile app?

Defining AI could sound a little more technical to you. On a simpler note, AI is an aspect of computer science that focuses on the development of intelligent machines that could perform like the human brain.

Such as creating & performing tasks and resolve to the inputs while learning from users’ experiences.

And when it comes to mobile app developments, AI includes certain traits such as; ability to manipulate and move the objectives, solve problems, enhance perception, and artificial knowledge.

The Impact at Business Industries:

These days the smart entrepreneurs are enthusiastic about AI when they have to judge the integration of smart interfaces and devices to achieve their business growth.

AI can imitator to human behavior or experiences by gathering different data and then performed by means of decode it. And it can continue to add and create more values with better knowledge as well as a faster and spontaneous business process.

Concerning to the user demand, the flexibility and adaptability can be address by AI-based apps considering their various aspects.

In a similar fashion, the demand for fulfilling the personalized experience has been increasing which can be drive through AI technology.

Users can expect more personalized and predictive experience through an AI-based application.

So, it is very definite, the AI factor that can take the mobile use and development process to the next level.

Let’s see what AI elements can make differences in your app:

  • Face Detection

This AI technology can be used in various applications as a safety measure. It is about identifying the user as suggest to the name digitally.

This face detection can be used as a mandatory surveillance purpose and monitoring the movement of the user. Both Android and iOS devices support this technology and you just need to add this feature to your business apps.Face Detection - How AI Can Bring a Modern Revolution in Mobile App Development

  • Text Recognition

This technology can be performed on two processes: The first one is text detection which can be executed from media images and video files. And the second one is recognizing the text.

The AI technology splits the texts into different fragments to recognize the text accordingly.

This is an ultramodern technology with having a lot of potentials for modern business and can be incorporate with mobile apps as a supplementary feature.

  • AI Chatbot

The Chatbot is known as the most innovative perception of a modern business application. The AI elements can make smart communication with the real audience, assemble the data, and offer better customer services to the users.

This technology can be executed as a 24*7 customer support executive on your business app. The integration of chatbot has become a major part of the aspect of the modern mobile app.

  • Image & Voice recognition

For image & voice recognition tasks, the use of an artificial intelligence algorithm is needed. To doing so, the technical process can be capable of providing a better result alike human brain.

Implementing the conventional AI technologies like Google Cloud Vision, and IBM Watson Visual Recognition can provide outstanding recognition results through your business apps.

  • Landmark / Object Detection

Landmark or object detection is a feature associated with finding the particular position defined by the specialist in an exacting researched domain.

Usually, the landmark detection is a preliminary part of a main and composite research process.

  • Smart Reply

Let’s start with a real-time example. GMAIL, it has one of the most user-friendly features as Smart Reply. The variants have successfully featuring worldwide by combining with AI technology to provide a richer and personalized user experience.

The same AI-based feature can be integrated at your business apps for digital communication.

  • Personalization

A loyal customer can be gained with the help of personal experience. AI technology offers projecting analytics, based on user choice and behaviors that enable the system to show the recommendation in a personalized way.

This personalization method can help to improve the customers’ experience to remain connected with your business service through the mobile app.

The AI-based app personalization has become a certain aspect in modern app development demand.

Conclusion:

From last few years, there is an overwhelming increase in popularity in the use of Artificial Intelligence in various fields of business, industries as well as users.

So, it is fair to reveal that AI is the future of mobile app integration and development. App development agency and many experts are forecasting, this technology will grow rapidly and will offer more benefits to the user.

Want to Know More about AI Integration? Talk to our Experts!

How Android Apps Are Beneficial For Entrepreneurs?

More than 2.5 billion smartphones are being used. But the interesting fact is Android remains an unchallenged winner in the smartphone market world.

You may ask, do we really care? Well, the answer is “Yes, we do…

That’s because, for every Android and iOS users, it is like ‘if you have a task to do, you have an app’. That’s why Google Play loads with more than 2.6 million apps.

Every year, Google comes up with a new and updated version of the Android platform with the latest features that are useful for both entrepreneurs and individuals.

When the entrepreneur comes to the point of developing a custom mobile app for their businesses, most of them prefer the Android operating system.

And the reasons are many like high scalability, flexibility, and capacity to address a large number of the audience all over the world.

Here, I’d like to mention some of the top signs that show the importance of Android apps in our digital lives and how they have transferred the way in our business doing.

Use of Android Apps in Our Everyday Life:

1. Improves Collaboration and Communication:

Tell me honestly, can you live without social media? Not exactly.

Today, social media has taken such a place that it became hard to imagine the world without it.

Everyone wants to stay connected with their family, relatives, and friends through social networks, and luckily Android apps enable people to do so.

On the other hand, android apps help us to connect and communicate with other people in an advanced and efficient way. Ultimately, it’s putting a huge impact on our business and daily life.

2. Shares Fun and Entertainment:

Google play has many categories for updating our lifestyle. Also, it has an abundance of apps that offer a lot of fun and happiness. Different gaming apps are attracting and engaging people of all age groups.

Let’s take PUBG (Play Unknown’s Battleground) as an example. I don’t need to explain, you guys know about it, right!

It’s engaging youngsters in a huge amount. All most everyone is now playing this game.

For entrepreneurs, different teamwork or strategy games are also there which help to engage employees effectively.

3. Manages Daily Tasks Easily:

It is easy to maintain pending tasks’ order with apps. Utility apps help you to manage and accomplish daily activities.

From fixing an appointment to arrange a meeting, booking a movie ticket to getting recipes, everything is just at your fingertips.

Many professional and personal apps are proven useful in our life.

4. Brings Automation:

Those days are gone where you have to stand in a long queue to book a ticket, or pay bills. Customized and updated Android apps can do these things instantly and securely.

Various mobile wallet apps are available which offers a secure and instant option to pay bills. It has spread to sectors like banking, healthcare, and retail and offers convenience to people.

There are no limitations in the offerings of Android apps. All I can say that enhanced comfort has made us more dependent on it.

From research, it has found that more than 46% of business people are using Android OS for their mobile app development. Here’s a pictorial representation on the same;

Smartphone OS UsersImage Source: Zdnet.com

Despite our daily lifestyle, it has also some major impacts on our work life as well. Let’s find out what are the reasons behind the Android app’s popularity in the business world.

How Android App Development Is Beneficial To Businesses?

As an entrepreneur, you must capitalize on those platforms where users get constant engagement.

Let’s find out the benefits of bringing your business to the Android platform.

1. Massive Audience:

You can find Pro-Android users everywhere in the world. Now, when it’s about business, these Android users became a huge audience to promote products and services.

It has become easy to build and improve brand promotion with the Android app as it helps you to reach a wide audience with ease.

In this competitive world, no one can afford to skip the Android platform for simplifying business processes and enhancing customer services.

2. Adaptability:

When you have decided to use a customized mobile app solution using Android for your business, you keep ensuring to integrate technological improvements to meet different business needs.

3. Time to Market (TTM):

One of the biggest pros of Android apps is, it can be built quickly if you’re ready with the basic features.

In the beginning, businesses can bring an app with the most required features and simultaneously add more features to that app to save time and money.

In this instance, reduced Time to Market (TTM) is a supreme advantage of Android app development for the business.

It can give an extract mileage to the companies in progress and an edge over other companies that have no mobile apps yet.

4. Customization:

Today, businesses have diverse requirements as they are multidimensional.

It is mandatory for them to meet the requirements along with the customer’s demand. At this stage, customization in app development can play a major role.

It becomes easy to add features and necessary functionalities in the Android apps.

The scalability and open-source nature also help the app developers to meet corporate needs. In short, easy customization assists business to keep their apps updated and user-friendly.

5. And It’s a Wrap:

Just like other mobile platforms, Android apps can be deployed in different ways. You don’t need to rely on a single platform to spread your applications.

With your choice of promotional strategy, you can reach your end users through multiple channels.

Hence, it is fair to say that Android apps have brought revolutionary changes in our personal as well as professional life.

You can hire Android application developers to make the most out of it and grow your business beyond borders.

In this competing market, Andolasoft has been providing the best quality Android app development services to its clients all over the world.

It offers the sophisticated Android app solutions that are capable of taking your business to the next level and a competitive edge over your peers.

Looking to reach the Digital Audience through Android Apps? Let’s Discuss!

Things You Should Know Before Planning Your Mobile App-Part-I

When you are looking at all the popular apps, you too are tempted to have one of your own; however, it can’t be done overnight. It is because; there are thousands of mobile app programmers and companies who may be thinking of doing the very much similar things. To have a successful mobile app it takes lots of hard work and well defined requirements.  You need to think about the main development aspects before planning to go for your mobile app.

Basic Steps You Need to Know For Developing Mobile App:

From our experiences, here are some guidelines you must go through if you are planning to develop a successful mobile app:

  1. The most crucial step is to come up with an innovative idea. Here, you need to make sure that there is little or no competition for it.
  2. Identify your targeted audience and build your app form their perspective, something that is more likely to be appreciated by these users.
  3.  Judge and determine major pain points and challenges that you expect to face for your application. You should hire a dedicated development team who could understand your specific business requirements and turn your ideas into a working app.
  4. Make sure that your app provides good usability and practical values to the users i.e., they should find your app useful and productive.
  5. Your app should have a solid built with no loose ends. Make sure to run a vigorous crash test and beta test phase before actually publishing it. User experience must be intuitive as well as engaging. If you are willing to implement APIs, ensure that it is robust and doesn’t generate any glitches in the application.
  6. After publishing your app to the application stores, you need to start promoting and market your application. One of the best ways to reach a wider audience is by promoting it over social media. Next, you will have to avail as much positive feedback from users as possible.
  7. You should offer constant support to your customers by addressing their comments, expectations and complaints. Then you should release updates and new features for your app to woo your existing customers as well as attracting the attention of new ones.
  8. Offering basic features for free and then selling premium stuff is a popular way to keep users hooked up and to gain traction. Also make sure that the app is noticed and favored by your customer.

iOS application development and Android app development can be easily executed and managed with the help of expertise mobile app developers. Moreover, it is advisable to outsource mobile application development tasks to development companies. Hiring a professional development company would facilitate you to build flawless and unique mobile apps which would greatly leverage revenue.

How to show Captured Images dynamically in “GridView” Layout

There are numerous camera apps in the market which displays shopping items (i.e. image view). In these camera apps we need to arrange each photo items in a list view, basically a ‘Grid View’.

In such cases, ‘table layout’ would be easier to use; but it is difficult to arrange large number of items in

gridview_sample-253x300

side scroll view. As ‘table view’ is just a layout manager, it doesn’t allow direct interaction with each item to the users.

In order to tackle such development issues, it would be smart to implement ‘Grid View’ Layout.

What is “Grid View” Layout?

Grid View (android.widget.Grid View) is a layout that is implemented to show two-dimensional view with scrollable structure.

With the help of ‘List’ adapter, we can add images dynamically to a ‘Grid View’ layout by customizing the number of columns.

Let me tell you the process to show your Android Smartphone captured images dynamically in “Grid View” layout with some example.

Example of Layout xml

[sourcecode]<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<RelativeLayout
android:id="@+id/RelativeGridLayout"
android:layout_width="wrap_content"
android:layout_height="fill_parent" >

<GridView
android:id="@+id/gridviewimg"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:numColumns="2"
android:scrollbarStyle="outsideInset"
android:smoothScrollbar="true"
android:verticalSpacing="10dp"
android:paddingBottom="50dp"
android:paddingTop="10dp"
/>
</RelativeLayout>

<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_alignBottom="@+id/RelativeGridLayout"
>

<Button
android:id="@+id/capture_btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Camera" />
</RelativeLayout>

</RelativeLayout>[/sourcecode]

Example of Main form Activity class

1.MainActivity.java

[sourcecode]package com.example.gridviewimagesdemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

Button captureBtn = null;
final int CAMERA_CAPTURE = 1;
private Uri picUri;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private GridView grid;
private  List<String> listOfImagesPath;

public static final String GridViewDemo_ImagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GridViewDemo/";

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

captureBtn = (Button)findViewById(R.id.capture_btn1);
captureBtn.setOnClickListener(this);
grid = ( GridView) findViewById(R.id.gridviewimg);

listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.capture_btn1) {

try {
//use standard intent to capture an image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch(ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Whoops – your device doesn’t support capturing images!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
//user is returning from capturing an image using the camera
if(requestCode == CAMERA_CAPTURE){
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
String imgcurTime = dateFormat.format(new Date());
File imageDirectory = new File(GridViewDemo_ImagePath);
imageDirectory.mkdirs();
String _path = GridViewDemo_ImagePath + imgcurTime+".jpg";
try {
FileOutputStream out = new FileOutputStream(_path);
thePic.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (FileNotFoundException e) {
e.getMessage();
} catch (IOException e) {
e.printStackTrace();
}
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
}
}
}

private List<String> RetriveCapturedImagePath() {
List<String> tFileList = new ArrayList<String>();
File f = new File(GridViewDemo_ImagePath);
if (f.exists()) {
File[] files=f.listFiles();
Arrays.sort(files);

for(int i=0; i<files.length; i++){
File file = files[i];
if(file.isDirectory())
continue;
tFileList.add(file.getPath());
}
}
return tFileList;
}

public class ImageListAdapter extends BaseAdapter
{
private Context context;
private List<String> imgPic;
public ImageListAdapter(Context c, List<String> thePic)
{
context = c;
imgPic = thePic;
}
public int getCount() {
if(imgPic != null)
return imgPic.size();
else
return 0;
}

//—returns the ID of an item—
public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

//—returns an ImageView view—
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
BitmapFactory.Options bfOptions=new BitmapFactory.Options();
bfOptions.inDither=false;                     //Disable Dithering mode
bfOptions.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage=new byte[32 * 1024];
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
FileInputStream fs = null;
Bitmap bm;
try {
fs = new FileInputStream(new File(imgPic.get(position).toString()));

if(fs!=null) {
bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
imageView.setImageBitmap(bm);
imageView.setId(position);
imageView.setLayoutParams(new GridView.LayoutParams(200, 160));
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fs!=null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageView;
}
}
}[/sourcecode]

Example of Manifest.xml file content:

Example of AndroidManifest.xml

[sourcecode]<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gridviewimagesdemo"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />

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

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

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

</manifest>[/sourcecode]

Conclusion:

So, a ‘Grid view’ implementation would result in following features and benefits:

  • In ‘GridView’ layout items would be listed in a static grid, defined in layout xml file.
  • ‘Gridview’ extends android.widget.Adapter, so it could be used where large amount of data is managed in a single page frame.
  • Enhanced data source binding capabilities (Direct interaction with SQLite Data Source)
  • Built-in support for sorting and paging mechanism
  • Additional Column types (ImageField)

I would like to recommend you to go through my previous article on where I have clearly narrate the process to display your iPhone captured images in Grid View layout.

I hope you find this useful. If you want to develop android or iPhone mobile app for you or for your organization, then you can hire single or group of developers from the pool of skilled and accomplished android specialists. Drop me a line below with your thoughts, thanks.