Friday, May 29, 2015

Android ViewPager (SWIPE)

Hi guys Today I am going to show you how to use ViewPager as a image slide gallery. In this example you can swipe left or right to view image.
ViewPagers have built-in swipe gestures to transition through pages, and they display screen slide animations by default. ViewPagers  use PagerAdapters as a supply for new pages to display. 
I simply put the images to drawable folder and display on it ViewPager
Swipe Image Gallery By ViewPager:





 





















First you need to create the PagerAdapter.

ImageAdapter.java 

import android.content.Context;

import android.support.v4.view.PagerAdapter;

import android.support.v4.view.ViewPager;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ImageView;



public class ImageAdapter extends PagerAdapter {

    Context context;

    private int[] GalImages = new int[] {

        R.drawable.a,

        R.drawable.b,

        R.drawable.c,

        R.drawable.d,

        R.drawable.e,



    };

    ImageAdapter(Context context){

        this.context=context;

    }

    @Override

    public int getCount() {

      return GalImages.length;

    }



    @Override

    public boolean isViewFromObject(View view, Object object) {

      return view == ((ImageView) object);

    }



    @Override

    public Object instantiateItem(ViewGroup container, int position) {

      ImageView imageView = new ImageView(context);

      //int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);

      //imageView.setPadding(padding, padding, padding, padding);

      //imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

      imageView.setImageResource(GalImages[position]);

      ((ViewPager) container).addView(imageView, 0);

      return imageView;

    }



    @Override

    public void destroyItem(ViewGroup container, int position, Object object) {

      ((ViewPager) container).removeView((ImageView) object);

    }

  }


Then create the xml file and add the ViewPager in layout.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
   
          <android.support.v4.view.ViewPager
          android:id="@+id/view_pager"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />

</RelativeLayout> 

Then create main Activity and create the instance of ViewPager

import android.app.Activity;

import android.os.Bundle;

import android.support.v4.view.ViewPager;



public class MainActivity extends Activity {

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);



    ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);

    ImageAdapter adapter = new ImageAdapter(this);

    viewPager.setAdapter(adapter);

  }


 
}

Stay Tune for next session happy coding :)

Adapters in Android

Adapters in android is like our mobile charging adapter to connect your device and get charge.Imagine what would have been the smartphone without adapters! definitely your smartphones battery gets blast! :)
Adapters in android act as bridge between the view (eg. ListView) and flow of input data for that Views.

 Just think for few seconds WHAT IF Adapter is not there?
Without Adapters, to implement the listview functionality, you will need to:
  1. create a TextView within a ScrollView group.
  2. Then you will have to implement pagination concept for the contents of the TextView.
  3. You will also have to write additional code to identify the click event on a particular row in the TextView. 
Quite cumbersome job! Isn’t it?

Below is a conceptual diagram which shows the high level working of the Android Adapter:

 


Let us now understand the internal working of an Android Adapter and how it acts as a data pump to the adapter view.
Adapters call the getView() method which returns a view for each item within the adapter view. The layout format and the corresponding data for an item within the adapter view is set in the getView() method. Now, it will be a performance nightmare if getView() returns a new View every time it is called. Creating a new view is very expensive in Android as you will need to loop through the view hierarchy (using the find ViewbyID () method) and then inflate the view to finally display it on the screen.It also puts a lot of pressure on the garbage collector. That is because when the user is scrolling through the list, if a new view is created; the old view (since it is not recycled) is not referenced and becomes a candidate to be picked up by the garbage collector. So what Android does is that it recycles the views and reuses the view that goes out of focus.

Below is a visual representation of this recycle process:

 


In the above figure, let us assume we are displaying the months in a year in a ListView. To begin with, the months January till May are shown in the screen. When you scroll the view, the month January goes out of the display area of the mobile screen. As soon as the January view goes out of the screen, the Adapter View (ListView in this case) sends the view to something called a recycler.So when you scroll up, the getView () method is called to get the next view (which is June). This method getView() has a parameter called convertview which points to the unused view in the recycler. Through the convertview, the Adapter tries to get hold of the unused view and reuse it to display the new view (which is June in this case).

