Sunday, 17 August 2014

Create or Copy Database in Android

No comments :
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 ...  
Read More

Friday, 27 June 2014

Implement Voice input mechanism in android

No comments :
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...
Read More

Sunday, 11 May 2014

Implement Push Notification in Your App

No comments :
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


Read More

Sunday, 23 March 2014

How To Create Application Folder in SD Card ?

1 comment :
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.. 
Read More

Thursday, 13 March 2014

Create Android Dynamic view with Fragments...

No comments :
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...
Read More