Adapters are like magician. In android if you want to display block of data in List view or Grid view or any other android widget you have to implement some kind of adapter class in your application. It can be Base adapter or Array adapter or any. So in this class you perform some ugly or magical work. Like creating view for each row of list or grid and then assign data and even you can write some business logic also in that adapter class.

Types of adapters in android are as follows
  1. Base Adapter
  2. Simple Adapter 
  3. Array Adapter
  4. Simple Cursor Adapter
  5. List Adapter
  6. Cursor Adapter
  7. Resource Cursor Adapter
  8. Spinner Adapter
  9. Simple Cursor Tree Adapter
  10. Cursor Tree Adapter
  11. Header View List Adapter
  12. Wrapper List Adapter

Well some of them are totally new for me and i hope for you also. Because they are less known and less used by developers. They consist lots of complexity but for different uses it may help you. just check it out in android documentation. These are the list of adapters till android v 4.4 Kitkat. it may happen android team will add new adapters in next version of android named as android L or in future . So from above all the adapters which are mostly used in android and easy to implement. 

Base Adapter
As name suggest it is base class for all adapter class and interface. Base adapter is abstract class. Base Adapter is a very generic adapter that allows you to do pretty much whatever you want. However, you have to do a bit more coding yourself to get it working. using this class you can define custom view for each row and also you can perform task on object click event also. getView method is basically implemented in this class and you can override it and define your layout in this method. using this class you can bind data with list view and spinner. this is the most used adapter class for binding data in any view. even you can write business logic also in this class. in base adapter class you have to implement even getcount method because on the basis of that adapter will call getview method. Read more

Simple Adapter
when you want to bind static data set to list view you can use simple adapter. you can define xml layout for each row and data can be in array list or in map. each row represent single record of array list. simple adapter class extends Base Adapter class so you have all those methods so you can override even in simple adapter class. data binding is done using view Binder method. Read more

Array Adapter
Second is Array Adapter. Array Adapter is a class which can work with array of data. you need to override only getview method. you can override getview method with different types of parameter. but the main use of array adapter when you want to display a single text view in each row of list. then it is batter to use this adapter. you have to pass data layout or resource file id and text view id in getview method. you can even use image view and other object but for that Base adapter class is perfect. Read more


Simple Cursor Adapter
If your application requires data from local database then you can use simple cursor adapter class to bind data. this is class like simple adapter if you require to display data from database in listview then it is best practice to extend this class. it also works as simple adapter class. different between both is in simple adapter data is in array list and static and in this class data is in cursor and comes from database. data binding in this also done using view Binder method. Read more

Cursor Adapter
if you want to implement this class make sure your table consist one column named as "_id". because cursor traverse data using this column in cursor adapter. and if you want to perform some filtration or swipe cursor then only use this class. it is quite complex so if you are new in android don't try this try some other adapters. one more thing in cursor adapter you have to implement or override new view and bind view method. in which you can define view for each row and bind data also. cursor view already implement getview method so it is better to not to override this method. Read more

Simple Cursor Tree Adapter
last but not list simple cursor tree adapter is useful when you have nested view like nested list view or grid view.  the class provide you method to define layout for child view or group view so if you have data from database and even it is complex (two / three table data) then you can use this adapter class to display data in nested view. Read more

Well there are other adapters also in the list but they are less used and i just covered few details of each adapter class you can find more details about it. click on read more and it will redirect you to documentation where you can find more about it. one more thing, in android View Holder pattern is most famous and use full pattern of saving row layout before it get recycled by garbage collector. so before implementing look after this pattern.

I hope these details help you to understand about adapters. and if it is helpful to you please share this article with your friends. and if you have any thing to say about this article write down in below comment box. new things and suggestion always welcome.

Keep coding...

Yesterday i spent whole day behind using my database i mean database is created i just require to use it in app. And i came across many problems, Some of them were really annoying and confusing. For some of them you can find online solution but some are really unknown like null pointer exception or getWritableDatabase method called recursively etc. Even if there is table and also data in it.  some times it also happens you can not copy big database and it is also big problem in android. For that you have to dig up in to your code. You have to debug your app and in android studio it is also tedious task.  so to save your time and without doing all this you can copy database from assets folder to internal storage. Just go through the full tutorial and i hope it will solve all problems regarding coping database.