So, when you are creating a custom Adapter View, you should code your
getView () as mentioned below:

@Override
 public View getView(int position, View convertView, ViewGroup parent) {

  ViewHolder holder = null;

  LayoutInflater mInflater = (LayoutInflater) context
    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
  if (convertView == null) {
   convertView = mInflater.inflate(R.layout.mangmt_list_item, null);
   holder = new ViewHolder();

   holder.member_name = (TextView) convertView
     .findViewById(R.id.member_name);
   holder.profile_pic = (ImageView) convertView
     .findViewById(R.id.profile_pic);
   holder.status = (TextView) convertView.findViewById(R.id.status);
   holder.contactType = (ImageView) convertView
     .findViewById(R.id.contact_type);

   ManagementRowItem row_pos = managementRowItems.get(position);

   holder.profile_pic.setImageResource(row_pos.getProfile_pic_id());
   holder.member_name.setText(row_pos.getMember_name());
   holder.status.setText(row_pos.getStatus());
   holder.contactType.setImageResource(row_pos.getContactType_id());

   convertView.setTag(holder);
  } else {
   holder = (ViewHolder) convertView.getTag();
  }

  return convertView;
 }
 


above content refer from  Edureka.co

stay tune happy coding :)


Sunday, May 17, 2015

Android Rating Bar & Toggle button

                        

In this tutorial we are creating Rating bar and some other basic components as Toggle button, Check Box. In rating bar we accepted user rating and displayed the rating as a Toast message.

This RatingBar we can create by two technics here
  1. using button click listner we can call getRating() method .
i.e

buttonrate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String s = String.valueOf(rb1.getRating()) ;
                Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();
            }
        });

    2. implement OnRatingBarChangeListener to accept user rating and display it as a Toast message.
 i.e.

rb1.setOnRatingBarChangeListener(this);

 //implements OnRatingBarChangeListener methods.

@Override
    public void onRatingChanged(RatingBar ratingBar, float rating,
            boolean fromUser) {
        // TODO Auto-generated method stub
         Toast.makeText(MainActivity.this, "New Rating: " + rating,
                    Toast.LENGTH_SHORT).show();
       
       
    } 
Here, the rating bar is registered to the android.widget.RatingBar.OnRatingBarChangeListener using the method ratingbar.setOnRatingBarChangeListener(). When the event (user clicking on rating bar) occurs it calls onRatingChanged() method. For simplicity, we display a Toast message with user’s rating.


 activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#CCFF66"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.torach.MainActivity" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Kindly Check the following : "
        android:layout_centerHorizontal="true"/>
   
    <ToggleButton
        android:id="@+id/tb"
        android:layout_below="@id/tv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true"/>
    <Button
        android:id="@+id/b1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@id/tb"
        android:layout_centerHorizontal="true"
        android:text="Toggle it"/>
   
 <CheckBox
        android:id="@+id/cb"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@id/b1"
        android:layout_centerHorizontal="true"
        android:text="Enable"
        android:layout_marginTop="35dip"/>
    <Button
        android:id="@+id/b2"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@id/cb"
        android:layout_centerHorizontal="true"
        android:text="Check" />
 
    <RatingBar
        android:id="@+id/rb"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@id/b2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dip"/>
    <Button
        android:id="@+id/b3"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@id/rb"
        android:layout_centerHorizontal="true"
        android:text="Rate"
        />
</RelativeLayout>

 

 MainActivity.java

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends ActionBarActivity implements OnRatingBarChangeListener {

    ToggleButton tb1;
    RatingBar rb1;
    CheckBox cb1;
    Button bt1, bt2, bt3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tb1 = (ToggleButton) findViewById(R.id.tb);
        rb1 = (RatingBar) findViewById(R.id.rb);
        rb1.setOnRatingBarChangeListener(this);
        cb1 = (CheckBox) findViewById(R.id.cb);
        bt1 = (Button) findViewById(R.id.b1);
        bt2 = (Button) findViewById(R.id.b2);
        bt3 = (Button) findViewById(R.id.b3);

        bt1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String s = (String)tb1.getText();
                Toast.makeText(getApplicationContext(), "Button is : " +s, Toast.LENGTH_LONG).show();
            }
        });
        bt2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                StringBuffer sb = new StringBuffer();
                sb.append("Button is : ").append(cb1.isChecked());
                Toast.makeText(getApplicationContext(), sb.toString(), Toast.LENGTH_LONG).show();
            }
        });
        bt3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String s = String.valueOf(rb1.getRating()) ;
                Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();
            }
        });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating,
            boolean fromUser) {
        // TODO Auto-generated method stub
         Toast.makeText(MainActivity.this, "New Rating: " + rating,
                    Toast.LENGTH_SHORT).show();
       
       
    }
}

 

