Archive for the ‘Android’ Category

A Guide to Outsourcing Mobile App Development

Outsourcing your mobile development project to a third party is an important decision.  It is dependent on many things and varies according to the situations. Though there are many options for outsourcing your work, but you need to decide which one is best for your business. This guide will give you a good idea about whom should you outsource your business. You need to take many things into consideration including manpower, resources, budget, etc. At the end of this article, you will have a fair idea about which option you will be choosing for your future mobile app development. Top-Emerging-Trends-in-Mobile-App-Development

Let us have a look at the options for outsourcing-

#1 Boutique Mobile App Development Firms

Image result for mobile app development Boutique mobile app development firms are not included in the technology giants. While they have the best services to offer, they are not set-up on the big scale. These firms specifically focus on mobile app development. They don’t keep it as a secondary product. They have strong technical capabilities and specialized platform knowledge. Though these companies are not as big as the business tycoons, but they vary as per different aspects. It includes technical expertise, resources, technology, project complexity, team size, etc. Such companies have the best to offer according to your budget.

#2 Big App Development Firms

Image result for mobile app development They are the basic technology giants. They have different domains under one string. Mobile app development is usually one of their products. While these companies are highly capable, but they lack at certain points. They have thousands of clients working with them due to which the small clients get less leverage over the big one.

#3 Independent or Freelance developers

Image result for mobile app development Let us keep the companies aside, and talk about the freelancers. Freelancers are probably the ones who are already working in a company but work part time to make extra money. Even though you will have the whole attention of the person, but there is a possibility of not getting the best returns. They are comparatively less expensive. Image result for mobile app development

Which one is right for you?

Outsourcing app development work is a decision that needs to be made according to the organizational goals and requirement of the project. Successfully determining these two things will help you to eliminate many options early in the process. After which you need to concentrate on the risk factor, time period, budget, and customization. And deciding these things will dissolve the other half of your search process. Once your company is able to determine the best route, you can begin researching and narrowing down the best vendor options.

Current Trends for Android App Development

Smartphones are ruling the market today. According to research, the number of smartphones users will be growing from 1.5 billion to 2.5 billion in 2019. And this is the reason why the Android market is growing rapidly. There are new trends in the market every day. Let us check out the key trends of Android app development that will define how the market is changing-

#1 Web Apps + AMP

Image result for web amp Google launched Progressive Web Apps Accelerated Mobile Pages (AMP) in 2016. Web Apps are designed to open a mobile app in the browser without downloading the app. Everything is same in web apps and mobile app except it allows you to use the same app in the browser. And these web apps are developed using AMP project’s principals. AMP is an open source platform that allows one to create faster, easy to load, and high performing web apps.

#2 Augmented Reality and Virtual Reality Apps

Image result for augmented and virtual reality AR and VR apps have not created a log of buzz in 2016, but they got highly popular worldwide at the end. Augmented Reality is a technology that generates a composite view by imposing computer-generated images on user’s view of the real world. You can take the example of Pokemon Go. Another type of app that got popular in 2016 was Virtual Reality (VR) apps. These apps are a simulation of three-dimensional images that a person can interact with real-time using special electronic gadgets. Example Samsung gear, google cardboard, etc.

#3 Mobile Finance Service (MFS) Apps

Image result for mobile financial services paytm mobikwik Well, these are the easiest ones to understand. These apps have an exponential grow recently. Examples of MFS apps are PayTm, Mobiwiki, PayUmoney, etc. People prefer to use cashless transactions nowadays, and they are using mobile apps instead.

#4 Security Factor in Apps

Image result for mobile security apps There are millions of Android apps, and over 75 percent of them do not even pass security tests. These apps are easily accessible by the hackers. And Android app development companies are focusing on improving the security feature of the app. Also, many antivirus apps have come in the market like Avast, McAfee, AVG, 360 security, etc.
So, these are some of the major trends which are ruling the Android app development market in 2017. Apart from this, there are many wearable devices like Fitbit, Apple, Watch, etc.  that will rule the market.  

Kotlin- The Next-Gen Android App Development Language