Steps 
1.  Put below code in your SQLiteOpenHelper Class file. you have to put this code in onCreate method. if you have done some other task in oncreate method then rearrange it after this code. this code will check if database exist then do nothing because if you won't check it will overwrite your database every time you call   getWritableDatabase Or getReadableDatabase Method. beacuse it call onCreate method internally.

2. From your Main Activity only first time call Oncreate method of  SQLiteOpenHelper Class. so for the first time it will create or copy your database. if your database is big you can display progress bar for loading process.


Coping Database Code
package com.androprogrammer.dbdemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class DbHelper extends SQLiteOpenHelper 
{
 public static final String DB_NAME = "mydb.db";
 public static final int version = 1;
 public static final String product_table = "tblproduct";
 public static final String order_id = "_id";
 public static final String pname = "pname";
 public static final String desc = "desc";
 public static final String quantity = "quantity";
 public static final String rating = "rating";
 
 private SQLiteDatabase ourdb;
 public Context cont;

 public DbHelper(Context context)
 {
  // TODO Auto-generated constructor stub
  super(context, DB_NAME, null, version);
  this.cont = context;
 }

 @Override
 public void onCreate(SQLiteDatabase db)
    {
        try
        {
            File dbFile = cont.getDatabasePath(DB_NAME);

            if (dbFile.exists())
            {
                //Toast.makeText(cont, "Database Already Exist..." , Toast.LENGTH_LONG).show();
            }
            else
            {
                this.getReadableDatabase();

                InputStream input = cont.getAssets().open(DB_NAME);
                int size = input.available();
                input.close();

                if (size > 0)
                {

                    Log.d("file" , dbFile.getPath());

                    copyDataBase(dbFile);
                    //this.close();
                }
                else
                {
                    // TODO Auto-generated method stub
                    db.execSQL("create table " + product_table +" ( "+ order_id + " INTEGER PRIMARY KEY AUTOINCREMENT , " + pname + " TEXT NOT NULL ," + desc + " TEXT ,"
                            + rating + " INTEGER ," + quantity +" INTEGER );");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.ourdb = db;

 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // TODO Auto-generated method stub
  
 }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     *
     * @param dbFile*/
    private void copyDataBase(File dbFile) throws IOException {

        //Open your local db as the input stream
        InputStream myInput = cont.getAssets().open(DB_NAME);

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(dbFile);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0)
        {
            myOutput.write(buffer, 0, length);
            Log.d("buf", "" + length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }
  
 public DbHelper open() throws SQLException
 {
        if (this.ourdb == null)
        {
           this.ourdb = this.getWritableDatabase();
        }

  return this;
 }

 public synchronized void close()
 {
        if(this.ourdb.isOpen())
      this.ourdb.close();
 }

 public long insert(String name, String des, Float ratings, int quan) throws SQLException
 {
  // TODO Auto-generated method stub
  ContentValues cv = new ContentValues();
  cv.put(pname, name);
  cv.put(desc, des);
  cv.put(rating, ratings);
  cv.put(quantity, quan);
  return this.ourdb.insertOrThrow(product_table, null, cv);

 }

 public Cursor getAllData() throws SQLException
 {
  // TODO Auto-generated method stub
  String [] colums = new String[]{order_id ,pname ,desc ,rating ,quantity};
  Cursor c = this.ourdb.query(product_table,colums, null, null, null, null, null, null);
  return c;
 }

}


As you can see i have even checked if there is no file in assets folder it will create blank database so application won't crash. because it create bad impect when you publish your app in Google play store and it crash so for safety side you can do this. then you can update it later on. now from your main activity just call the onCreate method for that put below code in it.

SQLiteDatabase db = null;
DbHelper helper = new DbHelper(Main.this);
helper.onCreate(db);

Now your database file created or copied so just check it if you have created display method or activity then open it and check it. you can see in debug window also because i have used Logger to know weather database is copied or not so check debug window in editor. now from all other class or activity just call open method. for that put below code in it.

DbHelper helper = new DbHelper(this);
helper.open();

The open method will return instance of database after checking weather it is opened or not. ok now run your app and see the result. if you find any error or if you have any query let me know. Comment in below comment box. it may happen you may find some new error then also let me know so other can also solve that and i will try my best to solve that problem. i have also written tutorial about add, update and display records from database so if you have any query regarding that also check this out.

Keep coding ...  
Google Now made us lazy. it can make call for you , can set alarm or reminder for you and much more things that you and i even don't know. And it is without using key board or even without touching your smart phone. as it provide voice input, it is one of the best functionality smart phone provides. Apps and User preference changes day by day and still you provide input using key board i think you have to rethink before next update.  Voice input is supported form android  v 2.3 Ginger bread so you can implement it in your application without using any third party Api. you can implement it using RecognizerIntent.ACTION_RECOGNIZE_SPEECH intent. In this tutorial i am going to show you how you can implement it in your app. just go through full tutorial i am sure you will implement it successfully.

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file.
minSdkVersion="11” and targetSdkVersion="17".

you can use below android version also for compilation and build option (As per requirement). now put below code in your project main.xml file. you can set layout as you want but for practice purpose you can go with same.

Main.xml


    

        
            
        

        
        
    


I have given style to the Edit text so it looks nice. below xml file is style applied on it . so now create one resource file and put this code in it.
edittextstyle.xml

    
    
    


Step -2 : Layout is set for your activity. now put below code inside your main class file or where you want voice input. the RecognizerIntent Class allows you to use inbuilt speech recolonization functionality. As i have used this class (intent) it will allow to prompt a dialog box where you can display message what ever you want. 
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak the word");
After user input you can get the result using onActivityResult() method. i get that response and set it into the edit text. now put the below code in class file.
Main.java
package com.androprogrammer.tutorialsamples;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

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

public class Main extends Activity {

    EditText word;
    ImageButton bt_voiceinput;
    private static final int REQUEST_CODE = 1234;

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

        // Disable button if no recognition service is present
        PackageManager pm = getPackageManager();
        List<resolveinfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() == 0) {
            bt_voiceinput.setEnabled(false);
        }

        bt_voiceinput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startVoiceRecognitionActivity();
            }
        });
        word.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                bt_voiceinput.setEnabled(false);
            }
        });
    }

    private void setRef() {
        // TO set Reference to the xml button object.
        bt_voiceinput = (ImageButton) findViewById(R.id.ib_speak);
        word = (EditText) findViewById(R.id.et_word);
    }

    /**
     * Fire an intent to start the voice recognition activity.
     */
    private void startVoiceRecognitionActivity() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak the word");
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //If Voice recognition is successful then it returns RESULT_OK
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if (resultCode == RESULT_OK) {
                ArrayList<string> textMatchList = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (!textMatchList.isEmpty()) {
                        String Query = textMatchList.get(0);
                        word.setText(searchQuery);
                }
                //Result code for various error.
            } else if (resultCode == RecognizerIntent.RESULT_NETWORK_ERROR) {
                showToastMessage("Network Error");
            } else if (resultCode == RecognizerIntent.RESULT_NO_MATCH) {
                showToastMessage("No Match");
            } else if (resultCode == RecognizerIntent.RESULT_SERVER_ERROR) {
                showToastMessage("Server Error");
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void showToastMessage(String msg) {
        Toast.makeText(Main.this, msg, Toast.LENGTH_LONG).show();
    }
}
       Screen Shots