AndroidManifest.xml

 

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

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

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

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

</manifest>

Output Screenshot.


stay tune for next session happy coding :)



 

Android Tab View

                      Creating Android TabView Application

This article will walk through creating a tabbed UI in Android.Android using the TabHost API. This is an older API that is available in all versions of Android. This example will create an application with five tabs, with the logic for each tab being encapsulated in an Activity. The following screenshot is an example of the application that we will create:




















Creating the Application:
1. First lets create the activity_main.xml file. that will host the tabs.

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp" />
    </LinearLayout>
</TabHost>

    The TabHost must have two child views inside it: a TabWidget and a FrameLayout. To position the TabWidget and FrameLayout vertically inside the TabHost, a LinearLayout is used. The FrameLayout is where the content for each tab goes, which is empty because the TabHost will automatically embed each Activity at runtime.
    There are several rules that must be observed when it comes to creating the layout for tabbed user interfaces:
  1. The TabHost must have the id @android:id/tabhost.
  2. The TabWidget must have the id @android:id/tabs.
  3. The FrameLayout must have the id @android:id/tabcontent.
  4. TabHost requires any activity it manages to inherit from TabActivity. Therefore, it is important to subclass TabActivity here - a regular Activity will not work.

    now creat the MainActivity.java file .

    MainActivity.java

    import android.app.TabActivity;
    import android.content.Intent;
    import android.content.res.Resources;
    import android.os.Bundle;
    import android.view.Menu;
    import android.widget.TabHost;
    import android.widget.TabHost.TabSpec;

    public class MainActivity extends TabActivity
    {

        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           
            Resources ressources = getResources();
           
            TabHost tabHost = getTabHost();

          
            // Android tab
            Intent intentAndroid = new Intent(this, AnimalA.class);
            TabSpec tabSpecAndroid = tabHost
                .newTabSpec("Animal A")
                .setIndicator("Animal A", ressources.getDrawable(R.drawable.a))
                .setContent(intentAndroid);

            // Apple tab
            Intent intentApple = new Intent(this, AnimalB.class);
            TabSpec tabSpecApple = tabHost
                .newTabSpec("Animal")
                .setIndicator("Animal", ressources.getDrawable(R.drawable.b))
                .setContent(intentApple);
          
            // Windows tab
            Intent intentWindows = new Intent(this, AnimalD.class);
            TabSpec tabSpecWindows = tabHost
                .newTabSpec("Animal")
                .setIndicator("", ressources.getDrawable(R.drawable.d))
                .setContent(intentWindows);
          
            // Blackberry tab
            Intent intentBerry = new Intent(this, AnimalC.class);
            TabSpec tabSpecBerry = tabHost
                .newTabSpec("Animal")
                .setIndicator("", ressources.getDrawable(R.drawable.e))
                .setContent(intentBerry);
          
            Intent intentBerry1 = new Intent(this, AnimalC.class);
            TabSpec tabSpecBerry1 = tabHost
                .newTabSpec("Animal")
                .setIndicator("", ressources.getDrawable(R.drawable.f))
                .setContent(intentBerry1);
       
            // add all tabs
            tabHost.addTab(tabSpecAndroid);
            tabHost.addTab(tabSpecApple);
            tabHost.addTab(tabSpecWindows);
            tabHost.addTab(tabSpecBerry);
            tabHost.addTab(tabSpecBerry1);

          
            //set Windows tab as default (zero based)
            tabHost.setCurrentTab(3);
        }

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


    Now, all you need to do is create a FragmentActivity to accommodate your tabs fragment.

    Here I will give you  the first tab as AnimalA.java activity and deer.xml . you need to make all other  activities for each tab.

    following class shows first tab activity.

    AnimalA.java
    import android.app.Activity;
    import android.os.Bundle;

    public class AnimalA extends Activity
    {
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
           
            setContentView(R.layout.deer);
        }
    }

    deer.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:background="#ffffff"
        android:gravity="center" >
       
        <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/deer"
            >
        </ImageView>
    </LinearLayout>

    follow same for remaining tab so you will get all tabs Activity by doing above same.

    With that, your job is pretty much done. You can see  in the screenshot the result.




