Search This Blog

Thursday, 2 August 2012

Twitter Live Streaming - Sample Code

Social media is the key ingredient of applications and integrating the social media platform with mobile applications the key of success for your mobile applications.


The large social networks could not fit to one single mobile application increasing the opportunity for all mobile developers to create more interesting and creative small apps for mobile devices with this social platforms.


Twitter is one of the popular social networking platform. The update on twitter is very fast as tweets are small in size. Twitter introduced the live streaming APIs to get the updates in real time from twitter live streaming service.


You can integrate the twitter live streaming in your android application as described in this post.


Create a default activity project in eclipse for android and create the following layout for your application in activity_main.xml.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/StartTweetsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Start Tweets"
android:onClick="startTweets" />
<Button
android:id="@+id/StopTweetsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Stop Tweets"
android:onClick="stopTweets" />
<EditText
android:id="@+id/SearchText"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</EditText>
<ListView android:id="@+id/TweetsList"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
></ListView>
</LinearLayout>


Now replace the default activity class code by the following code

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;



public class MainActivity extends Activity implements View.OnClickListener {

    private List<HashMap<String,String>> mTweets = new ArrayList<HashMap<String,String>>();
    private SimpleAdapter mAdapter;
    private boolean m_Running = false;
    private String m_SearchKeyWord = "";
    final int MAXLIST = 10;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //create a list view and bind with simple adapter
        mAdapter = new SimpleAdapter(this, mTweets, android.R.layout.simple_list_item_2, new String[] {"Tweet", "From"}, new int[] {android.R.id.text1, android.R.id.text2});
        ListView lv = (ListView)findViewById(R.id.TweetsList);
        lv.setAdapter(mAdapter);
        //create a list view and bind with simple adapter
    }
   
    public class StreamTask extends AsyncTask<Context, Boolean, Boolean> {
        protected Boolean doInBackground(Context... arg0) {
            try
            {
            DefaultHttpClient client = new DefaultHttpClient();
            String userName = "XXXXXXX";
            String password = "XXXXXXX";
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(userName, password);
            client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
            HttpGet request = new HttpGet();
            String m_SearchKeyWord = null;
            request.setURI(new URI("https://stream.twitter.com/1/statuses/filter.json?track=" + m_SearchKeyWord));
            HttpResponse response = client.execute(request);
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
            handleTweets(reader);
            
            in.close();
            }
            catch (Exception e) {
            Log.e("SampleTwitter", "doInBackground_" + e.toString());
            }
            return true;
        }
         private void handleTweets( BufferedReader reader ) {
                try {
                    String line = "";
                    
                    do
                    {
                        line = reader.readLine();
                        JSONObject tweet = new JSONObject(line);
                        HashMap<String, String> tweetMap = new HashMap<String, String>();
                        if (tweet.has("text")) {
                            Log.i("SampleTwitter","Tweet : " + tweet.getString("text"));
                            tweetMap.put("Tweet", tweet.getString("text"));
                            tweetMap.put("From", tweet.getJSONObject("user") .getString("screen_name"));
                            Log.i("SampleTwitter","From : " + tweet.getJSONObject("user") .getString("screen_name"));
                            mTweets.add(0, tweetMap);
                            if (mTweets.size() > MAXLIST) 
                            {
                                mTweets.remove(mTweets.size() - 1);
                            }
                            publishProgress(true);
                        }
                    } while (m_Running && line.length() > 0);
                }
                catch (Exception e) {
                    Log.e("SampleTwitter", "handleTweets_" + e.toString());
                }
            }
         
        
    
        protected void onProgressUpdate(Boolean... values) {
            super.onProgressUpdate(values);
            mAdapter.notifyDataSetChanged();
            Log.d("SampleTwitter", "Im in onProgressUpdate()");
        }
        
    }
    public void stopTweets(View view ) {
        m_Running = false;
        for(int idx=mTweets.size()-1;idx>=0;idx--)
            mTweets.remove(idx);
        if(mTweets.size() ==1)
            mTweets.remove(0);
        mAdapter.notifyDataSetChanged();
    }
   public void startTweets(View view) {
        
        if( m_Running == false ) 
        {
            EditText edt = (EditText)findViewById(R.id.SearchText);
            m_SearchKeyWord =  edt.getText().toString();
            if( m_SearchKeyWord.length() > 0 ) 
            {
                StreamTask st = new StreamTask();
                st.execute();
                m_Running = true;
                
            }
            else 
            {
                Toast.makeText(this, "Please enter the search keyword", Toast.LENGTH_SHORT).show();
            }
        }
        else 
        {
            Toast.makeText(this, "Already Running", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        
    }

    
}

This sample is getting the twitter updates from real time stream API and showing that in a list view. you need to change the username and password values in doInBackGround() method to connect to the twitter.


The following is URL on which we can send a https request to get the tweets update in real time based on the tag value or search keyword.


https://stream.twitter.com/1/statuses/filter.json?track=?


The AsyncTask is the best way to implement the tweets updates in background. The StreamTask in the sample is extending the AsyncTask and implementing the doInBackGround()  method to create a https connection with twitter service and receive a JSON response. The JSON response is parsed by the 
handleTweets() method. The method extract the text tweets and add in the hash map to update in the list view.


To update the UI in background function in AsyncTask the publishProgress will send the update to the onProgressUpdate method of AsyncTask. 


mAdapter.notifyDataSetChanged();


This call will send a signal to the list view adapter about the change of data and the UI thread update the list view.


See the output of the sample here


Twitter
Twitter Live Streaming




if you like the post then please provide your feedback.


Thanks
Creative Android Apps


Wednesday, 1 August 2012

Using Camera in Android Application


The picture speaks more then your words. The picture is the key ingredient for a application interacting with physical world.


Android provides the very easy interface with the existing camera application to quickly integrate the camera function to your application. You can take picture and easily access the image data in your application with very few line of code in android.


This post is explaining the quick integration of the existing camera application with your own android application.


To capture the photo from existing camera application you can use the following line of code.


private void dispatchTakePictureIntent(int actionCode) {
    Intent PictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(PictureIntent, actionCode);
}


To get the photo in your application you simple need to implement onActivityResult() method which. The image data bundled in the extras as a bitmap and return to the caller in onActivityResult method.


private void onActivityResult(Intent intent) {
    Bundle extras = intent.getExtras();
    Bitmap mImageBitmap = (Bitmap) extras.get("data");
    
}

Now you can play with this bitmap data in your application.


Thanks
Creative Android Apps

Thursday, 26 July 2012

Google Place APIs



Google Place APIs



Google Place API is a service which provides the search system for places. The search with the google place API can be perform by two ways.


1) Text String Search - a normal search specify the search string as text
2) User location based search - a search specified based on the location parameters (latitude,longitude)