Android app development is a major part of today’s technical and economical world. People use different languages for developing apps, though Java remains the most used language to develop logic. While running a Java application, the app is compiled into a set of instructions called Bytecode and runs in a virtual machine. In last few years, new programming languages have been introduced which also run on Java virtual machine. The reason behind using these languages is that the resulting app looks same for the virtual machine with simple code and some fixes that developers face while coding in Java. Image result for kotlin   Recently, one such language is introduced by JetBrains, known for IntelliJ IDEA (Android Studio is based on IntelliJ), called Kotlin. It is a statically typed programming language that runs on the JVM. It can be compiled to JavaScript source code. It has many other amazing features, and we will be knowing about them in this article.

Why Kotlin instead of any other language?

Since Java is the only language most of the people use while developing the mobile apps, developers had no actual alternatives to Java app. Java comes with a lot of historical baggage and some issues. Java 8 solved some of those problems, and some were corrected in Java 10. But these two options also have loopholes. One of them is in order to use these two versions, one must have the minimum SDK to Android 24 to use Java 8 which is not an option for many developers. And Java 10 is even far from their reach. So, Kotlin was made to fill these gaps through model language. There are some core principles that Kotlin work with-
  1. Concise- Reduce amount of boilerplate code
  2. Safe- Avoid entire classes of error such as null pointer
  3. Smart- Make your code more readable and understandable
  4. Tool-friendly- One can choose any Java IDE or build from the command line
  5. Interoperable- Leverage existing frameworks and libraries of JVM, Android, and browser.

How to work on Kotlin?

Download the starter project. Extract and open the starter project in Android Studio. It is a simple app that allows users to search for books, book covers and share books with friends to explore Kotlin. Image result for kotlin vs java

It consist of three source code files, let us check it out-

MainActivity.java- an activity that displays the screen for searching and displaying a list of books. DetailActivity.java- an Activity that displays the book cover for the ID passed to it. JSONAdapter.java- a custom BaseAdapter that transforms a JSON object into a listview item. Build and run the project to see what you’re working with.

How to set up the environment of Kotlin?

Android Studio doesn’t have any idea of what to do with Kotlin. So the first thing you need to do is to install the Kotlin plugin and configure Kotlin in your project.

-Installing the Plugin

1. Go to Android Studio/ Preferences and Select the Plugins entry. kotlin for android 32. Click on Install JetBrains plugin on Plugins screen intro_to_kotlin_4 3. Search and select Kotlin from the list and click Install. intro_to_kotlin_5 4. When you are done with downloading and installing Kotlin, then you need to follow the prompts to restart the IDE. intro_to_kotlin_28

– Configure Kotlin in Project