stay tune for next session happy coding :)


Thursday, May 14, 2015

Android Broadcastingreceiver

                                            Creating Broadcast receiver  


Android Broadcastreceiver is the android component where you can register for 
system level or Application level events.these events you will be notified after registering.
Broadcastreceiver originating from two aspects.
  • System level.   eg. Battery Low Notifications.
  • Application level.  eg. Application level is like when you download mp3 file, mp3 player gets notified about it and gets added to player list. Other examples of Broadcast Receiver from applications are new friend notifications, new friend feeds, new message etc.
Notifications like incoming messages, wi-fi, and Bluetooth activation signal, new wi-fi in the range, low battery signal are the real time examples of the BroadcastReceiver. Thus BroadcastReceiver are everywhere in the android system.
There are two ways to register android broadcastreceivers.

  • static way in which the broadcastreceiver is registered in an android application via AndroidManifest.xml . Use <receiver> tag in your Manifest files (AndroidManifest.xml).
  • Another way of registering the broadcast receiver is dynamic, which is done using Context.registerReceiver() method. Dynamically registered broadcast receivers can be unregistered using Context.unregisterReceiver() method. 
 Block Diagram of the system:

 Implementation:
A broadcast receiver extends BroadcastReceiver abstract class. Which means that we have to implement the onReceive() method of this base class. Whenever the event occurs Android calls the onReceive() method on the registered broadcast receiver. For example, if you register for ACTION_POWER_CONNECTED event then whenever power got connected to the device, your broadcast receiver’s onReceive() method will be invoked.

Main.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

public class Main extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
    }
    public void broadcastCustomIntent(View view)
    {
       Intent intent = new Intent("MyCustomIntent");

       EditText et = (EditText)findViewById(R.id.extraIntent);
       // add data to the Intent
       intent.putExtra("message", (CharSequence)et.getText().toString());
       intent.setAction("com.broadcastreceiver.A_CUSTOM_INTENT");
       sendBroadcast(intent);
    }
 }

In above main activity class we broadcast an event with input message from user.
intent.setAction() methode can call this broadcast intent.

main.xml

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

    <EditText android:id="@+id/extraIntent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/sendMessage" />

   <Button
       android:id="@+id/btnStartBroadcast"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_below="@+id/extraIntent"
       android:onClick="broadcastCustomIntent"
       android:text="@string/myBroadcastIntent" />

</RelativeLayout>

Above code snippet is for Material design for getting input from user with button.
button having onClick methode to performe the event.

MyBroadcastReceiver.java


 import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

                // Extract data included in the Intent
                CharSequence intentData = intent.getCharSequenceExtra("message");  
                Toast.makeText(context, "received the Intent's message: "+intentData, Toast.LENGTH_LONG).show();
      
    }

}

from AndroidManifest file we get receiver class to receive event.so above MyBroadcastReceiver.java  class having onReceive(Context context, Intent intent).
  

AndroidManifest.xml

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

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

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

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

        <receiver android:name="com.broadcastreceiver.MyBroadcastReceiver" >
            <intent-filter>
                <action android:name="com.broadcastreceiver.A_CUSTOM_INTENT" >
                </action>
            </intent-filter>
        </receiver>
    </application>

</manifest>

Above AndroidMenifest.xml file contens receiver class registeration and Intent filter.

Final output.


stay tune for next session happy coding :)


Wednesday, May 13, 2015

Android Custom ListView

 Customizing Android ListView with Custom ArrayAdapter.