So that's it from coding side now you can run app and test it. i hope you it will run smoothly.
if you have any query comment it in below comment box.
Keep coding...
To alert user about some event or to remind about some event happen in your app ,  push notification is a great and easy way. in android for in app notification you can use alert box but if your application is running in background (background mode) and then to notify user you have to use push notification. on Android devices, when a device receives a push notification, your application's icon and a message appear in the status bar. so in this tutorial i am going to show 2 types of notification. one is just small notification consist of Notification Heading , Sort subject , Icon , time etc. 
and in another type you can display big notification like Gmail notification for new mail (same as image).  it consist Big heading , big message and all other things remain same.

This tutorial will show you how to add push notification functionality in your an Android app to send and receive push notifications.

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file. 
minSdkVersion="11”  and 
targetSdkVersion="17".
you can use below android version also for compilation and build option (As per requirment). now put below code in your project main.xml file. you can set layout as you want but for practice purpose you can go with same.
Main.xml


 
 
 
 

 
 
 
 
 

 




In the below class file i have take care of which android version it is so it won't get crashed in older Android version. Below android  3.0 the notification consist simple style of notification  not the bigger one. so we have to take care which version user is using. but firstly you are require to get system service for creating notification. so get it using getSystemService() method of context. 
on small notification button click simple style notification is get created and pending intent will add that intent in intent pool. so system will notify user with NotificationManager.notify() method. 
in other case big notification will be created by second button. in which the big message which will be displayed in notification will be store in Notification.InboxStyle object. that object can store big message , big image (like Screen shot image) etc. 

