Saturday, August 31, 2013

Bind service using IBinder class

There are total 3 ways to bind a service with application components

  1. Using IBinder class
  2. Using Messanger class
  3. Using AIDL
This post is for explain about IBinder class 

To implement IBinder class there are following steps

Steps for service
  1. Create a new Project name "BindServiceUsingBinderClass
  2. Create one Service in your application by extending the Service class 
  3. Create a class "LocalBinder" inside your service and extends "Binder" class in this class
  4. Implement the onBind() method of the service and return the instance of the "LocalBinder" class
Steps for activity

  1. Create one activity "Client" and create a instance of the "ServiceConnection" Interface
  2. Implement two methods of this interface onServiceConnectedand onServiceDisconnected
  3. In  onServiceConnected method you will get instance of the iBinder so cast it to LocalBinder class which we have created in the service.
  4. Implement onStart() method and bind the service using bindService() method
  5. Implement onStop() method and unbind the service using unbindService()method
Source code of the IBinder class

Server.java
package com.example.bindservice.binder;

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

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class Server extends Service{

 IBinder mBinder = new LocalBinder();

 @Override
 public IBinder onBind(Intent intent) {
  return mBinder;
 }

 public class LocalBinder extends Binder {
  public Server getServerInstance() {
   return Server.this;
  }
 }

 public String getTime() {
  SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  return mDateFormat.format(new Date());
 }
}

Client.java

package com.example.bindservice.binder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bindservice.binder.Server.LocalBinder;

public class Client extends Activity {

 boolean mBounded;
 Server mServer;
 TextView text;
 Button button;
 
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        text = (TextView)findViewById(R.id.text);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
   
   public void onClick(View v) {
    text.setText(mServer.getTime());
   }
  });
    }

 @Override
 protected void onStart() {
  super.onStart();
  Intent mIntent = new Intent(this, Server.class);
        bindService(mIntent, mConnection, BIND_AUTO_CREATE);
 };
 
 ServiceConnection mConnection = new ServiceConnection() {
  
  public void onServiceDisconnected(ComponentName name) {
   Toast.makeText(Client.this, "Service is disconnected", 1000).show();
   mBounded = false;
   mServer = null;
  }
  
  public void onServiceConnected(ComponentName name, IBinder service) {
   Toast.makeText(Client.this, "Service is connected", 1000).show();
   mBounded = true;
   LocalBinder mLocalBinder = (LocalBinder)service;
   mServer = mLocalBinder.getServerInstance();
  }
 };
 
 @Override
 protected void onStop() {
  super.onStop();
  if(mBounded) {
   unbindService(mConnection);
   mBounded = false;
  }
 };
}

Thursday, August 29, 2013

Input Field Validation

activity_main.xml
------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"    
    tools:context=".MainActivity" >
 <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_normal_text"
            android:hint="Enter Normal Text"
            android:inputType="text"
            android:textStyle="bold"/>

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_email_address"
            android:textStyle="bold"
            android:inputType="textEmailAddress"
            android:hint="Enter Email Address"/>

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_phone_number"
            android:hint="Enter Phone Number"
            android:inputType="phone"
            android:textStyle="bold"/>

    <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Submit"
            android:id="@+id/btn_submit" />
</LinearLayout>


Validation.java
-----------------
package com.example.inputfieldvalidation;
import android.widget.EditText;
import java.util.regex.Pattern;
public class Validation {
// Regular Expression
    // you can change the expression based on your need
    private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private static final String PHONE_REGEX = "\\d{3}-\\d{7}";
 
    // Error Messages
    private static final String REQUIRED_MSG = "required";
    private static final String EMAIL_MSG = "invalid email";
    private static final String PHONE_MSG = "###-#######";
 
    // call this method when you need to check email validation
    public static boolean isEmailAddress(EditText editText, boolean required) {
        return isValid(editText, EMAIL_REGEX, EMAIL_MSG, required);
    }
 
    // call this method when you need to check phone number validation
    public static boolean isPhoneNumber(EditText editText, boolean required) {
        return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
    }
 