Dear Followers today I am going to show you the android custom ListView with custom Array Adapter. if someone is newbie on Listview please see my previous post on simple Android Listview.
http://itsjavasinception.blogspot.in/2015/05/android-listview-with-adapter-in.html
all of you know the default look and feel of Listview  in android is not so interactive, so in this tutorial I will show you how to create custom Listview with custom adapter.
I am creating custome listview for college management member list with there profile pic and names.

see the below screenshots of this tutorial.


Create a new Android project in Eclipse with Management as your Activity and management_activity.xml as your layout file. Declare a ListView control in your management_activity.xml layout file as shown in the following code. 


management_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

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

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/list_selector" />

</LinearLayout>


The above code is using simple LinearLayout with vertical orientation, and a ListView is declared to cover the entire width and height of the parent container using the fill_parent as the value of both android:layout_height and android:layout:width properties. ListView also has a unique id list that will be used in the Management Activity to reference the ListView control.



To create a custom ListView row, create another xml layout file mangmt_list_item.xml in the project layout directory. Android will render this file content in every ListView item and you are free to declare any control you want in it. For this tutorial I am using an ImageView for an profile pic and a TextView for displaying persone names. 

mangmt_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_selector"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/profile_pic"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:contentDescription="desc"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />

    <TextView
        android:id="@+id/member_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/profile_pic"
        android:paddingBottom="10dp"
        android:text="txt"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/member_name"
        android:layout_below="@+id/member_name"
        android:text="txt"
        android:textSize="16sp" />
    <!-- Rightend Arrow -->

    <ImageView
        android:id="@+id/contact_type"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/member_name"
        android:layout_alignBottom="@+id/member_name"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true" />

</RelativeLayout>



Now create one Model class as:


Next create a new Java class in your project and named it ManagementRowItem.java. This class will be used to create a custom ArrayAdapter and to bind the objects with the ListView later in this tutorial. Following is the code of ManagementRowItem.java class. It has four simple properties profile_pic, member_name, status and contactType_id and a typical class constructor to initialize the properties. 
And also this class having getter setter methods. 

ManagementRowItem.java



public class ManagementRowItem {

     private String member_name;
     private int profile_pic_id;
     private String status;
     private int contactType_id;

     public ManagementRowItem(String member_name, int profile_pic_id, String status,
       int contactType_id) {

      this.member_name = member_name;
      this.profile_pic_id = profile_pic_id;
      this.status = status;
      this.contactType_id = contactType_id;
     }

     public String getMember_name() {
      return member_name;
     }

     public void setMember_name(String member_name) {
      this.member_name = member_name;
     }

     public int getProfile_pic_id() {
      return profile_pic_id;
     }

     public void setProfile_pic_id(int profile_pic_id) {
      this.profile_pic_id = profile_pic_id;
     }

     public String getStatus() {
      return status;
     }

     public void setStatus(String status) {
      this.status = status;
     }

     public int getContactType_id() {
      return contactType_id;
     }

     public void setContactType_id(int contactType_id) {
      this.contactType_id = contactType_id;
     }

    }


Notice that the above mangmt_list_item.xml file has four views, which are correspondent to the properties of the ManagementRowItem class. The values of the ManagementRowItem class properties will be displayed on those views and to connect these four pieces together you need to create a custom ArrayAdapter that will inherit the Android BaseAdapter class and will override the getView method. Add a new java class in your project with the name  

MangmtCustomAdapter .java

import java.util.List;

import com.sumago.portal.R;