Step -2 : Hope it will be clear to you. So just now put the below code in Main.java file.
Main.java
package com.androprogrammer.tutorialsamples;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class Main extends Activity {

    Button notification_small , notification_big;
    EditText heading , message;
    String heading_text, subject_text;
    Notification n;
    Notification.Builder nb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final NotificationManager notificationManager = (NotificationManager)
                getSystemService(NOTIFICATION_SERVICE);
        setRef();

        final Intent intent = new Intent(getApplicationContext(),Main.class);
        final PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

        notification_small.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(heading.getText().length() < 0)
                {
                    heading_text = "test";
                }
                else
                {
                    heading_text = heading.getText().toString();
                }

                if (Build.VERSION.SDK_INT < 11)
                {
                    n = new Notification(R.drawable.ic_launcher,
                            heading_text,
                            System.currentTimeMillis());

                    n.setLatestEventInfo(
                            getApplicationContext(),
                            heading_text,
                            message.getText().toString(),
                            pending);
                }
                else
                {
                   n = new Notification.Builder(NotificationDemo.this)
                        .setContentTitle(heading_text)
                        .setContentText(message.getText().toString())
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentIntent(pending)
                        .setAutoCancel(true)
                        .addAction(R.drawable.abc_ic_clear, "Close", pending).build();
                }
                n.flags |= Notification.FLAG_AUTO_CANCEL;
                notificationManager.notify(0,n);
            }
        });

        notification_big.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if(heading.getText().length() < 0)
                {
                    heading_text = "test";
                }
                else
                {
                    heading_text = heading.getText().toString();
                }

                if (Build.VERSION.SDK_INT < 11)
                {
                    n = new Notification(R.drawable.ic_launcher,
                            heading_text,
                            System.currentTimeMillis());

                    n.setLatestEventInfo(
                            getApplicationContext(),
                            heading_text,
                            message.getText().toString(),
                            pending);
                }
                else
                {
                   nb = new Notification.Builder(Main.this);

                    Notification.InboxStyle nc =
                            new Notification.InboxStyle();

                    nc.setBigContentTitle(heading_text);

                    String [] text = new String[5];

                    for (int i = 0 ; i < 5 ; i++)
                    {
                        text[i]  = i + ". say hello...";
                        nc.addLine(text[i]);
                    }

                    nb.setStyle(nc);
                }

                notificationManager.notify(100,nb.build());
            }
        });
    }

    private void setRef()
    {
        // TO set Reference to the xml button & edit text object.
        notification_small = (Button) findViewById(R.id.nd_smallnotification);
        notification_big = (Button) findViewById(R.id.nd_bignotification);
        heading = (EditText) findViewById(R.id.nd_etHeading);
        message = (EditText) findViewById(R.id.nd_notificationbody);
    }

}


Step -3 :  Now run your app and write some text for heading and body part of notification. as you can see in below screen shot i have shown both notification type in it. 

if its still not clear to you or have some query ask me in below comment box.if you like it share this tutorial with your friends.

Keep coding...
Screen Shot