Now the IDE knows what to do with Kotline, but your project app doesn’t, so you have to modify the project’s build configuration. How do modify the project’s build configuration? Let us check out- 1. Go to Tools-> Kotlin-> Configure Koltin in Project intro_to_kotlin_7 2. A Choose Configurator pop up will appear, select Android with Gradle from the drop down. intro_to_kotlin_8 3. On Configure Kotlin in Project popup, select the plugin version you want to use and click OK. Configure Kotlin in Project 4. These actions will make some changes to your build.gradle files.   build.gradle (Project: omg-android-starter): buildscript {  ext.kotlin_version = ‘1.0.3’ // 1  repositories {    jcenter()  }  dependencies {    classpath ‘com.android.tools.build:gradle:2.1.3′    classpath “org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version // 2    // NOTE: Do not place your application dependencies here; they belong    // in the individual module build.gradle files  } } allprojects {  repositories {    jcenter()  } } build.gradle (Module: OMG Android):    apply plugin: ‘com.android.application’ apply plugin: ‘kotlin-android’ // 3 android {    compileSdkVersion 23    buildToolsVersion “24.0.2”    defaultConfig {        minSdkVersion 14        targetSdkVersion 23    }  sourceSets {    main.java.srcDirs += ‘src/main/kotlin’ // 4  } } dependencies {  compile ‘com.android.support:appcompat-v7:23.2.0′  compile ‘com.loopj.android:android-async-http:1.4.4′  compile ‘com.squareup.picasso:picasso:2.1.1′  compile “org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version // 5 } repositories {  mavenCentral() }   Here is a summary of what this code is about-  
  1. Declares configured Kotlin version
  2. Declares classpath dependency artifact that contains the Kotlin Gradle plugin with the version declared earlier
  3. Specifies the use of Kotlin Android plugin via apply plugin command
  4. Defines that source files found in src/main/Kotlin will be compiled. Gradle will compile source Kotlin files found in src/main/java.
  5. Added the Kotlin Standard library as a compile-time dependency to the project.
    Click on Sync Now to build a project and run it! intro_to_kotlin_25 Nothing changed visually here, it just made your work bit easier!

Here are 10 reason why Kotlin is cool-

Image result for kotlin
  1. Kotlin is open source
  2. Full Java Interoperability
  3. Kotlin compiles to JVM bytecode or JS
  4. Data Classes in Kotlin
  5. Defaulted parameters
  6. Kotlin imposes no runtime overhead
  7. Null Safety in Kotlin
  8. Extension functions
  9. Swift is like Kotlin
  10. Kotlin wants you to write less code
Inputs & Source

The technology stack powering the on demand applications

Uber and Ola have given rise to a slew of Ondemand applications which claim themselves to be Uber/Ola of X. Some of the verticals where these applications have found their usability include but not limited to taxi, transportation, Logistics, Home Services, Health apps and so on. In this blog we will go deeper into the various components and technology involved in on Demand Apps. Components Involved in Building and On Demand App In most of the cases there are 3 components involved in building an On-Demand App:
  • A cloud backend for Data Interaction APIs and live dispatch of Jobs
  • An Android/iOS App user to make a job(e.g book a ride with Uber/Ola)
  • An app with the drivers to receive the jobs created by the users and attend to them.
  Lets analyze each of these components in detail and how one can go around building each of them. Web Backend Web Backend is the most critical part of the On Demand applications because backend is what powers both the consumer and the driver apps. The web backend must meet the following requirements for a successful implementation:
  • A Light footprint to dispatch the jobs on fly.
  • A Good dispatch components to maximize the efficiency of the field workers(drivers in case of uber).
  • A Socket connectivity to enable the jobs dispatch and job information to the user.
  • A Good structure for a flexible and structured development
  We have recently worked on Bodhik which is an Ondemand Application for Financial Advisory Services.

Streaming Videos in an Android Application

The blog details on how we can stream videos in an android application. There are basically two parts two parts to the problem:
  1. A streaming server like adobe flash media which can deliver a video stream
  2. Playing the video progressively in your android application with help of a video player
The blog assumes that you already have a file uploaded at some place from where the player can pick up the file to play. The simple and the easiest solution is to use the android VideoView but the problem with the VideoView is it requires the whole file to be downloaded before starts playing. It can be very annoying to serve the videos like this in a real time production application. If however, you are happy with this behavior, you can skip the rest of the blog. Vitamio player Vitamio for android is an android library with a VideoView similar to android’s native VideoView. Vitamio’s VideoView can be used to play or stream the videos. To integrate vitamio,  its library for android needs to be included in the android project. The library is available at the following URL: https://github.com/yixia/VitamioBundle Using Vitamio with an existing Android project After downloading the Vitamio bundle add it into your android project as library. We will now start to build a simple Vitamio VideoView to play the videos Layout In layout xml file add the following lines to add videoView

<io.vov.vitamio.widget.VideoView
 android:id="@+id/video_view"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >

Activity In your activity file import vitamio’s videoView (io.vov.vitamio.widget.VideoView) instead of android native VideoView (android.widget.VideoView). The following sample code demonstrates how you can create a VideoView to stream a video within the Vitamio VideoView.

VideoView mVideoView = (VideoView)findViewById(R.id.video_view);

 //Setting video path(url)
 videoView = mVideoView.setVideoPath(“<Video url>”);

 //Setting main focus on video view
 mVideoView.requestFocus();
 mVideoView.start();

 //Initializing the video player’s media controller.
 MediaController controller = new MediaController(this);

 //Binding media controller with VideoView

 mVideoView.setMediaController(controller);

 //Registering a callback to be invoked when the media file is loaded and ready to go.
 mVideoView.setOnPreparedListener(new OnPreparedListener() {

 @Override
 public void onPrepared(MediaPlayer arg0) {
 //Starting the player after getting information from url.
 mVideoView.start();
 }
 });

Thats it !! You are now ready to stream videos within the vitamio video viewer. There are a lot of options that you can explore within the viewer in the vitamio documentation which is available on their site.

Integrating Google maps API v2 with Android application

Google Maps Android API v2 The Google Maps Android API v2 allows us integrate interactive, feature-rich Google maps to our Android application. Advantage of API v2 over API v1
  • The Maps API now uses vector tiles. Their data representation is smaller, so maps appear in your apps faster, and use less bandwidth.
  • Caching is improved, so users will typically see a map without empty areas.
  • Maps are now 3D. By moving the user’s viewpoint, you can show the map with perspective.
Pre-Requisites for integrating Google Maps API v2 into my Android application
  • The API is distributed as part of the Google Play services SDK, which can be downloaded with the Android SDK Manager. To use the Google Maps Android API v2 in your application, we first need to install the Google Play services SDK.Installing Google Play Services In Eclipse, choose Window > Android SDK Manager. In the list of packages that appears scroll down to Extras folder and expand it. Select the Google Play services checkbox and install the package.
  • Next, to use Google Maps we need to create a valid Google Maps API key. The key is free, we get this key via Google APIS Console. We have to provide our application signature key and the application package name in order to get the Google Maps API key
What is Application signature key? The Maps API key is based on a short form of your application’s digital certificate, known as its SHA-1 fingerprint. The fingerprint is a unique text string generated from the commonly-used SHA-1 hashing algorithm. Because the fingerprint is itself unique, Google Maps uses it as a way to identify our application. Generating SHA1 Key Find .android directory on your device : This directory is under your home directory. Windows Vista/7: windows installation drive: (C,DE, whatever)\Users\\.android OS X and Linux: ~/.android Find debug Keystore File called debug.keystore lies in .android directory To create the SHA-1 for your debug keystore you use the keytool command from your JDK installation pointing to the debug.keystore file. Command:
keytool -list -v -alias androiddebugkey \-keystore &lt;path_to_debug_keystore&gt;debug.keystore \-storepass android -keypass android
Now follow following documentation to generate API key https://developers.google.com/maps/documentation/android/start#obtaining_an_api_key
  • Now you have installed Google play services library and generated an API key for you app lest now move to actual process to integrate a google map
Steps to Integrate Google maps to an Android application
  • Create a new android project in Eclipse, with package name that you have registered with Google console to get API key
  • Import Google play Services library to your workspace Browse to /extras/google/google_play_services/libproject/google-play-services_lib and select google-play-services_lib
  • Add this Project to your android app as -> Properties -> Android -> Library, Add -> google-play-services_lib into your project
  • Code in MainActivity should look like this
  • public class MainActivity extends Activity {
     @Override
     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     }
  • Maps are now encapsulated in the MapFragment class, an extension of Android’s Fragment class.Now you can add a map as a piece of a larger Activity.With a MapFragment object, you can show a map by itself on smaller screens, such as mobile phones, or as a part of a more complex UI on larger-screen devices, such as tablets.
What is MapFragment? It is a Map component in an app. This fragment is the simplest way to place a map in an application. It’s a wrapper around a view of a map to automatically handle the necessary life cycle needs. Being a fragment, this component can be added to an activity’s layout file simply with the XML below.

<?xml version="1.0" encoding="utf-8"?>
 <fragment xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/map"
 android:layout_width="match_parent"
 android:layout_height="match_parent" android:name="com.google.android.gms.maps.MapFragment"/>

so we need to replace content ofres/layout/activity_main.xml with code above
  • Add the following tag into your AndroidManifest.xml just before the closing tag From here, the Maps API reads the key value and passes it to the Google Maps server, which then confirms that you have access to Google Maps data.
    <meta-data android:name="com.google.android.maps.v2.API_KEY"android:value="<strong>your_api_key</strong>"/>
  • Your application now also needs the following permissions in the AndroidManifest.xml
    <permission android:name="your_package_name.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
     <uses-permission android:name="your_package_name.permission.MAPS_RECEIVE"/>
     <uses-permission android:name="android.permission.INTERNET"/>
  • Maps v2 uses OpenGl so the following uses-feature is also required <uses-feature android:glEsVersion=”0x00020000″ android:required=”true”/>
  • Thats it !! Build and run your application.
  • You should see a map. If you don’t see a map, please confirm if you have missed out any of the configurations.

Debugging Android APK on Device using Eclipse

Lets accept it, a lot of us face this problem where debugging doesn’t help on emulator and one has to debug the android application on the device itself. I will try to explain on how to do this in a step by step manner. Before actually going into the topic let us understand what ADB is. ADB The Android Debug Bridge (ADB) is a command line tool that handles debug communication between a debugger on the host (DDMS) and an Android image running on the target (Emulator or Device). Setting up a Device FOR DEBUGGING Debugging APK from device using Eclipse
  • Export signed/unsigned apk from Eclipse and install on device
  • Connect device to your machine using USB cable
  • Now click on windows >open perspective >DDMS in top menu eclipse
  • Select Devices
  • Following screen will apper
image
  • when you click on your device, all the running apps will be shown
  • Now click on green debug icon on top as shown in pic below
image Your application is now being debugged on device. Hope this saves some of our valuable time !!

Database Operations with ORM Lite

In the first blog post, we discovered about ORMLite as a formidable ORM for use in android applications. Here we will delve deeper into how to perform various database operations using ORMLite Query Operation in ORM Lite The DAOs provide basic methods to query for an object that matches an id (queryForId) and query for all objects (queryForAll), iterating through all of the objects in a table . However, for more custom queries, there is the queryBuilder() method which returns a QueryBuilder object for the DAO with which you can construct custom queries to return a sub-set of your tables. Query Builder is something that assists in building SQL query (SELECT) statements for a particular table in a particular database. 1.Query for all Returns the list of all records in the table we have in build function queryForAll();
// get our dao
 RuntimeExceptionDao<DemoORMLite, Integer> DemoORMLiteDao = getHelper().getDemoORMLiteDao ();

// query for all of the data objects in the database
 List<SimpleData> list = simpleDao.queryForAll();
2. Query for id Returns the record corresponding to given id we have in build function queryForId(id);
TEntity entity = <strong>this</strong>.dao.queryForId(id);
3. Query for particular field name Here we use QueryBuilder to query for field “lastname” and return the list of records that have last_name =”lastname”
Public List<DemoORMLite> RetrieveByLastName(String lastname)throws SQLException {
QueryBuilder<TEntity,Integer> queryBuilder = dao.queryBuilder();
List list;
queryBuilder.where().eq("last_name", lastname);
list = queryBuilder.query();
return list;
}
Deleting a record in ormlite DeleteBuilder assists in building sql DELETE statements for a particular table in a database. Sample Code that deletes elements from table by argument
DatabaseHelper helper = OpenHelperManager.getHelper(App.getContext(), DatabaseHelper.class);</pre>
//get helper
 Dao dao = helper.getDao(YOUR_CLASS.class);

//get your Dao
 DeleteBuilder<CanteenLog, Integer> deleteBuilder = dao.deleteBuilder();
 // CanteenLog here is table name

deleteBuilder.where().eq("FIELD_NAME", arg);

deleteBuilder.delete();

Order by in ormlite Syntax: orderBy(String columnName, boolean ascending) Add “ORDER BY” clause to the SQL query statement to order the results by the specified column name. Use the ascending boolean to get a ascending or descending order. This can be called multiple times to group by multiple columns.
QueryBuilder<Visit, Integer> qb = getHelper().getyourdaoname().queryBuilder();
 qb.where().eq("Field_name", fieldname);
 qb.orderBy("order_according_to_this_field", false);

Using Max in Ormlite

long max = fooDao.queryRawValue(

"select max(modified) from foo where userid = ?", id);
 // now perform a second query to get the max row
 Foo foo = fooDao.queryBuilder().where().eq("modified", max).queryForFirst();

Set default value to column in ORMLite
@DatabaseField(defaultValue = "unknownName", canBeNull = true)
Here we explored various simple ORMLite operations. If you have used ORMLite in more advanced way, Please feel free to drop a comment below !!

ORMLITE – Light Weight Object Relational Mapping – An Introduction

OVERVIEW ORM Lite provides a lightweight Object Relation Mapping between Java classes and SQL databases. ORM Lite supports JDBC connections to MySQL, Postgres, H2, SQLite, Derby, HSQLDB, and Microsoft SQL Server. ORM Lite also supports native database calls on Android OS. Using ORM Lite with Android Downloading ORMLITE To get started with ORM Lite, We need to download the ORM Lite jar files. These can be downloaded from ORM Lite release page Once we have downloaded ORM Lite, we will need to add it as an external library to our android project. Just Drop the jar file into your project’s libs/ subdirectory. We only need the ormlite-android-4.14.jar, not the ORM lite-core or any other packages. Getting Started with ORM Lite To get started with ORM lite we need to create our own database helper class which should extend the OrmLiteSqliteOpenHelper class. This class creates and upgrades the database when the application is installed and also provide the DAO(Data Access Object) classes used by other classes. The helper class must implement the methods

onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource)

onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)

onCreate creates the database when app is first installed while onUpgrade handles the upgrading of the database tables when we upgrade our app to a new version. The helper should be kept open across all activities in the app with the same SQLite database connection reused by all threads. If we open multiple connections to the same database, stale data and unexpected results may occur. It is recommended to use the OpenHelperManager to monitor the usage of the helper – it will create it on the first access, track each time a part of our code is using it, and then it will close the last time the helper is released. Once we define our database helper and are managing it correctly, We will use it in our Activity classes. An easy way to use the OpenHelperManager is to extend OrmLiteBaseActivity for each of your activity classes – there is also OrmLiteBaseListActivity, OrmLiteBaseService, and OrmLiteBaseTabActivity. These classes provide a helper protected field and a getHelper() method to access the database helper whenever it is needed and will automatically create the helper in the onCreate() method and release it in the onDestroy() method. Here is sample DatabaseHelper class http://ormlite.com/android/examples/DatabaseHelper.java Creating Table using ORM Lite There are a few things to notice when we use ORM Lite:
  1. We just annotate our class as a table and its members as fields and we’ re almost done with creating a table
  2. ORM Lite handles all of the basic data types without any explicit work on your part (integers, strings, floats, dates, and more).
  3. It is mandatory to have a no argument constructor in our class
