Wednesday 22 May 2013

Sectioned List View/ List with Headers in Android

In this post we are going to learn about how to create simple sectioned adapter.

 Additionally we should not do any extra ordinary things. Its an ordinary one with one additional task that's it.

 This sample is not like other sample to set just an simple text view alone. You can use Seperate Header design page for section.

 1. Your Main.xml file



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

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

</LinearLayout>

  2. Your Header.xml  // in this file You can design whatever you want.


<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/list_header_title" 
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content" 
    android:paddingTop="2dip" 
    android:paddingBottom="2dip" 
    android:background="#008000"
    android:textColor="@android:color/white"
    android:paddingLeft="5dip" 
    style="?android:attr/listSeparatorTextViewStyle" /> 


3. Your List Childs  // As you peoples know this is also your custom.


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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />
   
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

   

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

</LinearLayout>


your MainActivity.java file



package com.example.mysectionadapter;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {       
   
    ListView listView1;
    Context context;
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.homepage);
       
        context=this;
       
        listView1=(ListView)findViewById(R.id.listView1);// list view finding
        // Adding data to array lists
        ArrayList<String> S1 = new ArrayList<String>();
       
        for (int i = 0; i < 10; i++) {
           
            S1.add("S1 item"+i);
        }
       
ArrayList<String> S2 = new ArrayList<String>();
       
        for (int i = 0; i < 10; i++) {
           
            S2.add("S2 item"+i);
        }
       
ArrayList<String> S3 = new ArrayList<String>();
       
        for (int i = 0; i < 10; i++) {
           
            S3.add("S3 item"+i);
        }
       
       
       
       
        // create our list and custom adapter
        SeparatedListAdapter adapter = new SeparatedListAdapter(this);
        adapter.addSection("Header 1 ", new ListAdapter(context,S1));    // this is your first adapter which contains the data related to first header    
        adapter.addSection("Header 2", new ListAdapterTest(context,S2));// this is your second adapter which contains the data related to first header
        adapter.addSection("Header 3 ", new ListAdapter(context,S3));// this is your third adapter which contains the data related to first header        
       
        // the thing is you can set above three adapters as single adapter.. or to differenciate your every single adapter you can use different adapters.
          //if you use different adapters you can use separate design files it will give different look to your ListView.
        // one more thing everything will work under single Scroll.

       
        listView1.setAdapter(adapter);
       
       
        listView1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                arg2=arg2-1;
               
                Toast.makeText(context, ""+arg2, 1000).show();  
                System.out.println(" TTTTTTTTTTTT " + arg2);
            }
        });

    }

}



SeparatedListAdapter .java  
// this is the master adapter which binds all the adapters as a single adapter with headers.

package com.example.mysectionadapter;

import java.util.LinkedHashMap;
import java.util.Map;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;

public class SeparatedListAdapter extends BaseAdapter {
   
    public final Map<String,Adapter> sections = new LinkedHashMap<String,Adapter>();
    public final ArrayAdapter<String> headers;
    public final static int TYPE_SECTION_HEADER = 0;
   
    public SeparatedListAdapter(Context context) {

        headers = new ArrayAdapter<String>(context, R.layout.header); // this is the header desing page.

    }
   
    public void addSection(String section, Adapter adapter) {
        this.headers.add(section);
        this.sections.put(section, adapter);
    }
   
    public Object getItem(int position) {
        for(Object section : this.sections.keySet()) {
            Adapter adapter = sections.get(section);
            int size = adapter.getCount() + 1;
           
            // check if position inside this section
            if(position == 0) return section;
            if(position < size) return adapter.getItem(position - 1);

            // otherwise jump into next section
            position -= size;
        }
        return null;
    }

    public int getCount() {
        // total together all sections, plus one for each section header
        int total = 0;
        for(Adapter adapter : this.sections.values())
            total += adapter.getCount() + 1;
        return total;
    }

    public int getViewTypeCount() {
        // assume that headers count as one, then total all sections
        int total = 1;
        for(Adapter adapter : this.sections.values())
            total += adapter.getViewTypeCount();
        return total;
    }
   