Android framework create your application folder in internal space when you install any of app. it is located at data/data/package-name folder. if you have rooted emulator or smart phone you can check it out. but it has one disadvantage once user remove your app this folder will also be removed but if you want to store data after it also so you can use it if user again install your app or you want to store some info related to your app on SD card then you can create it using this tutorial.  just follow the steps of this tutorial.

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file. minSdkVersion="11” and targetSdkVersion="17".you can use below android version also for compilation and build option. put this below code in your mainactivity so once user start your app it will be created so you can use it further in your app.
MainActivity.java
package com.androprogrammer.tutorialsamples;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;

import java.io.File;


public class MainActivity extends ActionBarActivity {

    String folderPath;
    File folder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sdcard_folder_demo);
        folderPath = createFolder();
    }

    private String createFolder()
    {
            String extStorageDirectory = Environment
                    .getExternalStorageDirectory().toString();
            folder = new File(extStorageDirectory, "/Android/data/" + getPackageName());
            if(!folder.exists())
            {
                folder.mkdir();
                Toast.makeText(MainActivity.this, "Folder Created At :" + folder.getPath().toString(), Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(MainActivity.this, "Folder Already At :" + folder.getPath().toString(), Toast.LENGTH_LONG).show();
            }
            return folder.getPath().toString();
    }
}
Step -2 : i have created createFolder() method it will also check if folder is already created or not. if it is there it return path to the folder. the above code will create folder with your package name so to check out run your application. one more thing in order to create or write in SD card you required to add below permission in manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Screen Shots
androprogrammer.comandroprogrammer.com

That's it check out your application folder in SD card at Android/data/package-name folder. now you can store any data in or file in this folder using string returned by that method.

Keep coding.. 
In Android Application to Perform multiple task you have to create different activities or services or both but using fragments you can use multiple views in single fragment activity. The Concept of Fragments comes from Android 3.0 (Honeycomb) but now developers have created many API so you can use it in below android version also. In this tutorial i am going to explain you how you can implements fragment in your application easily. The Fragment concept is quit confusing and from documentation you can not understand it properly. 

So Go through the full tutorial and don't miss any steps because it is confusing so you may miss some of the main points. In this tutorial i am going to create List of Website and When user clicks on it. it will open that site in web view. so these are the files i am going to create in my project. i am clarifying it because their are many tutorials but in many of them you get confuse between those files so have a look it.

Java (Class) Files
1. MainActivity.java
2.FragmentListview.java
3.FragmentWebview.java
4.FragmentSupport.java

Xml (Layout) Files
1.activity_main.xml
2.fragmentlistview.xml
3.fragmentwebview.xml
4.fragment_support.xml


Fragments in android



This is how it looks in portrait view. When mobile is in Portrait view only one view is display to the user. when user click on list item then new view is get created and display to the user. you can add view in back stack of fragment. further read about back stack navigation.
Below image is of fragment in landscape view. in order to work your application in landscape mode you have to create folder name as layout-land. 


Fragments in android

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file. minSdkVersion="11” and targetSdkVersion="17".you can use below android version also for compilation and build option.
Step-2 : in your activity_main.xml file add fragment in it. when you add it in eclipse you have option to create fragment class but in android studio you will see below popup box then select any of them we will change it later.

Fragments in android

Now below coding is of activity_main.xml file you can put it in your code.
activity_main.xml



    


Now Create New Layout File For List view and add list view in it and Layout for Web view also. this layouts are use to create dynamically view.
fragmentlistview.xml


    
    


fragmentwebview.xml


    

Step-3 : Create New Activity and name it fragmentSupport.jave and fragment_support.xml. Below one is layout for fragment support activity. this activity is for take index of list item and pass it to the web fragment. in landscape view both layout is in view so you are not require to call or create web view again.
fragment_support.xml


    
    


now create layout-land folder in res folder and create new layout file and give same name as activity_main.xml. android will automatically use this view when user rotate mobile to landscape view. then copy below code in it. it have both fragment listview and webview. 
now all your layout is done. make sure name of fragments are same in portrait view layout file and landscape view file. 

Step-4 : All layout is set so now i proceed to coding so copy below code in MainActivity.java file. the MaiActivity.java file implements interface that is created in FragmentListview.java class. this interface is connector between two views. 
MainActivity.java
package com.androprogrammer.democollection;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.app.FragmentManager;