    // return true if the input field is valid, based on the parameter passed
   /* public static boolean isValid(EditText editText, String regex, String errMsg, boolean required) {
 
        String text = editText.getText().toString().trim();
        // clearing the error, if it was previously set by some other values
        editText.setError(null);
 
        // text required and editText is blank, so return false
        if ( required && !hasText(editText) ) return false;
 
        // pattern doesn't match so returning false
        if (required && !Pattern.matches(regex, text)) {
            editText.setError(errMsg);
            return false;
        };
 
        return true;
    }*/
    public static boolean isValid(EditText editText, String regex, String errMsg, boolean bRequired) {
    // text required and editText is blank, so return false
    String sText = editText.getText().toString().trim();
    // clearing the error, if it was previously set by some other values
    editText.setError(null);
    if (sText.length() == 0) {
    if (bRequired) {
    editText.setError(REQUIRED_MSG);
    return false;
    }
    } else {
    // filled field
    // pattern doesn’t match so returning false
    if (!Pattern.matches(regex, sText)) {
    editText.setError(errMsg);
    return false;
    }
    }
    return true;
    }
 
    // check the input field has any text or not
    // return true if it contains text otherwise false
    public static boolean hasText(EditText editText) {
 
        String text = editText.getText().toString().trim();
        editText.setError(null);
 
        // length 0 means there is no text
        if (text.length() == 0) {
            editText.setError(REQUIRED_MSG);
            return false;
        }
 
        return true;
    }
}


MainActivity.java
--------------------
package com.example.inputfieldvalidation;

import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
private EditText etNormalText;
   private EditText etEmailAddrss;
   private EditText etPhoneNumber;
   private Button btnSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerViews();
}

private void registerViews() {
etNormalText = (EditText) findViewById(R.id.et_normal_text);
       // TextWatcher would let us check validation error on the fly
       etNormalText.addTextChangedListener(new TextWatcher() {
           public void afterTextChanged(Editable s) {
               Validation.hasText(etNormalText);
           }
           public void beforeTextChanged(CharSequence s, int start, int count, int after){}
           public void onTextChanged(CharSequence s, int start, int before, int count){}
       });
 
       etEmailAddrss = (EditText) findViewById(R.id.et_email_address);
       etEmailAddrss.addTextChangedListener(new TextWatcher() {
           // after every change has been made to this editText, we would like to check validity
           public void afterTextChanged(Editable s) {
               Validation.isEmailAddress(etEmailAddrss, true);
           }
           public void beforeTextChanged(CharSequence s, int start, int count, int after){}
           public void onTextChanged(CharSequence s, int start, int before, int count){}
       });
 
       etPhoneNumber = (EditText) findViewById(R.id.et_phone_number);
       etPhoneNumber.addTextChangedListener(new TextWatcher() {
           public void afterTextChanged(Editable s) {
               Validation.isPhoneNumber(etPhoneNumber, false);
           }
           public void beforeTextChanged(CharSequence s, int start, int count, int after){}
           public void onTextChanged(CharSequence s, int start, int before, int count){}
       });
 
       btnSubmit = (Button) findViewById(R.id.btn_submit);
       btnSubmit.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               /*
               Validation class will check the error and display the error on respective fields
               but it won't resist the form submission, so we need to check again before submit
                */
               if ( checkValidation () )
                   submitForm();
               else
                   Toast.makeText(MainActivity.this, "Form contains error", Toast.LENGTH_LONG).show();
           }
       });
   }
 
   private void submitForm() {
       // Submit your form here. your form is valid
       Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
   }
 
   private boolean checkValidation() {
       boolean ret = true;
 
       if (!Validation.hasText(etNormalText)) ret = false;
       if (!Validation.isEmailAddress(etEmailAddrss, true)) ret = false;
       if (!Validation.isPhoneNumber(etPhoneNumber, false)) ret = false;
 
       return ret;
   }
}

Screens
----------

 

 



Sunday, August 25, 2013

NotificationManager