You can integrate the places search based on the location in your android application. See the previous example to determine the location of a user and draw a overlay icon pointed to that location of the user.


This post is explaining the implementation of place search by google place API.


The HTTP URL for the place search is as follows

https://maps.googleapis.com/maps/api/place/search/output?parameters

The output could be json or xml and the required parameters are as follows


key - Your application key.
location - latitude,longitude of the place to search
radius - search area in which the search should perform for location
sensor - true or false based on the request is initiated by a devices having a location sensor (GPS) enabled or disabled


The following is the list of optional parameters to refine your search


Keyword — A term to be matched against all content that Google has indexed for the place
Language — The language code, indicating in which language the results should be returned.
Name — A term to be matched against the names of Places. Results will be restricted to those containing the values passed here.
Rankby — Specifies the order in which results are listed. Possible values are:

· Prominence - This option sorts results based on their importance.
· Distance - This option sorts results in ascending order by their distance from the specified location.
· Types — Restricts the results to places matching at least one of the specified types. Types must be separated with a pipe symbol (type1|type2|etc).
· Pagetoken — Returns the next 20 results from a previously run search.



   Code : The following few line of code explain how can you call google web    service in your application.

    String result = "";
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    ResponseHandler<String> handler = new BasicResponseHandler();
    try {
        result = httpclient.execute(request, handler);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();

The Google Place APIs provide a quick way to integrate the context aware search to your application. 


If you like the post please provide your feedback. 


Thanks
Creative Android Apps






Tuesday, 24 July 2012

Exception networkonmainthreadexception in Android


Exception networkonmainthreadexception in Android



This exception is due to the StrictMode introduced on honeycomb or later android devices to not allow the network operations in main thread.


The solution to this exception is that you implement a thread for network operation instead of implementing in main thread.


The alternative method is to disable the option which is enable by default in honeycomb and later android OS.The previous versions of android OS allowed the main thread to create the network connections.


Disabling the StrictMode in Android


StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);


If you like the solution please provide your comments.


Thanks
Creative Android Apps

Monday, 23 July 2012