public class MainActivity extends Activity implements FragmentListview.OnSiteSelectedListener{

    FragmentWebview web;
    FragmentListview list;
    FragmentManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager = getFragmentManager();
        list = (FragmentListview) manager.findFragmentById(R.id.fragment1);
        list.setRefrence(this);
    }

    @Override
    public void onSiteSelected(int i) {
        // TODO Auto-generated method stub

        web = (FragmentWebview) manager.findFragmentById(R.id.fragment2);
        // Check for landscape mode
        if (web!= null && web.isVisible())
        {
            web.setNewPage(i);
        }
        else
        {
            Intent intent = new Intent(this , Fragmentsupport.class);
            intent.putExtra("index", i);
            startActivity(intent);
        }
    }

}
onSiteselected method is implemented in OnSiteSelectedListener interface. this method will take index from main view weather it is portrait view or landscape view and then send it to the Fragmentwebview class to get website from String array and then load it in Web view. now put below code in FragmentListview.java file.
FragmentListview.java
package com.androprogrammer.democollection;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FragmentListview extends Fragment implements AdapterView.OnItemClickListener
{
    ListView list;
 String [] websites = {"Google","Facebook","Twitter","Xda-developer"};
 
 
 OnSiteSelectedListener SiteListener;

 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  View v = inflater.inflate(R.layout.fragmentlistview, container, false);
        list = (ListView) v.findViewById(R.id.list);
        list.setAdapter(new ArrayAdapter(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1,websites));
        list.setOnItemClickListener(this);
        return v;
 }

    @Override
    public void onItemClick(AdapterView adapterView, View view, int position, long l)
    {
        SiteListener.onSiteSelected(position);
    }

    // Container Activity must implement this interface
    public interface OnSiteSelectedListener {
        public void onSiteSelected(int i);
    }

    public void setRefrence(OnSiteSelectedListener siteListener)
    {
        this.SiteListener = siteListener;
    }

}
Fragmentwebview.java
package com.androprogrammer.democollection;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

public class FragmentWebview extends Fragment {

 WebView webView;
 String [] links = {"http://www.google.com","http://www.facebook.com","http://www.twitter.com" , "http://www.xda-developers.com"};
 @Override
 public void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragmentwebview, container, false);
  webView = (WebView) v.findViewById(R.id.webView1);
        webView.loadUrl(links[0].toString());
        return v;
 }

 public void setNewPage(int i) 
 {
  //webView = (WebView) getView().findViewById(R.id.webView1);
  Log.d("webveiw", "called");
  webView.loadUrl(links[i].toString());
 }
}
FragmentSupport.java
package com.androprogrammer.democollection;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class Fragmentsupport extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_support);
        Intent intent = getIntent();
        int index = intent.getIntExtra("index",0);
        FragmentWebview web = (FragmentWebview) getFragmentManager().findFragmentById(R.id.fragment2);
        if (web != null)
            web.setNewPage(index);

    }
}

the above four class file is not activity only MainActivity and FragmentSupport is activity so make sure you have added entry in manifest file. one more thing add below permission also in manifest file.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
that's it. you have created fragment project successfully. so now customize it as you require.
you can download full source code from here.
Keep Coding...
To Access Web Services or Internet connection you required to check weather connection is available or not. so to check how you can do this read my this article in which i will help you to get connection status in your application. there are no of ways to get connectivity status like broadcast receiver , back ground service etc. but in this example i am using connectivity manager class which allow to use connection service in our application. 

Step -1  : Create New Android application and give name ConnectivityDemo to main activity and same name for layout file. minSdkVersion="17” and targetSdkVersion="17".you can use below android version also for compilation and build option.

Step-2 : in your connectivitydemo.xml file put the below code in it. in this layout file i have used two buttons but if you won't require it you can skip this step.
ConnectivityDemo.xml


      

    


