Android Source Code Projects Download

Android Multiple Tab Layout Example

In this post, you can learn android source code example on tabs in android and about designing multiple tab layout in android. This functionality is mainly used in many android professional application development and you can have a clear observation and description on how to design it with the below example.

1. Create TabLayout_Activity.java file.

TabLayout_Activity.java

package com.asce;

import com.asce.R;

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

@SuppressWarnings("deprecation")
public class TabLayout_Activity extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        TabHost tabHost = getTabHost();
        
        // Tab for Tab A
        TabSpec a = tabHost.newTabSpec("Tab A");
        // Title and Icon for Tab
        a.setIndicator("Tab A", getResources().getDrawable(R.drawable.tab_a));
        Intent a_Intent = new Intent(this, A_Activity.class);
        a.setContent(a_Intent);
        
        // Tab for Tab B
        TabSpec b = tabHost.newTabSpec("Tab B");
        b.setIndicator("Tab B", getResources().getDrawable(R.drawable.tab_b));
        Intent b_Intent = new Intent(this, B_Activity.class);
        b.setContent(b_Intent);
        
        // Adding all TabSpec to TabHost
        tabHost.addTab(a); // Adding Tab A tab
        tabHost.addTab(b); // Adding Tab B tab
    }

}

2. Create A_Activity.java

A_Activity.java

package com.asce;

import com.asce.R;

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

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

}

3. Create A_Activity.java

B_Activity.java

package com.asce;

import com.asce.R;

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

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

}

4. Create tab_a.xml in res - drawable folder

tab_a.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/tab_a_grey"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/tab_a_white" />

</selector>

tab_a_grey & tab_b_grey are images in drawable folder

Similarly create for tab_b.xml

5. Create a_layout.xml in layout folder

a_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  
  <!-- Screen Design for Tab A -->
  <TextView android:text="Contents of Tab A here"
  android:padding="15dip"
  android:textSize="18dip"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"/>
    

</LinearLayout>

Similarly create for b_layout.xml.

6. Now your main.xml.

main.xml

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

7. Your AndroidManifest.xml

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name="com.asce.TabLayout_Activity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <!--  Tab A Activity -->
        <activity android:name="com.asce.A_Activity" />
        
        <!--  Tab B Activity -->
        <activity android:name="com.asce.B_Activity" />
      
    </application>
</manifest>

Play Online Video in Android Device

In this post you can learn android source code example on how to play a video from a URL online from an android device. The basic functionality part is given below. This can be used in android application development for live video streaming from a URL. Using this concept you can develop android apps for online TV viewer application and online video live streaming from a valid URL containing the video.

1. Create a android project and make use of this main.xml file below.

main.xml

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

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <VideoView
            android:id="@+id/video"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center" />

        <ProgressBar
            android:id="@+id/progress"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_gravity="center" />
    </FrameLayout>

</LinearLayout>

2. Now construct your main activity file and make use of the below code.

MainActivity.java

public class MainActivity extends Activity {
      public static String url = "url_of_the_video_that_you_want_to_play";
      private VideoView videoView = null;
      private ProgressBar progress = null;
      private Context ctx = null;
      private MediaController mediaController = null;

     @Override
     public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().setFormat(PixelFormat.TRANSLUCENT);
                setContentView(R.layout.main);
                ctx = this;
                progress = (ProgressBar) findViewById(R.id.progress);
                videoView = (VideoView) findViewById(R.id.video);
                Uri video = Uri.parse(url);
                mediaController = new MediaController(this);
                mediaController.setAnchorView(videoView);
                videoView.setMediaController(mediaController);
                videoView.setVideoURI(video);

                videoView.setOnErrorListener(new OnErrorListener() {

                               @Override
                               public boolean onError(MediaPlayer mp, int what, int extra) {
                                        // TODO Auto-generated method stub
                                        Toast.makeText(ctx, "Error occured", 500).show();
                                        return false;
                               }
                });

                videoView.setOnPreparedListener(new OnPreparedListener() {

                               public void onPrepared(MediaPlayer arg0) {
                                          progress.setVisibility(View.GONE);
                                          videoView.start();
                               }
               });
     }

     @Override
     protected void onDestroy() {
           try {
                   videoView.stopPlayback();
           } catch (Exception e) {
                   //
           }
           super.onDestroy();
     }
}

3. Add USES permission (Internet Permission) to your android manifest xml file without fail for internet access.

AndroidManifest.xml

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

Note : The video does not play in your android emulator. Just compile your code units perfectly and install the .apk file into your android device and start watching the video from the URL which you have embedded.

Read PDF files in Android Source Code

Dear all, In this post you can learn on how to read PDF files in android. Let us consider the below example that the PDF file is located in the SD card of your android phone. The below android source code example is illustrated on how to read this PDF file.

1. Create a Android Project. Download "PDFViewer.jar" and add it in the project build path. You can download the "PDFViewer.jar" from the below link.
https://github.com/jblough/Android-Pdf-Viewer-Library

2. Create an activity java file as below.

activity_second.java