import android.app.Activity;
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 MangmtCustomAdapter extends BaseAdapter {

 Context context;
 List<ManagementRowItem> managementRowItems;

 public MangmtCustomAdapter(Context context, List<ManagementRowItem> managementRowItems) {
  this.context = context;
  this.managementRowItems = managementRowItems;
 }

 @Override
 public int getCount() {
  return managementRowItems.size();
 }

 @Override
 public Object getItem(int position) {
  return managementRowItems.get(position);
 }

 @Override
 public long getItemId(int position) {
  return managementRowItems.indexOf(getItem(position));
 }

 /* private view holder class */
 private class ViewHolder {
  ImageView profile_pic;
  TextView member_name;
  TextView status;
  ImageView contactType;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

  ViewHolder holder = null;

  LayoutInflater mInflater = (LayoutInflater) context
    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
  if (convertView == null) {
   convertView = mInflater.inflate(R.layout.mangmt_list_item, null);
   holder = new ViewHolder();

   holder.member_name = (TextView) convertView
     .findViewById(R.id.member_name);
   holder.profile_pic = (ImageView) convertView
     .findViewById(R.id.profile_pic);
   holder.status = (TextView) convertView.findViewById(R.id.status);
   holder.contactType = (ImageView) convertView
     .findViewById(R.id.contact_type);

   ManagementRowItem row_pos = managementRowItems.get(position);

   holder.profile_pic.setImageResource(row_pos.getProfile_pic_id());
   holder.member_name.setText(row_pos.getMember_name());
   holder.status.setText(row_pos.getStatus());
   holder.contactType.setImageResource(row_pos.getContactType_id());

   convertView.setTag(holder);
  } else {
   holder = (ViewHolder) convertView.getTag();
  }

  return convertView;
 }

}



In the above code, the first important thing is the constructor of the class that takes two parameters. The first parameter is the Context and we can pass the reference of the activity in which we will use MangmtCustomAdapter class.
The second parameter is an List of ManagementRowItem class objects that will be used by the Adapter to display data. 
Next the parent class getView method is overridden. This method will be called for every item in the ListView to create views with their properties set as we want. The getView method is also using a temporary holder class declared inside the MangmtCustomAdapter class. This class will be used to cache the ImageView and TextView so they can be reused for every row in the ListView and this will provide us a great performance improvement as we are recycling the same two views with different properties and we don’t need to find ImageView and TextView for every ListView item.

The final piece of code is our application MainActivity in which we will be using all the above objects we declared. Following is the code of the Management.java file.

 Management.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.sumago.portal.CollageApp;
import com.sumago.portal.LoginPage;
import com.sumago.portal.R;
import com.sumago.portal.utility.ManagementRowItem;
import com.sumago.portal.utility.Managementinfo;
import com.sumago.portal.utility.MangmtCustomAdapter;

public class Management extends Activity implements OnItemClickListener {

    String[] member_names;
    TypedArray profile_pics, contactType;
    String[] statues;
    static final String TAG_IMAGES = "images";
    List<ManagementRowItem> managementRowItems;
    ListView mylistview;

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

        managementRowItems = new ArrayList<ManagementRowItem>();

        member_names = getResources().getStringArray(R.array.Member_names);

        profile_pics = getResources().obtainTypedArray(R.array.profile_pics);

        statues = getResources().getStringArray(R.array.statues);

        contactType = getResources().obtainTypedArray(R.array.contactType);

        for (int i = 0; i < member_names.length; i++) {
            ManagementRowItem item = new ManagementRowItem(member_names[i],
                    profile_pics.getResourceId(i, -1), statues[i],
                    contactType.getResourceId(i, -1));
            managementRowItems.add(item);
        }

        mylistview = (ListView) findViewById(R.id.list);
        MangmtCustomAdapter adapter = new MangmtCustomAdapter(this,
                managementRowItems);
        mylistview.setAdapter(adapter);
        profile_pics.recycle();
        mylistview.setOnItemClickListener(this);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        String selected = managementRowItems.get(position).getMember_name();
        int imgs = managementRowItems.get(position).getProfile_pic_id();
        Log.v("item selected", "on item click " + selected);
        Intent i = new Intent(getApplicationContext(), Managementinfo.class);

        Bundle b = new Bundle();
        b.putString("name", selected);

        i.putExtras(b);
        i.putExtra("imgss", imgs);
        startActivity(i);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.managemnt, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.logout:

            Intent logout = new Intent(Management.this, LoginPage.class);
            startActivity(logout);
            overridePendingTransition(R.anim.slide_in, R.anim.slide_out);

            return true;

        case R.id.home:

            Intent home = new Intent(Management.this, CollageApp.class);
            startActivity(home);
            overridePendingTransition(R.anim.slide_in, R.anim.slide_out);