Step-3 : Above layout File having one button for checking mobile data connection and one is for wifi connection.  now put below code in ConnectivityDemo.java file.
ConnectivityDemo.java
package com.example.samplecollection;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ConnectivityDemo extends Activity implements OnClickListener{

 Button MobileData,wifi;
 boolean status;
 CheckForConnection cf;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.connectivity_demo);
  setRef();
 }

 private void setRef()
 {
  // TO set Refrence to the xml button object.
  MobileData = (Button) findViewById(R.id.CD_bt_mdata);
  wifi = (Button) findViewById(R.id.CD_bt_wifi);
  MobileData.setOnClickListener(this);
  wifi.setOnClickListener(this);
  
 }

 @Override
 public void onClick(View v)
 {
  // Get Which button is clicked by user
  switch (v.getId())
  {
   case R.id.CD_bt_mdata:
    cf = new CheckForConnection();
    status = cf.getMobileDataStatus(ConnectivityDemo.this);
    if(status)
     Toast.makeText(ConnectivityDemo.this,"Data Connection is On.", Toast.LENGTH_LONG).show();
    else
     Toast.makeText(ConnectivityDemo.this,"Data Connection is Off", Toast.LENGTH_LONG).show();
   break;

   case R.id.CD_bt_wifi:
    cf= new CheckForConnection();
    status = cf.getWifiStatus(ConnectivityDemo.this);
    if(status)
     Toast.makeText(ConnectivityDemo.this,"Wifi Connection is On.", Toast.LENGTH_LONG).show();
    else
     Toast.makeText(ConnectivityDemo.this,"Wifi Connection is Off.", Toast.LENGTH_LONG).show();
   break;
   
  default:
   break;
  }
  
 }

}
Step-4 : i have created another class CheckForConnection which actually check weather mobile data or wifi is on or not. in android you can not do network connectivity task on main thread so to perform network task i have created this class. this is the main and handy point because if you create Broad cast Receiver you have to register it and you have to add entry in manifest file also but if you forget any of this its like a burden for you. and if you create service in your application it runs continuously. so that's why i choose this way  to make yor work easy. now create new class CheckForConnection.java. and copy below code in it.
CheckForConnection.java
package com.example.samplecollection;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class CheckForConnection
{
 
    public static boolean getWifiStatus(Context context) 
    {
        // To get System Connectivity status
     ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork)
        {
         // Check For Wifi Status 
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return true;
            else
             return false;
        } 
        
        return false;
    }

    public static boolean getMobileDataStatus(Context context) 
    {
        // To get System Connectivity status
     ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork)
        {
         // Check For Mobile Data Status  
            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return true;
            else
             return false;
        } 
        
        return false;
    }
    
 
}


Screen Shots
androprogrammer
androprogrammer.com

Now just run your application and check weather it works.  i hope you understand the way i have done this so you can implement in your application. if you have any query or problem ask in below comment box.

Keep coding...
Search Functionality the best thing we use to find information fast and easy. well in your application if you have long list of information and you want provide search function in your application. it may affect your application credits. user get bored after so much scroll in list. So to add search functionality you have two option One is using Action bar search functionality and Second is alert box that ask for query and then you search on the basis of that. one main thing about this Search function is you have to use in built layout of list view in order to work it (My opinion). 

Steps
  • Create New Application and give name it ListViewSearch and Do next. 
    • minSdkVersion="17” 
    • targetSdkVersion="17". 
  • Give activity name – Main.java and main.xml. 
  • Go to main.xml and paste the below code.
Main.xml


    
    


Now Go to menu > main.xml file and put below code in it.
 
 

Action bar was introduce in Android 3.0 version so if you are creating app that works on gingerbread and all version you have to add search view above list view or you can use action bar sherlock. you can check out my tutorial on action bar sherlock for more.now go to your class file and put below code.
Main.java
package com.androprogrammer.app3;

import android.os.Bundle;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.text.TextUtils;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

public class Main extends Activity implements OnQueryTextListener{