public class activity_second extends PdfViewerActivity {
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
     // TODO Auto-generated method stub
     super.onCreate(savedInstanceState);
    }
   
    public int getPreviousPageImageResource() {
     return R.drawable.left_arrow;
    }
   
    public int getNextPageImageResource() {
     return R.drawable.right_arrow;
    }
   
    public int getZoomInImageResource() {
     return R.drawable.zoom_in;
    }
   
    public int getZoomOutImageResource() {
     return R.drawable.zoom_out;
    }
   
    public int getPdfPasswordLayoutResource() {
     return R.layout.pdf_file_password;
    }
   
    public int getPdfPageNumberResource() {
     return R.layout.dialog_pagenumber;
    }
   
    public int getPdfPasswordEditField() {
     return R.id.etPassword;
    }
   
    public int getPdfPasswordOkButton() {
     return R.id.btOK;
    }
   
    public int getPdfPasswordExitButton() {
     return R.id.btExit;
    }
   
    public int getPdfPageNumberEditField() {
     return R.id.pagenum_edit;
    }
}

3. Now add the below class into your project's main activity and extend this class to ListActivity.

activity_first.java

public class activity_first extends ListActivity {
     
    String[] pdflist;
    File[] imagelist;
    @Override
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     //setContentView(R.layout.main);
   
     File images = Environment.getExternalStorageDirectory();
     imagelist = images.listFiles(new FilenameFilter() {
      public boolean accept(File dir, String name) {
       return ((name.endsWith(".pdf")));
      }
     });
     pdflist = new String[imagelist.length];
     for (int i = 0; i < imagelist.length; i++) {
      pdflist[i] = imagelist[i].getName();
     }
     this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, pdflist));
    }
   
    protected void onListItemClick(ListView l, View v, int position, long id) {
     super.onListItemClick(l, v, position, id);
     String path = imagelist[(int) id].getAbsolutePath();
     openPdfIntent(path);
    }
   
    private void openPdfIntent(String path) {
     try {
      final Intent intent = new Intent(activity_first.this, Second.class);
      intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
      startActivity(intent);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
}

4. Add your Second Activity too in your Android Manifest.xml file without fail.

Check Internet Connection in Android Source Code

You can check the availability of internet connection in android device by using the following source code example. While building android web applications it is necessary to check whether the device has internet connection available or not. This concept is very important and is very useful while developing android applications for validation purposes.

Android Source Code Example to Check Internet Connectivity

1. The below main activity returns the boolean value as true if there is internet connection in the device and if it returns false then there is no internet access in the android device.

public class isNetworkAvailable {

//return boolean as true if there is internet access

 public static boolean isNetworkAvailable(Context context) {
     ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
     if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
           for (int i = 0; i < info.length; i++) {
              if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                 return true;
              }
           }
        }
     }
     return false;
  }
}

2. Please add the USES permission (Internet / Wifi) in the android manifest file.

LED Notification Android Source Code Example

This is a simple android project where you can see LED notification with different colors in the android mobile screen. Please find below the source code example. No special permissions are required for this project. Just you can run with default manifest and layout. Before seeing the demo through android IDE, just lock your phone screen to see the LED illumination.

NotificationLED.java

public class NotificationLED extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  for (int i = 0; i < 8; i++) {
   notif.cancel(1); // clear all previous notification 
   final Notification notification = new Notification();
   if (i == 0){
    notification.ledARGB = Color.MAGENTA;
   }else if (i == 1){
    notification.ledARGB = Color.BLUE;
   }else if (i == 2){
    notification.ledARGB = Color.CYAN;
   }else if (i == 3){
    notification.ledARGB = Color.GRAY;
   }else if (i == 4){
    notification.ledARGB = Color.GREEN;
   }else if (i == 5){
    notification.ledARGB = Color.RED;
   }else if (i == 6){
    notification.ledARGB = Color.WHITE;
   }else if (i == 7){
    notification.ledARGB = Color.YELLOW;
   }
   notification.ledOnMS = 1000;
   notification.flags |= Notification.FLAG_SHOW_LIGHTS;
   notif.notify(1, notification);
   try {
    Thread.sleep(2000);
   } catch (InterruptedException e) {    
    e.printStackTrace();
   }
  }

 }


Android Spinner Example Source Code

Android Spinner helps us to select an item from the drop down menu. In this post let us see an example on how to populate static values in the spinner drop down.

1. First create a new android project.
2. Under "res" folder you can see string.xml file. Add spinner title in this as illustrated in the below example.

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">AndroidSpinner</string>
    <string name="spinner_title">Select</string>
</resources>

3. Now design a simple layout for spinner with a textview as shown below.

main.xml

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

    <!-- Text Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="Players:"
        android:layout_marginBottom="5dp"
    />

    <!-- Spinner Element -->
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/spinner_title"
    />
</LinearLayout>

4. Now let us see the key part, the Main Activity for Android Spinner below.

Here once the item is selected from the spinner drop down, the alert message toast gets displayed with the value what you have selected.

AndroidSpinnerActivity.java

package com.androidspinner;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class AndroidSpinnerActivity extends Activity implements OnItemSelectedListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Spinner Element
        Spinner spinner = (Spinner) findViewById(R.id.spinner);

        //On Spinner Item click listener
        spinner.setOnItemSelectedListener(this);

        // Spinner Values
        List<String> categories = new ArrayList<String>();
        categories.add("Sachin");
        categories.add("Dhoni");
        categories.add("Shewag");
        categories.add("Virat");
        categories.add("Raina");
        categories.add("Dravid");

        // Creating an adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);

        // Spinner Style as a List view with radio buttons
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner.setAdapter(dataAdapter);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // On select spinner item
        String item = parent.getItemAtPosition(position).toString();

        // Displaying selected spinner item
        Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();

    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}

5. Call the class name in the activity of your Manifest.xml file and just run it and enjoy playing with spinners and that's it.
My Profile