Integrating Facebook in Android Apps


Quick integration of facebook on android platform



Hello Creative Android Developers,


This post is explaining the integration of facebook a powerful social media with android applications.


facebook the powerful social media provides the enrich developer APIs to integrate the facebook features in applications. You can create lots of derivative social apps from facebook and can add a social touch to your app with facebook interaction.


This post is focusing on developing the android application with facebook APIs. The facebook SDK could be download from https://github.com/facebook/facebook-android-sdk/


Once you download the facebook-android-sdk you need to create an android project to compile the facebook-android-sdk code and create a library for facebook APIs.


Now you can create your sample code by using the above library as reference in your application.


Create a simple android application project and replace the activity code as follows.


You need to register your application on facebook platform and get the application id from the platform.

package com.example.samplefacebook;

import android.os.Bundle;

import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import com.facebook.android.*;
import com.facebook.android.Facebook.*;

public class MainActivity extends Activity {

   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    
    Facebook facebook = new Facebook("YOUR APP ID");

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

        facebook.authorize(this, new DialogListener() {
            @Override
            public void onComplete(Bundle values) {}

            @Override
            public void onFacebookError(FacebookError error) {}

            @Override
            public void onError(DialogError e) {}

            @Override
            public void onCancel() {}
        });
    }

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

        facebook.authorizeCallback(requestCode, resultCode, data);
    }
    
}


This is the simple code for invoking the login interface with single-sign-on (SSO) of the facebook from your android application. 


You need to add the following permission to access the facebook platform.


Add the following line in AndroidManifest.xml of the sample.

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

Now running the application we show the following output

facebook on android
Facebook - (SSO) in Android App

Now you can make your apps more social with facebook. If you like the post then please provide your feedback.


Thanks
Creative Android Apps



Sunday, 22 July 2012

Sample Code - Implementing the sensor in Android


Sample Code - TYPE_LIGHT sensor to get the screen brightness for android device



Android provide the android.hardware framework to implement the sensors. you could get a quick understanding of android sensor framework for our previous post.


http://creativeandroidapps.blogspot.in/2012/07/basics-of-sensors-on-android-platform.html


This post will explain the implementation of SensorEventListener for the TYPE_LIGHT sensor. The light listener is used to control the brightness of the screen.


You need to create a Android Application Project in your eclipse editor and modify the Activity class to extend with SensorEventListener.  See the following code of the sample.

package com.example.samplesensor;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity implements SensorEventListener {

    private SensorManager mSensorManager;
    private Sensor mLight;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onSensorChanged(SensorEvent arg0) {
        // TODO Auto-generated method stub
        float lux = arg0.values[0];
        Toast.makeText(getApplicationContext(), "Sensor Value " + lux, 1000).show();
    }

    @Override
      protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
      }

      @Override
      protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
      }
}


Get the instance of the system service of sensor manager and get the TYPE_LIGHT sensor from the system.
You need to implement the two callback methods provided by the SessionEventListener.


The sensor need to register on the onResume() and onPause() methods of activity class.


The TYPE_LIGHT sensor only returns the one value which is brightness of the device screen. The brightness of the screen is measured by lux unit.


One lux is equal to one lumen per square metre.


If you like the example please provide your feedback.


Thanks
Creative Android Apps


Sensors framework for Android



Android Sensor Framework


Android provides a development framework to develop the applications with various sensors described in the following post.


http://creativeandroidapps.blogspot.in/2012/07/basics-of-sensors-on-android-platform.html

Android provides a android.hardware package which includes the following four classes for sensor management.

SensorManager - Sensor Manager is a class to manage the various sensors provides the methods to list the sensors available on the device, register the sensor listeners and acquire the sensors data. You can use this class to create an instance of the sensor service.


Sensor - This class provides the methods specific to a sensor. The sensor manager returns the sensor object which can use to handle the sensor functions which depends on the type of the sensor.


SensorEvent - The framework defines this class to handle the sensor events and create a object of sensor event. A sensor event object includes the raw sensor data, the type of sensor that generated the event, the accuracy of the data, and the timestamp for the event.


SensorEventListener - The sensor event listener provides the two callback methods to implement to receive the sensor events when sensor changes its value or when sensor accuracy changes.


Now you can see the next article to create quick sample for sensors on android platform.


http://creativeandroidapps.blogspot.in/2012/07/sample-code-implementing-sensor-in.html


If you like the post please provide your feedback.


Thanks
Creative Android Apps