            return true;

        }
        return false;
    }

    @Override
    protected void onResume() {
        // adapter.notifyDataSetChanged();
        super.onResume();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, CollageInformation.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }




string.xml file for getting array values 

 /*
 <!-- management Person list -->
    <!-- Names -->
    <string-array name="Member_names">
        <item>Shri.Balasaheb D. Wagh.</item>
        <item>Shri.Kashinath B. Tarle.</item>
        <item>Shri.Ashok R.Merchant.</item>
        <item>Shri.Changdeorao B.Holkar</item>
        <item>Shri.D.S. Shinde</item>
         <item>Dr(Mrs.)Priti D.Bhamare</item>
      <!--   <item>Dr. K.N.Nandurkar</item>
        <item>Dr(Mrs.)Priti D.Bhamare</item>
        <item>Dr.Shirish S.Sane</item> -->
    </string-array>

    <!-- Pictures -->
    <array name="profile_pics">
        <item>@drawable/bhau</item>
        <item>@drawable/bhaua</item>
        <item>@drawable/bhaub</item>
        <item>@drawable/bhauc</item>
        <item>@drawable/bhaud</item>
         <item>@drawable/mavshi</item>
      <!--   <item>@drawable/bhaue</item>
      
        <item>@drawable/bhauf</item> -->
    </array>

    <!-- Status -->
    <string-array name="statues">
        <item>President KKW</item>
        <item>Vice President</item>
        <item>Trustee</item>
        <item>Trustee</item>
        <item>Trustee</item>
          <item>Staff Representative</item>
        <!-- <item>Trustee</item>
     
        <item>Trustee</item> -->
    </string-array>

    <!-- contact type -->
    <string-array name="contactType">
        <item>@drawable/right_arrow_icon</item>
        <item>@drawable/right_arrow_icon</item>
        <item>@drawable/right_arrow_icon</item>
        <item>@drawable/right_arrow_icon</item>
        <item>@drawable/right_arrow_icon</item>
        <item>@drawable/right_arrow_icon</item>
    </string-array>

*/ 

There are few things in the Management that required explanation for your better understanding. First notice, we are creating an array of each properties those we initialized in Model class (ManagementRowItem) class here I am getting array values from string.xml file passed as constructor parameters. 
Finally we are passing our custom adapter to ListView setAdapter method. That’s about it. You are ready to build and run our project. If everything implemented properly you will see the following output.



Note: you have to get your images with there specific names to run this project perfectely. Thanks!


stay tune for next session..happy codding :)


   

Android ListView with Adapter

                                 Android ListView with Adapter

In Android development, any time we want to show a vertical list of scrollable items we will use a ListView which has data populated using an Adapter. The simplest adapter to use is called an ArrayAdapter because the adapter converts an ArrayList of objects into View items loaded into the ListView container.
ListView with Adapter conceptual Diagram.
The ArrayAdapter fits in between an ArrayList (data source) and the ListView (visual representation) and configures two aspects:
  • Which array to use as the data source for the list
  • How to convert any given item in the array into a corresponding View object.

 Using a Basic ArrayAdapter

To use a basic ArrayAdapter, you just need to initialize the adapter and attach the adapter to the ListView. First, we initialize the adapter:

ArrayAdapter<String> itemsAdapter = 
    new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
 
The ArrayAdapter requires a declaration of the type of the item to be converted to a View (a String in this case) and then accepts three arguments: context (activity instance), XML item layout, and the array of data. Note that we've chosen simple_list_item_1.xml which is a simple TextView as the layout for each of the items.

Now, we just need to connect this adapter to a ListView to be populated:

ListView lv= (ListView) findViewById(R.id.listview1);
lv.setAdapter(itemsAdapter);
 

Example:

activity_main.xml

 <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ListView>

 

MainActivity.java

public class MainActivity extends ActionBarActivity {
ListView lv;
String[] data = new String[]{"Nokia","Samsung","LG","Micromax","iPhone","Nexus s","Karbone","Lava","Geonie"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView)findViewById(R.id.listview1);
        ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,data);
        lv.setAdapter(itemsAdapter);
       
    }
 

Happy coding :)