 ListView lv;
 CustomAdapter adapter;
 String temp[] = {"Gplus","Facebook","Instagram","Linkdin","Pintrest","Twitter","Snapchat","Skype"};
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  lv = (ListView) findViewById(R.id.listView1);
  lv.setAdapter(new ArrayAdapter < string >(getApplicationContext(),android.R.layout.simple_list_item_1,temp));
  lv.setTextFilterEnabled(true);
  
 }

 @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);
  SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
        SearchView searchView = (SearchView) menu.findItem(R.id.menu_item_search).getActionView();

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setSubmitButtonEnabled(true);
        searchView.setOnQueryTextListener(this);

        return super.onCreateOptionsMenu(menu);
 }

 @Override
 public boolean onQueryTextChange(String newText)
 {
  // this is your adapter that will be filtered
      if (TextUtils.isEmpty(newText))
      {
            lv.clearTextFilter();
        }
      else
      {
            lv.setFilterText(newText.toString());
        }
        
      return true;
 }

 @Override
 public boolean onQueryTextSubmit(String query) {
  // TODO Auto-generated method stub
  return false;
 }

}
Screen Shot

As you can see your query display in below Box and it also filter your list view adapter. that's it now run your application and see it works with your tweak or not. if you have any query or problem with it post it in below comment box. i have solved many problems that are still on stack overflow and many forums. you can suggest or share this link with your friends.
if you like the blog subscribe to our blog or like us on facebook or Google+.
Keep coding..

Download Code
In Gallery Application I hope you have used images it to swipe all images in your smartphone.Today in this tutorial how you can achieve this in your application. To add Gesture in your image switcher you have to override onTouchEvent method. this will allow you to get how and what gesture performed. i am using Cursor adapter to fetch all images from SD card. if you don't know about it check out My Tutorial on How to Fetch Images From Storage ? 

Steps
  1. Create New Application and give name it ImageSwitcher and Do next. 
    1. minSdkVersion="17” 
    2. targetSdkVersion="17". 
  2. Give activity name – Main.java and main.xml. 
  3. Go to main.xml and paste the below code.
Main.xml


    

        
       
        
    


Now your layout is set. Now Copy paste below Code in your Main.java file. in java file i have overridden onTouchEvent Method. that will accept parameter as event that user have done. In create method i have created cursor that will fetch images from SD card. some time it won't work. if you have same problem you have to add onfilling method.in image view i have set scale type as center crop that will stretch images from center and display but you can set different parameters in it .that will also accept Touch event as parameter and then you can do swipe operation.
Main.java
package com.example.samplecollection;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MotionEvent;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;

public class ViewFlipper_Demo extends Activity {

 ImageSwitcher Switch;
 ImageView images;
 float initialX;
 private Cursor cursor;
 private  int columnIndex, position = 0;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.view_flipper);
  Switch = (ImageSwitcher) findViewById(R.id.imageSwitcher1);
  images = (ImageView) findViewById(R.id.imageView1);
  String[] projection = {MediaStore.Images.Thumbnails._ID};
     cursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.Thumbnails._ID + "");
     columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  // TODO Auto-generated method stub
  switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            initialX = event.getX();
            break;
        case MotionEvent.ACTION_UP:
            float finalX = event.getX();
            if (initialX > finalX)
            {
             cursor.moveToPosition(position);
             int imageID = cursor.getInt(columnIndex);
             images.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
             //images.setBackgroundResource(R.drawable.mb__messagebar_divider);
                 Switch.showNext();
                 Toast.makeText(getApplicationContext(), "Next Image", 
                       Toast.LENGTH_LONG).show();
                 position++;
            } 
            else
            {
             if(position > 0)
             {
              cursor.moveToPosition(position);
              int imageID = cursor.getInt(columnIndex);
              images.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
              //images.setBackgroundResource(R.drawable.ic_launcher);
              Toast.makeText(getApplicationContext(), "previous Image", 
                     Toast.LENGTH_LONG).show();
              Switch.showPrevious();
              position= position-1;
             }
             else
             {
              Toast.makeText(getApplicationContext(), "No More Images To Swipe", 
                      Toast.LENGTH_LONG).show();
             }
            }
            break;
        }
        return false;
 }

}

Screen Shots


As you can see toast message will display when you swipe gesture on image switcher. copy paste all above code and change name as per your project. if you like this tutorial subscribe to my blog for future updates and best tutorials on android.
Keep Coding..