In onCreate method of Databasehelper we create tables with help of TableUtils like
TableUtils.createTable(connectionSource, SimpleData.class);,
SimpleData here is name of table An example code to create Table in the onCreate callback:
 /**
 * This is called when the database is first created. Usually you should call createTable statements here to create
 * the tables that will store your data.
 */
 @Override
 public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
 try {
 TableUtils.createTable(connectionSource, SimpleData.class);
 } catch (SQLException e) {
 Log.e(DatabaseHelper.class.getName(), "Can't create table", e);
 throw new RuntimeException(e);
 }

Here is sample ORMLite table class

/**
 * A simple demonstration object we are creating and persisting to the database.
 */
 public class SimpleData {

// id is generated by the database and set on the object automagically
 @DatabaseField(generatedId = true)
 int id;
 @DatabaseField(index = true)
 String string;
 @DatabaseField
 long millis;
 @DatabaseField
 Date date;
 @DatabaseField
 boolean even;

SimpleData() {
 // needed by ormlite
 }

public SimpleData(long millis) {
 this.date = new Date(millis);
 this.string = (millis % 1000) + "ms";
 this.millis = millis;
 this.even = ((millis % 2) == 0);
 }

@Override
 public String toString() {
 StringBuilder sb = new StringBuilder();
 sb.append("id=").append(id);
 sb.append(", ").append("string=").append(string);
 sb.append(", ").append("millis=").append(millis);
 SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.S");
 sb.append(", ").append("date=").append(dateFormatter.format(date));
 sb.append(", ").append("even=").append(even);
 return sb.toString();
 }
 }