package com.example.notificationactivity;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
Button btn;
private static final int NOTE_ID=100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
handler.postDelayed(task, 1000);
Toast toast=Toast.makeText(getApplicationContext(), "notification will be displayed in 10 sec.",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
});
}
Handler handler=new Handler();
private Runnable task=new Runnable() {

@Override
public void run() {
NotificationManager manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
NotificationCompat.Builder builder=new NotificationCompat.Builder(MainActivity.this);
builder.setSmallIcon(R.drawable.ic_launcher) 
            .setTicker("Something Happened") 
            .setWhen(System.currentTimeMillis()) 
            .setAutoCancel(true) 
            .setDefaults(Notification.DEFAULT_SOUND) 
            .setContentTitle("We're Finished!") 
            .setContentText("Click Here!") 
            .setContentIntent(pi); 
       
       /* builder.addAction(R.drawable.ic_launcher, "Call Back", pi); 
        builder.addAction(R.drawable.ic_launcher, "Call History", pi); 
        NotificationCompat.BigTextStyle expandedStyle = 
                new NotificationCompat.BigTextStyle(builder); 
        expandedStyle.bigText("Here is some additional text to be displayed when" 
            + " the notification is in expanded mode.  " 
            + " I can fit so much more content into this giant view!"); */
NotificationCompat.InboxStyle expandedStyle = 
           new NotificationCompat.InboxStyle(builder); 
   expandedStyle.setSummaryText("4 New Tasks"); 
   expandedStyle.addLine("Make Dinner"); 
   expandedStyle.addLine("Call Mom"); 
   expandedStyle.addLine("Call Wife First"); 
   expandedStyle.addLine("Pick up Kids"); 
 
  // Notification note = expandedStyle.build(); 
        Notification note = builder.build(); 
        //Post the notification 
        manager.notify(NOTE_ID, note);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Custom Toast

Toast toast=Toast.makeText(getApplicationContext(), "notification will be displayed in 10 sec.",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();

Thursday, August 8, 2013

Servlet+MySql+Android

MySql Database
------------------
+----------+------------------+-----------------+------------+----------+----------+
| event_id | event_name       | event_desc      | e_date     | e_time   | e_img    |
+----------+------------------+-----------------+------------+----------+----------+
|      101 | fifa world cup   | postponed       | 2014/06/03 | 02:00 PM | img1.jpg |
|      102 | Durand CUP       | Coming Soon     | NULL       | NULL     | img2.jpg |
|      103 | champions trophy | played in japan | 2014/02/05 | 03:00 PM | img3.jpg |
+----------+------------------+-----------------+------------+----------+----------+

Images
---------
WebContent->img
img1.jpg
img2.jpg
img3.jpg

Server Side Servlet
==============
Qfa_Events.java
-------------------
package com.mangium.qfa;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mysql.jdbc.Connection;


public class Qfa_Events extends HttpServlet {

private static final long serialVersionUID = 1L;
 Connection con = null;  
 Statement stmt = null;
 ResultSet rs = null;
 String name=null;
 String des=null;
 String date=null;
 String time=null;
 String img = null;
 String[] line=null;
public void service(HttpServletRequest request, HttpServletResponse response)
 throws IOException, ServletException{
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
/* out.println("Hello Servlet !!!!");
 out.println("<html>");
 out.println("<head><title>events</title></head>");
 out.println("<body>");
 out.println("<h1>Database Results</h1>");
 out.println("</body></html>");*/  
 // connecting to database
 
 try {
 Class.forName("com.mysql.jdbc.Driver");
 con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/qfa", "root", "root");
 stmt =  con.createStatement();
 rs = stmt.executeQuery("SELECT event_id,event_name,event_desc,e_date,e_time,e_img FROM events");
 // displaying records
 
  int i=0;
           JSONArray jArray = new JSONArray();

 while(rs.next()){

 int id=rs.getInt("event_id");
 name=rs.getString("event_name");
 des=rs.getString("event_desc");
 date=rs.getString("e_date");
 time=rs.getString("e_time");
 img=rs.getString("e_img");
   /*  out.println("<img src='img/"+img+"' width='60' height='60'/>"+"</br>");
 out.println("Image:"+ img +"</br>");
 out.println("Id:"+ id +"</br>");
 out.println("Name:"+ name +"</br>");
 out.println("Description:"+ des +"</br>");
 out.println("Date:"+ date +"</br>");
 out.println("Time:"+ time +"</br>");
 out.println("--------------------------------------"+"</br>");*/

 JSONObject json=new JSONObject();  
 json.put("name", name);
 json.put("description", des);
 json.put("date", date);
 json.put("time", time);
 json.put("image", img);
 jArray.put(i,json);
       i++;

 
 }
 JSONObject jobj=new JSONObject();
jobj.put("events", jArray);
 out.println(jobj.toString());
 

  
 } catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
 } catch (ClassNotFoundException e) {
 throw new ServletException("JDBC Driver not found.", e);

} finally {
 try {
 if(rs != null) {
 rs.close();
 rs = null;
 }
 if(stmt != null) {
 stmt.close();
 stmt = null;
 }
 if(con != null) {
 con.close();
 con = null;
 }
 } catch (SQLException e) {}
 }
 out.close();
 }

 }

Extra jars
------------
json-lib-2.4-jdk15.jar
mysql-connector-java-5.1.25-bin.jar
json-rpc-1.0.jar

web.xml
----------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>QFA_Server</display-name>
  <servlet>
    <servlet-name>events</servlet-name>
    <servlet-class>com.mangium.qfa.Qfa_Events</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>events</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
  <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

index.html
------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Refresh" content="2;URL=*.do" >
<title>Insert title here</title>
</head>
<body>
<h1>Loading...</h1>
</body>
</html>

Client Side Android
===============
activity_main.xml
---------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load Servlet" />

  

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Event_name" 
        android:textColor="#C71585"/>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"       
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Display ListView" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

image_view.xml
---------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/nameView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" 
        android:layout_marginTop="20dip"
        android:layout_marginLeft="20dip"
        android:textColor="#C71585"/>

</LinearLayout>


MainActivity.java
--------------------
package com.mangium.qfa_project;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
Button btn,btn2;
static TextView tv;
static ImageView iv;
static ListView lv;
public static final String URL="http://192.168.1.129:8080/QFA_Server/*.do";
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.textView1);
iv=(ImageView) findViewById(R.id.imageView1);
lv=(ListView) findViewById(R.id.listView1);
btn=(Button) findViewById(R.id.button1);
btn2=(Button) findViewById(R.id.button2);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
GetJSONData task = new GetJSONData();
       task.execute(new String[] { URL });
       Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
     
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
lv.setAdapter(new MyImageAdapter(getApplicationContext(),GetJSONData.nameID,GetJSONData.imageID));
}
});
 
}
}