    public int getItemViewType(int position) {
        int type = 1;
        for(Object section : this.sections.keySet()) {
            Adapter adapter = sections.get(section);
            int size = adapter.getCount() + 1;
           
            // check if position inside this section
            if(position == 0) return TYPE_SECTION_HEADER; 
            if(position < size) return type + adapter.getItemViewType(position - 1);

            // otherwise jump into next section
            position -= size;
            type += adapter.getViewTypeCount();
        }
        return -1;
    }
   
    public boolean areAllItemsSelectable() {
        return false;
    }

    public boolean isEnabled(int position) {
        return (getItemViewType(position) != TYPE_SECTION_HEADER);
    }
   
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int sectionnum = 0;
        for(Object section : this.sections.keySet()) {
            Adapter adapter = sections.get(section);
            int size = adapter.getCount() + 1;
           
            // check if position inside this section
            if(position == 0) return headers.getView(sectionnum, convertView, parent); // this is where your header names will get bind. correctly.
            if(position < size) return adapter.getView(position - 1, convertView, parent);

            // otherwise jump into next section
            position -= size;
            sectionnum++;
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

}


Adapter files


for sample purpose i have used two adapters. they are as follows.


package com.example.mysectionadapter;
import java.util.ArrayList;

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

public class ListAdapter extends BaseAdapter {
    Context ctx;
    LayoutInflater lInflater;

    ArrayList<String> Datastring=new ArrayList<String>();
   
    public ListAdapter(Context context,ArrayList<String> Items) {
        ctx = context;       
        Datastring.addAll(Items);
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       
    }

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

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

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       
        if (convertView == null) {
            convertView = (View) lInflater.inflate(R.layout.list, parent, false);           
        }
        TextView text=(TextView)convertView.findViewById(R.id.textView1);
        text.setText(Datastring.get(position));
       
        return convertView;
    }

   
   

}

Adapter file 2



package com.example.mysectionadapter;
import java.util.ArrayList;

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

public class ListAdapterTest extends BaseAdapter {
    Context ctx;
    LayoutInflater lInflater;

    ArrayList<String> Datastring=new ArrayList<String>();
   
    public ListAdapterTest(Context context,ArrayList<String> Items) {
        ctx = context;       
        Datastring.addAll(Items);
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       
    }

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

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

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       
        if (convertView == null) {
            convertView = (View) lInflater.inflate(R.layout.list, parent, false);           
        }
        TextView text=(TextView)convertView.findViewById(R.id.textView1);
        text.setText(Datastring.get(position));
       
        return convertView;
    }

   
   

}

Manifest file . // this is as usual one.



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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mysectionadapter.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>


Hope this post will help to some beginners . happy coding.

Monday 20 May 2013

Android Vertical/Horizontal custom Tablayout

In this post we are going to see about Vertical Tab layout (May be you can say custom tab layout by other words.)

Normally we can create tab layout only horizontally. And also it will show some default separator within it. If you follow below method it won’t look like actual Tab layout. But it will do its functionality. 

Main.xml file will be like below.
1.       Normally we will have Tab host to use tab layout So we should have that here also.
2.       As like Tab host we are having Tab Widget.
3.       Then Normal Frame layout to show the  tab activities. 

<?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:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

        <FrameLayout
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.2" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />

          

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical" >

                    <Button
                        android:id="@+id/Tab1"
                        android:layout_width="fill_parent"
                        android:layout_height="0dip"
                        android:layout_weight="1.0"
                        android:onClick="tabHandler"
                      
                        android:text="Tab1" />

                    <Button
                        android:id="@+id/Tab2"
                        android:layout_width="fill_parent"
                        android:layout_height="0dip"
                        android:layout_weight="1.0"
                        android:onClick="tabHandler"
                        android:text="Tab2" />

                    <Button
                        android:id="@+id/Tab3"
                        android:layout_width="fill_parent"
                        android:layout_height="0dip"
                        android:layout_weight="1.0"
                        android:onClick="tabHandler"
                        android:text="Tab3" />

                    <Button
                        android:id="@+id/Tab4"
                        android:layout_width="fill_parent"
                        android:layout_height="0dip"
                        android:layout_weight="1.0"
                        android:onClick="tabHandler"
                        android:text="Tab4" />

                    <Button
                        android:id="@+id/Tab5"
                        android:layout_width="fill_parent"
                        android:layout_height="0dip"
                        android:layout_weight="1.0"
                        android:onClick="tabHandler"
                        android:text="Tab5" />
                     
                </LinearLayout>
         
        </FrameLayout>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.8" />
    </LinearLayout>

