Browse Month: October 2012

Server Client Communication in android

In this tutorial we will make a TCP Connection. The server will be written in Java and the client will be written in Android. Actually it will be a very simple messenger client.

A. Make the Server in Java

1.To create the server create a new project in Java and make a class called “TCPServer”. In this class put the following code:

import javax.swing.*;




/* The class extends the Thread class so we can receive and send messages at the same time*/

public class TCPServer extends Thread {

public static final int SERVERPORT = 4444;

private boolean running = false;

private PrintWriter mOut;

private OnMessageReceived messageListener;

public static void main(String[] args) {

//opens the window where the messages will be received and sent

ServerBoard frame = new ServerBoard();





/**Constructor of the class @param messageListener listens for the messages*/

public TCPServer(OnMessageReceived messageListener) {

this.messageListener = messageListener;


/* Method to send the messages from server to client @param message the message sent by the server*/

public void sendMessage(String message){

if (mOut != null && !mOut.checkError()) {






public void run() {;

running = true;

try {

System.out.println(“S: Connecting…”);

//create a server socket. A server socket waits for requests to come in over the network.

ServerSocket serverSocket = new ServerSocket(SERVERPORT);

//create client socket… the method accept() listens for a connection to be made to this socket //and accepts it.

Socket client = serverSocket.accept();

System.out.println(“S: Receiving…”);

try {

//sends the message to the client

mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

//read the message received from client

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

//in this while we wait to receive messages from client (it’s an infinite loop)

//this while it’s like a listener for messages

while (running) {

String message = in.readLine();

if (message != null && messageListener != null) {

//call the method messageReceived from ServerBoard class




} catch (Exception e) {

System.out.println(“S: Error”);


} finally {


System.out.println(“S: Done.”);


} catch (Exception e) {

System.out.println(“S: Error”);




//Declare the interface. The method messageReceived(String message) will must be implemented in the ServerBoard

//class at on startServer button click

public interface OnMessageReceived {

public void messageReceived(String message);



2.Now create another java class and call it “ServerBoard”. In this class we will make the “messenger” UI (a very simple one) with a field where the messages will be added, a text field where the server side can enter a message and 2 buttons: one to start the connection and one to send the messages. The code is like this:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class ServerBoard extends JFrame {

private JTextArea messagesArea;

private JButton sendButton;

private JTextField message;

private JButton startServer;

private TCPServer mServer;

public ServerBoard() {


JPanel panelFields = new JPanel();

panelFields.setLayout(new BoxLayout(panelFields,BoxLayout.X_AXIS));

JPanel panelFields2 = new JPanel();

panelFields2.setLayout(new BoxLayout(panelFields2,BoxLayout.X_AXIS));

//here we will have the text messages screen

messagesArea = new JTextArea();




sendButton = new JButton(“Send”);

sendButton.addActionListener(new ActionListener() {


public void actionPerformed(ActionEvent e) {

// get the message from the text view

String messageText = message.getText();

// add message to the message area

messagesArea.append(“n” + messageText);

// send the message to the client


// clear text




startServer = new JButton(“Start”);

startServer.addActionListener(new ActionListener() {


public void actionPerformed(ActionEvent e) {

// disable the start button


//creates the object OnMessageReceived asked by the TCPServer constructor

mServer = new TCPServer(new TCPServer.OnMessageReceived() {


//this method declared in the interface from TCPServer class is implemented here

//this method is actually a callback method, because it will run every time when it will be called from

//TCPServer class (at while)

public void messageReceived(String message) {

messagesArea.append(“n “+message);






//the box where the user enters the text (EditText is called in Android)

message = new JTextField();

message.setSize(200, 20);

//add the buttons and the text fields to the panel







getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));

setSize(300, 170);




B. Create the Client in Android

/*To create the Client, create a new project and call the class that creates with the project ”   MyActivity”.

*After this make a new class and call it “TCPClient”

*Now in the class TCPClient put the following code:*/


import android.util.Log;




public class TCPClient {

private String serverMessage;

public static final String SERVERIP = “”; //your computer IP address

public static final int SERVERPORT = 4444;

private OnMessageReceived mMessageListener = null;

private boolean mRun = false;

PrintWriter out;

BufferedReader in;

/* Constructor of the class. OnMessagedReceived listens for the messages received from server*/

public TCPClient(OnMessageReceived listener) {

mMessageListener = listener;


/** Sends the message entered by client to the server

* @param message text entered by client*/

public void sendMessage(String message){

if (out != null && !out.checkError()) {





public void stopClient(){

mRun = false;


public void run() {

mRun = true;

try {

//here you must put your computer’s IP address.

InetAddress serverAddr = InetAddress.getByName(SERVERIP);

Log.e(“TCP Client”, “C: Connecting…”);

//create a socket to make the connection with the server

Socket socket = new Socket(serverAddr, SERVERPORT);

try {

//send the message to the server

out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

Log.e(“TCP Client”, “C: Sent.”);

Log.e(“TCP Client”, “C: Done.”);

//receive the message which the server sends back

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

//in this while the client listens for the messages sent by the server

while (mRun) {

serverMessage = in.readLine();

if (serverMessage != null && mMessageListener != null) {

//call the method messageReceived from MyActivity class



serverMessage = null;


Log.e(“RESPONSE FROM SERVER”, “S: Received Message: ‘” + serverMessage + “‘”);

} catch (Exception e) {

Log.e(“TCP”, “S: Error”, e);

} finally {

//the socket must be closed. It is not possible to reconnect to this socket

// after it is closed, which means a new socket instance has to be created.



} catch (Exception e) {

Log.e(“TCP”, “C: Error”, e);



//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity

//class at on asynckTask doInBackground

public interface OnMessageReceived {

public void messageReceived(String message);



At the beginning of this class you have a constant SERVERIP. In this constant you have to put your computer IPv4. To do this open the commander and type ipconfig and press Enter. Then you will see your computer’s IP.

Also the SERVERPORT from this class (TCPClient) must be the same with the SERVERPORT from server class (TCPServer).

Now that the server and client classes are done, we have to set the interface a little. For this we will make a ListView in MyActivity class where we will get the messages sent and received, an EditText to enter the message from client side and a button to send the message. So let’s begin.

2.go to res – layout – main.xml and put this code in main.xml:

<LinearLayout xmlns:android=””




<ListView android:id=”@+id/list”







<LinearLayout android:id=”@+id/footer”





<EditText android:inputType=”textMultiLine|textNoSuggestions”





<Button android:layout_width=”wrap_content”




android:text=”send” />



create a new xml file and call it “list_item.xml”. This will contain a TextView for the messages which will be added to the ListView. The code will look like this:

3.<?xml version=”1.0″ encoding=”utf-8″?>








<TextView android:layout_width=”wrap_content”







4.create a new class and call it “MyCustomAdapter”.

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.TextView;

import java.util.ArrayList;

public class MyCustomAdapter extends BaseAdapter {

private ArrayList<String> mListItems;

private LayoutInflater mLayoutInflater;

public MyCustomAdapter(Context context, ArrayList<String> arrayList){

mListItems = arrayList;

//get the layout inflater

mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);



public int getCount() {

//getCount() represents how many items are in the list

return mListItems.size();



//get the data of an item from a specific position

//i represents the position of the item in the list

public Object getItem(int i) {

return null;



//get the position id of the item from the list

public long getItemId(int i) {

return 0;



public View getView(int position, View view, ViewGroup viewGroup) {

//check to see if the reused view is null or not, if is not null then reuse it

if (view == null) {

view = mLayoutInflater.inflate(R.layout.list_item, null);


//get the string item from the position “position” from array list to put it on the TextView

String stringItem = mListItems.get(position);

if (stringItem != null) {

TextView itemName = (TextView) view.findViewById(;

if (itemName != null) {

//set the item name on the TextView




//this method must return the view corresponding to the data at the specified position.

return view;



5.And now in the MyActivity class put the following code:


import android.os.AsyncTask;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ListView;

import java.util.ArrayList;

public class MyActivity extends Activity


private ListView mList;

private ArrayList<String> arrayList;

private MyCustomAdapter mAdapter;

private TCPClient mTcpClient;


public void onCreate(Bundle savedInstanceState)




arrayList = new ArrayList<String>();

final EditText editText = (EditText) findViewById(;

Button send = (Button)findViewById(;

//relate the listView from java to the one created in xml

mList = (ListView)findViewById(;

mAdapter = new MyCustomAdapter(this, arrayList);


// connect to the server

new connectTask().execute(“”);

send.setOnClickListener(new View.OnClickListener() {


public void onClick(View view) {

String message = editText.getText().toString();

//add the text in the arrayList

arrayList.add(“c: ” + message);

//sends the message to the server

if (mTcpClient != null) {



//refresh the list






public class connectTask extends AsyncTask<String,String,TCPClient> {


protected TCPClient doInBackground(String… message) {

//we create a TCPClient object and

mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {


//here the messageReceived method is implemented

public void messageReceived(String message) {

//this method calls the onProgressUpdate




return null;



protected void onProgressUpdate(String… values) {


//in the arrayList we add the messaged received from server


// notify the adapter that the data set has changed. This means that new message received

// from server was added to the list





6.And one last thing. Go to AndroidManifest.xml and put the internet permission just before the </manifest>:

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


  • Now that the project is done we must see how it actually works

1. First, you must open the server, so run the TCPServer class, the one that is made in Java and a window called ServerBoard will appear. Press on the start button like in the picture below. Do NOT start the android project before you press the start button!


2. The server waits the client to connect now, so run the android project on the emulator and wait for the project to load.


3. After the project is loaded enter a message in the EditText and send it. Your text should appear on the ListView.


4. Now go back to the ServerBoard and send a message to the client from Android. The message from server side should appear on the ListView too.


NOTE: If you test this on a device and it's not working, probably you should turn off all your firewall (from Windows, from antivirus) . And make sure that your device WIFI is turned on (because the android client must be on the same network as the server).










Updates in iOS 6

A lot has happened in iOS 6 and apple has a document which you may read it from here. The above document will guide you out regarding the changes that has happened in iOS technology.

UIKIT Framework

  • In iOS 5.1, the UISplitViewController class adopts the sliding presentation style when presenting the left view (previously seen only in Mail). This style is used when presentation is initiated either by the existing bar button item provided by the delegate methods or by a swipe gesture within the right view. No additional API adoption is required to obtain this behavior, and all existing APIs—including that of the UIPopoverController instance provided by the delegate—will continue to work as before. If the gesture would be insupportable in your app, setting the presentsWithGesture property of your split view controller to NO disables the gesture. However, disabling the gesture is discouraged because its use preserves a consistent user experience across all apps.
  • In iOS 6, changes have been introduced so that you no longer need to set a delegate and implement a method for single-finger and single-tap gesture recognizers. This makes them work well with theUIControl objects.
  • In iOS 6 and later, the UIWebView class paints its contents asynchronously.
  • Autorotation is changing in iOS 6. In iOS 6, the shouldAutorotateToInterfaceOrientation: method of UIViewController is deprecated. In its place, you should use thesupportedInterfaceOrientationsForWindow: and shouldAutorotate methods.
    • More responsibility is moving to the app and the app delegate. Now, iOS containers (such as UINavigationController) do not consult their children to determine whether they should autorotate. By default, an app and a view controller’s supported interface orientations are set to UIInterfaceOrientationMaskAll for the iPad idiom andUIInterfaceOrientationMaskAllButUpsideDown for the iPhone idiom.
    • A view controller’s supported interface orientations can change over time—even an app’s supported interface orientations can change over time. The system asks the top-most full-screen view controller (typically the root view controller) for its supported interface orientations whenever the device rotates or whenever a view controller is presented with the full-screen modal presentation style. Moreover, the supported orientations are retrieved only if this view controller returns YES from its shouldAutorotate method. The system intersects the view controller’s supported orientations with the app’s supported orientations (as determined by the Info.plist file or the app delegate’s application:supportedInterfaceOrientationsForWindow: method) to determine whether to rotate.
    • The system determines whether an orientation is supported by intersecting the value returned by the app’s supportedInterfaceOrientationsForWindow: method with the value returned by thesupportedInterfaceOrientations method of the top-most full-screen controller.
    • The setStatusBarOrientation:animated: method is not deprecated outright. It now works only if the supportedInterfaceOrientations method of the top-most full-screen view controller returns 0. This makes the caller responsible for ensuring that the status bar orientation is consistent.
    • For compatibility, view controllers that still implement the shouldAutorotateToInterfaceOrientation: method do not get the new autorotation behaviors. (In other words, they do not fall back to using the app, app delegate, or Info.plist file to determine the supported orientations.) Instead, the shouldAutorotateToInterfaceOrientation: method is used to synthesize the information that would be returned by the supportedInterfaceOrientations method.
  • The willRotateToInterfaceOrientation:duration:,   willAnimateRotationToInterfaceOrientation:duration:, and didRotateFromInterfaceOrientation: methods are no longer called on any view controller that makes a full-screen presentation over itself—for example, presentViewController:animated:completion:.
    • You should make sure that your apps are not using these methods to manage the layout of any subviews. Instead, they should use the view controller’s viewWillLayoutSubviews method and adjust the layout using the view’s bounds rectangle.
  • In iOS 6, the viewWillUnload and viewDidUnload methods of UIViewController are now deprecated. If you were using these methods to release data, use the didReceiveMemoryWarning method instead. You can also use this method to release references to the view controller’s view if it is not being used. You would need to test that the view is not in a window before doing this.
  • It is not supported to set values for the shadowOffset or shadowColor properties of a UILabel object if its attributedText property contains a valid attributed string. Instead, use theNSShadowAttributeName attribute of the attributed string to set the shadow.
  • Due to compatibility concerns, the NSBaselineOffsetAttributeName attribute is no longer supported in iOS 6.
  • The NSTextAlignmentNatural value is not supported. It will throw an exception when it is used with the textAlignment property of UILabel or is supplied as the alignment parameter to thedrawInRect:withFont:lineBreakMode:alignment: method of NSString.
  • The setContentStretch: method of UIView has been deprecated. To achieve the same effect, use the resizableImageWithCapInsets: method of UIImage and display the image with aUIImageView.
  • The resizableImageWithCapInsets: method of UIImage effectively resizes images by tiling. As a performance optimization, it uses stretching rather than tiling when the user would not be able to tell the difference, such as when a single column or row is being stretched. But in certain circumstances, the user might want to actually stretch some region of an image. In iOS 6, theresizableImageWithCapInsets:resizingMode: method allows the caller to specify a tiling or stretching resizing mode.
  • The UICollectionViewLayout class has changed:
    • The class now supports the customization of the animations created during rotation. The names of methods for customizing insert and delete animations have also changed, so the same hooks can be used for rotations as well as for insertions and deletions.
    • The class has changed some method names. Specifically, decoration views are no longer referred to by “reuse identifier” but rather by “element kind.” Apps that are using decoration views will need to modify their code and be rebuilt to accommodate this.
  • The bottom edge of a UILabel view is now different from its baseline.

Previously, Auto Layout was interpreting the bottom of a UILabel to be the same as its baseline. While convenient in many cases, it caused problems if you wanted to place the top edge of one label against the bottom edge of another. In such a scenario, the bottom label would overlap the top one, and descenders from the top label could crash into ascenders from the bottom label. Now, Auto Layout interprets UILayoutAttributeBottom as the bottom of the text box (presuming the label is not bigger than its intrinsic content size) and UILayoutAttributeBaseline as the baseline of the text. If you have already created code for laying out labels according to the bottom or center point, your text will move around a little and you will need to adjust your constraints.

  • Apps with table views in their nib or storyboard files, and that were built using previous versions of iOS 6 beta, will require a clean build with beta 3 and newer.

Landscape-only apps that invoke a portrait-only view controller (such as the Game Center login screen) will cause the app to crash.


1.    Apps should provide the delegate method application:supportedIntefaceOrientationsForWindow and ensure that portrait is one of the returned mask values.

2.    When a UINavigationController is involved, subclass the UINavigationController and overriding supportedInterfaceOrientations.


  • Passes will no longer fall back to background.png if strip.png is not included in your pass bundle.
  • The contents of the userInfo dictionary for PKPassLibraryDidChangeNotification have changed in the case of removed passes. Please consult the latest documentation for the new userInfo dictionary.
  • Passes must include the WWDR Intermediate Certificate in their signature. Passes that omit this certificate are invalid and cannot be added to Passbook. This restriction was not enforced in previous beta releases.
  • Images included in passes that use RGB need to include an alpha channel.


  • No privacy alerts are displayed in iOS Simulator for apps that access Photos, Contacts, Calendar, and Reminders.
  • For this release, iOS Simulator does not support testing In-App Purchase. Please use a device to test your apps that use this feature.
  • When attempting to play an MP3 sound in Simulator, you will hear a popping sound instead.

Shared Photo Stream

  • The Shared Photo Stream feature is set to OFF when updating from iOS 6 beta 1 to a later release. The default setting should be ON.



UIRefreshControl in iOS6


All our clients want to have a basic functionality when its regarding the data display in the table view and that is having a spinner at it’s top. To do this you have the EGORefreshDemo that is available and is a little bit tricky to handle but is quite cool. 

In iOS 6 apple has been a little open hearted to provide you with a class named UIRefreshControl which is similar in fashion, so in this post we will have a look at the UIRefreshControl and will use it with a table view.
Step 1: Open you Xcode 4.5 and create an empty view based project and add a UITableViewController file to it that will have a list of various products. After you have done this then add your table view controller view in the app delegate and the run your project to see if you have got things right.
Step 2: After completing step no1 select your tableviewcontroller.h file and declare a global object of UIRefreshControl. 

Note: This class requires a call back method that will get triggered once you pull it so in simple terms we need a function, which we will assign to the UIRefreshControl and this function will be called when we pull our table to refresh it.

So now in your table view controller.h file you will be doing two things:
1. Creating a global object of the UIRefreshControl
2. Declaring a function that will be called when you pull the refresh control to refresh the table.
Step 3: Alright now after Step no 2 it’s time to switch to your tableviewcontroller.m file and select the view did load method where you will initialize the object of UIRefreshControl.
Code Explanation:I have used comments to make you understand the code.
After initializing the control it’s time to work on the callback method that would be associated with the UIRefreshControl.
Step 4: All set and done its time to run your project and see how it looks try pulling your table view and see apple’s new UIRefreshControl. Given below is the output for the same.
My Views on UIRefreshControl: After looking at this your client may or may not ask you to customize the UIRefreshControl class or stick with EGORefresh library, this class is available for iOS6 and not with any previous versions. But anyways its quite handly and less code is involved so it’s a good class by apple.
You may download the source code of this project from here.

Happy i coding

Create Horizontal UIPickerView (Custom)

So lets get started, first of all, all you need to do is drop a UIPickerView object on your view in the Interface Builder. Then in your .h file input:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIPickerViewDelegate> {

IBOutlet UIPickerView *pickerView;

NSMutableArray *itemArray;


@property (nonatomic, retain)  UIPickerView *pickerView;


Basically we’re just declaring our UIPickerView as IBOutlet (nothing new in declaration method here). We also added a NSMutableArray so that we can manipulate our items and be able to add our items in the pickerview easily later. We also add UIPickerViewDelegate at the interface because we will be using the built in Delegate functions of UIPickerView object.

Hang on a minute, what the heck is an NSMutableArray? If you are familiar with some basic programming I am sure that you are familiar with an array. An array is a defined quantity of collection of data. For eg:

myFish[14] holds 15 variables. from 0 to 14. (Remember index of an arrays always start with 0).
So you can access them by myFish[0] = Tetras; myFish[1] = Rasboras. And so on. But you are limited to 15 fishes. This is where NSMutableArray differs, an NSMutableArray is an array that is mutable, or expandable/changeable. So if you declare myFish as an NSMutableArray, then you can have up to whatever value you wish, so long as you be careful not to overload it (memory issues).

So now you have declared the UIPickerView, go to Interface Builder and connect BOTH the “delegate” and “Referencing Outlet” to the FileOwner.

Next, we go to .m file and synthesize the UIPickerView. Also we’d want to add the UIPickerView delegate methods as below (read the comments for each delegate’s purposes:

– (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {

return 1;


– (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {

return [itemArray count];


– (UIView *)pickerView:(UIPickerView *)thePickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view


return [itemArray objectAtIndex: row];


– (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {


This delegate is easy to implement, just type “return #;” where # is the number of components
you want. “Component” is the scrollable object in a pickerview. For example, a date pickerview has 3 components where user can select each of date, month and year. For our case, we are going to use just 1 component.

This delegate you need to return the number of items in each component. If you have multiple components,
you need to use switch (or if) statement to specify for each components. In our case we just have 1 component, so we only return the item count of our array.

This delegate is where you specify the “VIEW”/”Object” of the item. Since we store our items in
array, we just need to return the object by using: [itemArray objectAtIndex:row];

This delegate is always called when user selects an item. Write the actions you’d like to happen when user select something in here.

Remember that delegate functions must be written as it is, EXACTLY. Any deviation might cause it not to work. Do check Apple docs for the latest delegate function names in case your implementation does not work.

Next is the fun part, customizing the UIPickerView. We will add the customization code in the viewDidLoad as we want it to be customized after the view is loaded. Write the codes below in the viewDidLoad.

// set the pickerview delegate to itself. This is important because if you don’t set

// this, then the delegate functions will not work/be called.

self.pickerView.delegate = self;

// here is where the customization lies: CGAffineTransform is a way to transform

// object according to scale and rotation. Here we rotate the pickerview by PI/2

// which is 90 degrees in radians. Then we concat the rotation transform with

// scale transform, and finally setting the pickerview transform.

CGAffineTransform rotate = CGAffineTransformMakeRotation(3.14/2);

rotate = CGAffineTransformScale(rotate, 0.1, 0.8);

[self.pickerView setTransform:rotate];

// set the center location. = CGPointMake(160,75);

// Here I decided to add UILabel as the item’s “object”

// you can use ANYTHING here, like UIImageViews or any class of UIView

// Since we rotate the pickerview in one direction, we need to compensate

// the item’s angle by counter rotating it in the opposite direction,

// and adjust the scale as well. You may need to try a few times to get

// the right/suitable size as for the scale.

UILabel *theview[20];

CGAffineTransform rotateItem = CGAffineTransformMakeRotation(-3.14/2);

rotateItem = CGAffineTransformScale(rotateItem, 1, 10);

// next alloc and create the views in a loop. here I decided to have 20

// UIlabels, each with a text of 1 to 20. Set the other UIlabel’s property as you wish.

for (int i=1;i<=20;i++) {

theview[i] = [[UILabel alloc] init];

theview[i].text = [NSString stringWithFormat:@”%d”,i];

theview[i].textColor = [UIColor blackColor];

theview[i].frame = CGRectMake(0,0, 100, 100);

theview[i].backgroundColor = [UIColor clearColor];

theview[i].textAlignment = UITextAlignmentCenter;

theview[i].shadowColor = [UIColor whiteColor];

theview[i].shadowOffset = CGSizeMake(-1,-1);

theview[i].adjustsFontSizeToFitWidth = YES;

UIFont *myFont = [UIFont fontWithName:@”Georgia” size:15];

[theview[i] setFont:myFont];

theview[i].transform = rotateItem;


// then we initialize and create our NSMutableArray, and add all 20 UIlabel views

// that we just created above into the array using “addObject” method.

itemArray = [[NSMutableArray alloc] init];

for (int j=1;j<=20;j++) {

[itemArray addObject:theview[j]];


That is all there is to it. Run your app and it should display a nice horizontal UIPickerView!
How about have it do something when you select an item? Easy. Go back to .h and add another IBOutlet of UILabel *myLabel. Go to your XIB file in IB and add a label and connect the Outlet to FileOwner as myLabel. Goto .m file and synthesize myLabel. Then goto UIPickerView delegate called didSelectRow and add the following line:

  1. myLabel.text = [NSString stringWithFormat:@”SELECTED: %d”, row+1];

Now when you select a row, the label will show you which row you selected. Cool eh?

Happy iCoding


Get SIM card details of iPhone

Here is the code to get SIM card details of iPhone

1) Add CoreTelephony framework

2) Import following libraries

#import <CoreTelephony/CTCarrier.h>

#import <CoreTelephony/CTTelephonyNetworkInfo.h>

3) Use this code to get details

CTTelephonyNetworkInfo* info = [[CTTelephonyNetworkInfo alloc] init];

CTCarrier* carrier = info.subscriberCellularProvider;

NSString *carrierName = carrier.carrierName;

NSLog(@”carrier : %@”, carrier);

// Here are some parameters

//NSString *mobileCountryCode = carrier.mobileCountryCode;

//NSString *isoCountryCode = carrier.isoCountryCode;

//NSString *mobileNetworkCode = carrier.mobileNetworkCode;




Create php webservice in json format

$webid = $_GET[‘webid’];
$callback = $_REQUEST[‘callback’];

$sql = “SELECT * FROM `Restaurant_main` where `webid` = ‘$webid'”;
$result = mysql_query($sql)or die(mysql_error());
$row1 = mysql_fetch_array($result);
$db_webid = $row1[‘webid’];
if($db_webid == $webid){
$sql1 = “SELECT * FROM `Restaurant_main` where `webid` = ‘$webid'”;
$result1 = mysql_query($sql1)or die(mysql_error());

$response = array();
$posts = array();

$posts[] = array(‘Id’=> $id, ‘Name’=> $name,’email’=> $email,’website’=> $website,’img1’=> ‘’.$img1,’img2’=> ‘’.$img2);
if ($callback) {
header(‘Content-Type: text/javascript’);
echo $callback . ‘(‘ . json_encode($posts) . ‘);’;
} else {
header(‘Content-Type: application/x-json’);
echo json_encode($posts);

Note: use this as


Post Image on friends facebook wall

Note: Remember one thing image is a file and if you want to post a file on your friends wall then in that case you have to make use of a class named “FBGraphFile”.

– (IBAction)postImageButtonclicked:(id)sender
if (fbgraphref!=nil)
NSMutableDictionary *variables = [[NSMutableDictionaryalloc]initWithCapacity:2];
FbGraphFile *fbfile = [[FbGraphFile alloc]initWithImage:imgv.image];
[variables setObject:fbfile forKey:@”file”];
[variables setObject:@”iPhone by radix” forKey:@”message”];
[fbgraphref doGraphPost:[NSStringstringWithFormat:@”%@/photos”,self.friendID] withPostVars:variables];
UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:@”Alert”message:@”Data Posted on friends wall” delegate:nil cancelButtonTitle:@”OK”otherButtonTitles:nil];
[objAlert show];
[self.navigationController popToRootViewControllerAnimated:YES];
Code Explanation: In the above code i am using the class FBGraphFile and storing the image data that i want to send to my friends wall.
Then with the help of dictionary i am encapsulating the image and some text about the image.
Later with the help of the FBGraph object i am posting the image and the text data regarding that image  with the help of the method named doGraphPost also make a note that this time its not the feeds that i am using its the photo variable since we want to push a photo on our friends wall.
Now when everything is in place you may run the application.
Now select a friend from the list and when you do you will be navigated to the following screen.
Now when you tap on the Post Image button then the image which is currently selected by you will be posted on your friends facebook feeds.
Later you may login to your facebook account and check your friends wall just in case to see if the image is loaded or not
You can download the source file from here.

Android Read Excel File from Website and display using a ListView

n this example we start the activity by making a HTTP request to read the Excel file hosted on a Web Server. We take help of the AsyncTask to fetch the data in background from the Excel file using the URL pointing to it. The input stream from the file is then parsed using the Apache POI classes and stored in an ArrayList. After the AsyncTask is completed, basically the complete Excel file is downloaded and parsed it is then displayed using a ListView.

Android Activity –

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import android.widget.ArrayAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.ListView;
import android.widget.Toast;

public class ReadExcelFromUrlActivity extends Activity {

private String LOG_TAG = "ReadExcelFromUrl";
ArrayList shoppingCartList;

public void onCreate(Bundle savedInstanceState) {

//URL path for the Excel file
String url = "";


private void displayCart() {

//Array list of countries
List myList = new ArrayList();
for(int i = 0, l = shoppingCartList.size(); i < l; i++){
ShoppingCart shoppingCart = shoppingCartList.get(i);
String myData = shoppingCart.getItemNumber() + ": " +
shoppingCart.getDescription() + "nPrice: $" +
shoppingCart.getPrice() + "nQuantity: " +

//Display the Excel data in a ListView
ArrayAdapter dataAdapter = new ArrayAdapter(this,
R.layout.data_list, myList);
ListView listView = (ListView) findViewById(;


public void excelURL(String url) {
Log.v(LOG_TAG, url);
new ExcelURL().execute(url);

private class ExcelURL extends AsyncTask {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
private String content = null;
private ProgressDialog dialog = new ProgressDialog(ReadExcelFromUrlActivity.this);

protected void onPreExecute() {
dialog.setMessage("Getting your data... Please wait...");;

protected String doInBackground(String... urls) {

String URL = null;

try {

URL = urls[0];
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

HttpGet httpGet = new HttpGet(URL);
response = httpclient.execute(httpGet);

StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
} else{
//Closes the connection.
throw new IOException(statusLine.getReasonPhrase());
} catch (ClientProtocolException e) {
Log.w("HTTP2:",e );
content = e.getMessage();
} catch (IOException e) {
Log.w("HTTP3:",e );
content = e.getMessage();
}catch (Exception e) {
Log.w("HTTP4:",e );
content = e.getMessage();

return content;

protected void onCancelled() {
Toast toast = Toast.makeText(ReadExcelFromUrlActivity.this,
"Error connecting to Server", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);;


protected void onPostExecute(String content) {

private void parseExcel(InputStream fis){

shoppingCartList = new ArrayList();


// Create a workbook using the Input Stream
HSSFWorkbook myWorkBook = new HSSFWorkbook(fis);

// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);

// We now need something to iterate through the cells
Iterator rowIter = mySheet.rowIterator();

HSSFRow myRow = (HSSFRow);
// Skip the first 2 rows
if(myRow.getRowNum() < 2) {

ShoppingCart shoppingCart = new ShoppingCart();

Iterator cellIter = myRow.cellIterator();

HSSFCell myCell = (HSSFCell);
String cellValue = "";

// Check for cell Type
if(myCell.getCellType() == HSSFCell.CELL_TYPE_STRING){
cellValue = myCell.getStringCellValue();
else {
cellValue = String.valueOf(myCell.getNumericCellValue());

// Just some log information
Log.v(LOG_TAG, cellValue);

// Push the parsed data in the Java Object
// Check for cell index
switch (myCell.getColumnIndex()) {
case 0:
case 1:
case 2:
case 3:


// Add object to list
catch (Exception e){



Shopping cart Java object –

public class ShoppingCart {

String itemNumber = null;
String description = null;
Double price = null;
Double quantity = null;

public String getItemNumber() {
return itemNumber;
public void setItemNumber(String itemNumber) {
this.itemNumber = itemNumber;
public String getDescription() {
return description;
public void setDescription(String description) {
this.description = description;
public Double getPrice() {
return price;
public void setPrice(Double price) {
this.price = price;
public Double getQuantity() {
return quantity;
public void setQuantity(Double quantity) {
this.quantity = quantity;


Android Manifest file

Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box