GetJSONData.java
-----------------------
package com.mangium.qfa_project;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint.Join;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;

public class GetJSONData extends AsyncTask<String, Void, String> {
String[] str=null;
String Enent_name=null;
String Enent_img=null;
String Image_path="http://192.168.1.129:8080/QFA_Server/img/";
static Bitmap mIcon=null;
static Bitmap mIcon1=null;
static Bitmap mIcon2=null;
static String[] nameID;
static String[] imageID;
    @Override
    protected String doInBackground(String... urls) {
        String output = null;
        for (String url : urls) {
          
output = getOutputFromUrl(url);
        }
        
        
        try {
            InputStream in = new java.net.URL(Image_path+imageID[0]).openStream();
             mIcon = BitmapFactory.decodeStream(in);
             InputStream in1 = new java.net.URL(Image_path+imageID[1]).openStream();
             mIcon1 = BitmapFactory.decodeStream(in1);
             InputStream in2 = new java.net.URL(Image_path+imageID[2]).openStream();
             mIcon2 = BitmapFactory.decodeStream(in2);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
       
        
        return output;
    }

    private String getOutputFromUrl(String url)  {
        String output = null;
        try {
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            output = EntityUtils.toString(httpEntity);
            System.out.println(output);
           try {
JSONObject jobj=new JSONObject(output);
JSONArray jarray=jobj.getJSONArray("events");
nameID=new String[jarray.length()];
imageID=new String[jarray.length()];
JSONObject jobject=null;
for(int i=0;i<=jarray.length();i++){
jobject=jarray.getJSONObject(i);
 
Enent_name=jobject.getString("name");
Enent_img=jobject.getString("image");
nameID[i]=jobject.getString("name");
imageID[i]=jobject.getString("image");
}
System.out.println("*****"+Enent_name);
System.out.println("*****"+imageID[1]);

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}    
         
           
         
            
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return output;
    }

    @Override
    protected void onPostExecute(String output) {
    MainActivity.tv.setText("Event Name: " + nameID[0]);            
   
    MainActivity.iv.setImageBitmap(mIcon);  
   
    }


}

MyImageAdapter.java
-------------------------
package com.mangium.qfa_project;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyImageAdapter extends BaseAdapter  {
Context context;
String[] nameID;
String[] imageID;
public MyImageAdapter(Context context, String[] nameID, String[] imageID) {
// TODO Auto-generated constructor stub
this.context=context;
this.nameID=nameID;
this.imageID=imageID;
}


@Override
public int getCount() {
// TODO Auto-generated method stub
return nameID.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.image_view, parent,false);
TextView name=(TextView) rowView.findViewById(R.id.nameView);
ImageView iv=(ImageView) rowView.findViewById(R.id.imageView1);
name.setText(nameID[position]);
String str1=nameID[position];
if(str1.startsWith("fifa world cup")){
//iv.setImageResource(R.drawable.ic_launcher);
iv.setImageBitmap(GetJSONData.mIcon);
}
if(str1.startsWith("Durand CUP")){
//iv.setImageResource(R.drawable.ic_launcher);
iv.setImageBitmap(GetJSONData.mIcon1);
}
if(str1.startsWith("champions trophy")){
//iv.setImageResource(R.drawable.ic_launcher);
iv.setImageBitmap(GetJSONData.mIcon2);
}
return rowView;
}

}