</TabHost>



Activity File :

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class VerticalTabhost extends TabActivity {
       /** Called when the activity is first created. */
       Button Tab1,Tab2,Tab3,Tab4,Tab5;
       TabHost tabHost;
       public static String Tab="";
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main_view);

               tabHost = getTabHost();
            
              Tab1=(Button)findViewById(R.id.Tab1);
              Tab2=(Button)findViewById(R.id.Tab2);
              Tab3=(Button)findViewById(R.id.Tab3);
              Tab4=(Button)findViewById(R.id.Tab4);
              Tab5=(Button)findViewById(R.id.Tab5);

              // Tab for tab1
              TabSpec spec1 = tabHost.newTabSpec("Tab1");
              // setting Title and Icon for the Tab
              spec1.setIndicator("Tab1");
              Intent Intent1 = new Intent(this, Activity1.class);
              spec1.setContent(Intent1);

              // Tab for tab2
              TabSpec spec2 = tabHost.newTabSpec("Tab2");
              // setting Title and Icon for the Tab
              spec2.setIndicator("Tab2");
              Intent Intent2 = new Intent(this, Activity1.class);
              spec2.setContent(Intent2);

              // Tab for tab3
              TabSpec spec3 = tabHost.newTabSpec("Tab3");
              // setting Title and Icon for the Tab
              spec3.setIndicator("Tab3");
              Intent Intent3 = new Intent(this, Activity1.class);
              spec3.setContent(Intent3);

              // Tab for tab4

              TabSpec spec4 = tabHost.newTabSpec("Tab4");
              // setting Title and Icon for the Tab
              spec4.setIndicator("Tab4");
              Intent Intent4 = new Intent(this, Activity1.class);
              spec4.setContent(Intent4);

              // Tab for tab5
              TabSpec spec5 = tabHost.newTabSpec("");
              // setting Title and Icon for the Tab
              spec5.setIndicator("");
              Intent Intent5 = new Intent(this, Activity1.class);
              spec5.setContent(Intent5);
                         
            
              // Adding all TabSpec to TabHost

              tabHost.addTab(spec1); // Adding tab1
              tabHost.addTab(spec2); // Adding tab2

              tabHost.addTab(spec3); // Adding tab3
              tabHost.addTab(spec4); // Adding tab4
              tabHost.addTab(spec5); // Adding tab5
            
            
       }

//======================= click Handling for the tab layout buttons=============
       public void tabHandler(View target) {
              if (target.getId() == R.id.Tab1) {
                     Tab="this is Tab 1";
                     tabHost.setCurrentTab(0);
            
              } else if (target.getId() == R.id.Tab2) {
                     Tab="this is Tab 2";
                   
                   
                     tabHost.setCurrentTab(1);
                   
              } else if (target.getId() == R.id.Tab3) {
                     Tab="this is Tab 3";
                   
                     tabHost.setCurrentTab(2);
                   
              }
              else if (target.getId() == R.id.Tab4) {
                     Tab="this is Tab 4";
                   
                     tabHost.setCurrentTab(3);
                   
              }
              else if (target.getId() == R.id.Tab5) {
                     Tab="this is Tab 5";
                   
                     tabHost.setCurrentTab(4);
                   
              }
       }
}

Vertical Tablayout will be look like below image. 

 If you want to change this for horizontal view your design will be look like below.