Hope that the blog gets you running on ORMLite, In the subsequent posts, we will explore more about ORMLite and how to use it to manipulate/retrieve data objects. References:
  1. ORMLite Sample table class (http://ormlite.com/android/examples/SimpleData.java)
  2. ORMLite example: (http://ormlite.com/android/examples/)

Developing an android twitter client using twitter4j

Recently, we worked out an android twitter client for one for our esteemed clients. In this blog, I will try to explain on how to go about on building such an android application from scratch.
  1. Register your application on http://dev.twitter.com/apps/new.
  2. Please ensure that the application is of the browser type. Please fill anything in the callback url like http://twitter-test.com
  3. You will get the consumer key and the consumer secret once the application registration has been successful.
  4. Create an android project in eclipse(We use eclipse mostly, Please adjust the eclipse specific notes in this blog to adjust to your editor).
  5. Import twitter4j(http://twitter4j.org/en/index.html) as an external jar. This seems to be one of very few complete twitter libraries for java.
  6. We will try to post a status update to twitter. Lets get down to a bit of coding now. Place the following code where you want to trigger the twitter authentication process.
  7. 	Twitter twitter = new TwitterFactory().getInstance();
    	try
    	{
    
    	twitter.setOAuthConsumer(<consumer_key>, <consumer_secret>);
    	String callbackURL = "twitter-client:///";
    	rToken = twitter.getOAuthRequestToken(callbackURL);
    	startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(rToken.getAuthenticationURL())));
    	}
    	catch(IllegalStateException e)
    	{
    	// access token is already available, or consumer key/secret is not set.
    	if(!twitter.getAuthorization().isEnabled()){
    	System.out.println("OAuth consumer key/secret is not set.");
    	System.exit(-1);
    	}
    	}
    	catch(Exception e)
    	{
    	Toast.makeText(TwitterClient.this, "Network Host not responding",Toast.LENGTH_SHORT).show();
    	}
    	
  8. Lets try to deciper the code here
  9. First we get the instance of the twitter factory and the set the oAuth consumer and secret with the keys that we got from the twitter site.
  10. Next we point the callbackURL to the intent filter that we would create in the application xml file. The intent filter is required so that the application catches the intent when the browser redirects back after successful twitter authentication. In my case i have added the following intent filter to my AndroidManifest.xml
  11. <intent-filter>
    <action android:name=”android.intent.action.VIEW” />
    <category android:name=”android.intent.category.DEFAULT” />
    <category android:name=”android.intent.category.BROWSABLE” />
    <data android:scheme=”twitter-client”/>
    </intent-filter>
    You can read more about intent filters on the android sdk site.
  12. Next we get the oauth request token and start the activity which will get the username/password and give authorization to our twitter application.
  13. When we return back from twitter, will place the following code on onResume activity callback:
    </li>
    @Override
    
    public void onResume() {
    
    super.onResume();
    
    Uri uri = getIntent().getData();
    
    if (uri != null) {
    
    oauthVerifier = uri.getQueryParameter("oauth_verifier");
    
    }
    
    try {
    
    Twitter tt = new TwitterFactory ().getInstance();
    tt.setOAuthConsumer(<consumer_key>, <consumer_secret>);
    AccessToken at = tt.getOAuthAccessToken(rToken, oauthVerifier);
    String token = at.getToken();
    String secret = at.getTokenSecret();
    // Post to twitter.
    Twitter t = new TwitterFactory().getOAuthAuthorizedInstance(<consumer_key>,
    <consumer_secret>,
    new AccessToken (token, secret));
    t.updateStatus("Test Android Twitter Client");
    
    } catch(Exception e) {
    Toast.makeText(TwitterClient.this, "Network Host not responding",Toast.LENGTH_SHORT).show();
    }
    }
    
  14. Twitter has sent the verifier in the parameter of the return url, so we get it using getIntent().getData().getQueryParameter(“oauth_verifier”)
  15. Now when we have the verifier, we can get the access token and call the twitter4j method to update the status on twitter. twitter4j supports most of the twitter API and can be used for any operation which can be performed using twitter API.
Hope this helps someone. In case you have any queries, Please feel free to leave them in comments. We will be more than happy to help !! Edit: Here is the link to Sample Application. Please replace the variables OAUTH_CONSUMER and OAUTH_SECRET with the consumer and secret keys of the application that you have registered with twitter.