<?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:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <FrameLayout
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="0.2" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />

          

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="horizontal" >

                    <Button
                        android:id="@+id/Tab1"
                        android:layout_width="0dip"
                        android:layout_height="fill_parent"
                        android:layout_weight="1.0"
                        android:onClick="tabHandler"
                      
                        android:text="Tab1" />

                    <Button
                        android:id="@+id/Tab2"
                        android:layout_width="0dip"
                        android:layout_height="fill_parent"
                        android:layout_weight="1.0"
                        android:onClick="tabHandler"
                        android:text="Tab2" />

                    <Button
                        android:id="@+id/Tab3"
                        android:layout_width="0dip"
                        android:layout_height="fill_parent"
                        android:layout_weight="1.0"
                        android:onClick="tabHandler"
                        android:text="Tab3" />

                    <Button
                        android:id="@+id/Tab4"
                        android:layout_width="0dip"
                        android:layout_height="fill_parent"
                        android:layout_weight="1.0"
                        android:onClick="tabHandler"
                        android:text="Tab4" />

                    <Button
                        android:id="@+id/Tab5"
                        android:layout_width="0dip"
                        android:layout_height="fill_parent"
                        android:layout_weight="1.0"
                        android:onClick="tabHandler"
                        android:text="Tab5" />
                     
                </LinearLayout>
         
        </FrameLayout>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:background="@android:color/darker_gray"
            android:layout_weight="0.8" />
    </LinearLayout>

</TabHost>

View will be look like below image.
Hope this will help to some peoples.

Saturday 18 May 2013

Android Shared Preferences

Hi all,

In this post we will learn about how to use shared preferences.
Shard preferences is nothing but simply we can say small Database. Normally we will use one library variable or temporary variable to store the values. If suppose your app gets crash in some pages means your temporary variable will loose their assigned values.

To know more about shared Preferences please gothrough the following link .
http://developer.android.com/reference/android/content/SharedPreferences.html

Step 1: 
To obtain shared preferences, use the following method In your activity:
SharedPreferences prefs = this.getSharedPreferences("Rajesh", Context.MODE_PRIVATE);

Step 2:

To read preferences:

SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String text = app_preferences.getString("UserName", "null");

like getString you can have lot of methods like below

for Boolean values
 boolean Ischeck = app_preferences.getBoolean("key", false);

for float values 

   float text1 = app_preferences.getFloat("key", 0f);

for long values :

long text1 = app_preferences.getLong("key", 0l);

for int values:

int text1 = app_preferences.getInt("key", 0);

To edit and save preferences

public static final String PREFS_NAME = "LoginPrefs"; //
By using above line you can create multiple shared preferences file .

SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("value1", "Rajesh");
editor.commit();

if you want to add all the values in single preferences file use the below lines. 

SharedPreferences app_preferences =
               PreferenceManager.getDefaultSharedPreferences(this);
               SharedPreferences.Editor editor1 = app_preferences.edit();
                  editor1.putString("key", text);
               editor1.putString("key1", text1);

               editor1.commit();

The android sdk's sample directory contains an example of retrieving and stroing shared preferences. Its located in the:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

Tuesday 7 May 2013

Android view PDF in Webview

Hi all,

Today we are going to see about how to view pdf files in android using google docs.

Normally Android don't have support to view the PDF files. So that we should use web view to view the PDF files in Android.

This is not much different from web view. just we need to append the Google docs URL in web view.loadurl().

1. main.xml
below is the layout code with web view.

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

2. Your Activity code should be like below 
 package org.example.webviewdemo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewDemo extends Activity {      
  

    private WebView webView;
    Activity activity ; // instead of context we can use activity
    private ProgressDialog progDailog;  // loader
    String GoogleDocs="http://docs.google.com/gview?embedded=true&url="; 

                                     // google docs support url.
 
       @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        activity = this;      
        progDailog = ProgressDialog.show(activity, "Loading","Please wait...", true);
        progDailog.setCancelable(false);      
       webView = (WebView) findViewById(R.id.webview_compontent);     
      
   
       webView.getSettings().setJavaScriptEnabled(true);   
       webView.getSettings().setLoadWithOverviewMode(true);
       webView.getSettings().setUseWideViewPort(true);      

//following lines are to show the loader untile downloading the pdf file for view.
        webView.setWebViewClient(new WebViewClient(){
          
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                progDailog.show();
                view.loadUrl(url);
           
                return true;              
            }
            @Override
            public void onPageFinished(WebView view, final String url) {
                progDailog.dismiss();
            }
        });
      
        webView.loadUrl(GoogleDocs+"http://178.239.16.28/fzs/sites/default/files/dokumenti-vijesti/sample.pdf");   // webview loader to load the URL of file

 }  }


Don't forget to add below permission in manifest file.

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


happy coding.