Open top menu




How to Integration YouTube channel in android app programmatic?


In this tutorial we will explain how to integrate youtube channel  in android and how to play YouTube videos in your app.

Step 1:-First you can enabled youtube API YouYube Android Player API  provide by google.

Please follow some Step and obtain google Developer API Key.

1. you can download API client library an JavaDocs.

2.Go to Google developer Console and create New Project and registering your application .

3.On the left-sidebar, select Dashboard and Enable API.

4.On the left-sidebar, select Library and select YouTube Data Api. then you check api enable or not.

5.On the left-sidebar, select Credential and Create new Key under public acess.







select Create Credential button then select RESTRIC KEY.

Open new settings..



select Android App Radio button and save. then generate API KEY and used this key in your android application..




6. Then you can add YouTubeAndroidApi.jar file in lib folder and compile in android studio and you can check in Gradle dependency add or not.


dependencies {
   .........
.......
......
    compile files('libs/YouTubeAndroidPlayerApi.jar')
}










7. Add Internet permission in manifest.xml file .


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





8. you can create Config  java class.
............................................................................................................
public class Config {
    public static final String _KEY= "AIzaSyDD5REJaO1Qu2y56v6QUW1FuGbnyariPI8";
    public static final String YOUTUBE_VIDEO_CODE = "CUciBrtqFGM";
}



............................................................................................................



9.you can create activity_main.xml
............................................................................................................
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:tools="http://schemas.android.com/tools"    
android:layout_width="match_parent"    
android:layout_height="match_parent" >


    
<LinearLayout        
android:layout_width="fill_parent"        
android:layout_height="wrap_content"        
android:layout_centerInParent="true"        
android:layout_marginLeft="30dp"        
android:layout_marginRight="30dp"        
android:orientation="vertical" >

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

            
<com.google.android.youtube.player.YouTubePlayerView                
android:id="@+id/youtube_view"               
 android:layout_width="match_parent"                
android:layout_height="wrap_content"                
android:layout_marginBottom="30dp" >

            
</com.google.android.youtube.player.YouTubePlayerView>

        
</LinearLayout>


    
</LinearLayout>

</RelativeLayout>
............................................................................................................

10. MainActivity.java
............................................................................................................

public class MainActivity extends YouTubeBaseActivity implements        YouTubePlayer.OnInitializedListener {

    private static final int RECOVERY_DIALOG_REQUEST = 1;
    private YouTubePlayerView youTubeView;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
        youTubeView.initialize(Config._KEY, this);

    }

    @Override    public void onInitializationFailure(YouTubePlayer.Provider provider,
                                        YouTubeInitializationResult errorReason) {
        if (errorReason.isUserRecoverableError()) {
            errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
        } else {
            String errorMessage = String.format("some error...", errorReason.toString());
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
        }
    }

    @Override    public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                        YouTubePlayer player, boolean wasRestored) {
        if (!wasRestored) {
            player.loadVideo(Config.YOUTUBE_VIDEO_CODE);
            player.setPlayerStyle(PlayerStyle.CHROMELESS);
        }
    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RECOVERY_DIALOG_REQUEST) {
            getYouTubePlayerProvider().initialize(Config.DEVELOPER_KEY, this);
        }
    }

    private YouTubePlayer.Provider getYouTubePlayerProvider() {
        return (YouTubePlayerView) findViewById(R.id.youtube_view);
    }

}
............................................................................................................
Read more


What is a XSream ?

XSream :-  XStream is a Simple Java Based Library to Serialize Java Object to XML. XStream is a light weight, fastest and provide Default Maping for most the object to serialize.

 XStream serializes used some internal fields e.g- private ,final, non-public and inner class. XStream Provide Security issues etc.

Example- Show xml formate.

<com.project.example.makexmlapp.Person>
                                                                   
<Name>Android Beginner point</Name>
                                                                   
<Number>120-4122333</Number>

                                                                 </com.project.example.makexmlapp.Person>


Explain:- How to implement XStream Xml step by step?

First you can add .jar file inside lib folder our android project.

   xstream-1.4.4.jar    





 Create Student class.

Student.Java
............................................................................................................
public class Student { public  String Name;
    public String RollNumber;
    public String Section;
    public String ContactNumber;


    public Student(String Name,String RollNumber,
                     String Section,String ContactNumber){
        this.Name=Name;
        this.RollNumber=RollNumber;
        this.Section=Section;
        this.ContactNumber=ContactNumber;
    }

    public Student(){

    }

    public String getRollNumber() {
        return RollNumber;
    }

    public void setRollNumber(String rollNumber) {
        RollNumber = rollNumber;
    }

    public String getSection() {
        return Section;
    }

    public void setSection(String section) {
        Section = section;
    }

    public String getContactNumber() {
        return ContactNumber;
    }

    public void setContactNumber(String contactNumber) {
        ContactNumber = contactNumber;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }


}
............................................................................................................

activity_main.xml
............................................................................................................

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"     >

    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="15dp"        android:textStyle="bold"        android:id="@+id/text"/>


</RelativeLayout>
............................................................................................................

MainActivity.java
............................................................................................................
public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView vieatxt=(TextView)findViewById(R.id.text);

       try {
           Student record=new Student("Rohit Kumar", 
                   "4122333","B","+91 7953568756");
           XStream xstream = new XStream();
           String xml = xstream.toXML(record);
           Log.i("Xml", xml);
           vieatxt.setText("Output:"+"\n\n"+xml);

       }catch (Exception e){
           e.printStackTrace();
       }



    }
}
............................................................................................................

 Output:-


<com.project.example.makexmlapp.Student>
                                                                     
<ContactNumber>+91 7953568756</ContactNumber> 

<Name>Rohit Kumar</Name>
                                                                     <RollNumber>4122333</RollNumber>
                                                                    
<Section>B</Section>
                                                                   </com.project.example.makexmlapp.Student>   

Read more


HOW TO READ AND WRITE FILE  INTERNAL STORAGE ?


activity_main.xml.
............................................................................................................
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:tools="http://schemas.android.com/tools"    
android:layout_width="match_parent"    
ndroid:layout_height="match_parent"    
android:orientation="vertical"    
android:layout_gravity="center"    
android:layout_margin="6dp"    
tools:context=".MainActivity">

    
<TextView        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:textColor="#066001"        
android:gravity="center"        
android:textStyle="bold"        
android:textSize="20dp"        
android:layout_margin="10dp"        
android:text="Android Beginner point"/>

    
<TextView        
android:layout_width="fill_parent"        
android:layout_height="wrap_content"        
android:gravity="center"        
android:layout_marginTop="30dp"        
android:textAlignment="center"        
android:text="Android Read/Write File" />

    
<EditText        
android:layout_width="fill_parent"        
android:layout_height="wrap_content"        
android:id="@+id/fname"        
android:hint="Text File Name" />

    
<EditText        
android:layout_width="fill_parent"        
android:layout_height="wrap_content"        
android:id="@+id/ftext"        
android:layout_marginTop="10dp"        
android:hint="Write In Text File " />
    
<Button        
android:layout_width="100dp"        
android:layout_height="wrap_content"        
android:id="@+id/btnwrite"        
android:layout_gravity="center_horizontal"        
android:text="Write File" />

    
<TextView        
android:layout_width="fill_parent"        
android:layout_height="1dp"        
android:layout_marginTop="40dp"         
android:background="#066001" />
    
<Button        
android:layout_width="100dp"        
android:layout_height="wrap_content"        
android:id="@+id/btnread"        
android:layout_gravity="center_horizontal"        
android:text="Read File" />

    
<TextView        
android:layout_width="fill_parent"        
android:layout_height="wrap_content"        
android:textSize="36dp"        
android:id="@+id/filecon" />

</LinearLayout>
............................................................................................................


MainActivity
............................................................................................................
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends Activity {
    EditText editTextFileName,editTextData;
    Button saveButton,readButton;
    TextView readtext;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextFileName=(EditText)findViewById(R.id.fname);
        editTextData=(EditText)findViewById(R.id.ftext);
        saveButton=(Button)findViewById(R.id.btnwrite);
        readButton=(Button)findViewById(R.id.btnread);
        readtext=(TextView)findViewById(R.id.filecon) ;
        //Performing Action on Read Button        saveButton.setOnClickListener(new OnClickListener(){

            @Override            public void onClick(View arg0) {
                String filename=editTextFileName.getText().toString();
                String data=editTextData.getText().toString();

                FileOutputStream fos;
                try {
                    fos = openFileOutput(filename, Context.MODE_PRIVATE);
                    fos.write(data.getBytes());
                    fos.close();

                    Toast.makeText(getApplicationContext(),filename + " saved",
                            Toast.LENGTH_LONG).show();


                } catch (FileNotFoundException e) {e.printStackTrace();}
                catch (IOException e) {e.printStackTrace();}

            }

        });

        //Performing Action on Read Button        readButton.setOnClickListener(new OnClickListener(){

            @Override            public void onClick(View arg0) {
                String filename=editTextFileName.getText().toString();
                StringBuffer stringBuffer = new StringBuffer();
                try {
                    //Attaching BufferedReader to the FileInputStream by the help of InputStreamReader                    BufferedReader inputReader = new BufferedReader(new InputStreamReader(
                            openFileInput(filename)));
                    String inputString;
                    //Reading data line by line and storing it into the stringbuffer                    while ((inputString = inputReader.readLine()) != null) {
                        stringBuffer.append(inputString + "\n");
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
              readtext.setText(stringBuffer.toString());
            }

        });
    }


}
............................................................................................................


Read more





<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:tools="http://schemas.android.com/tools"    
android:id="@+id/activity_main"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:paddingBottom="@dimen/activity_vertical_margin"    
android:paddingLeft="@dimen/activity_horizontal_margin"    
android:paddingRight="@dimen/activity_horizontal_margin"    
android:paddingTop="@dimen/activity_vertical_margin"    
android:gravity="center">


    
<ProgressBar        
style="?android:attr/progressBarStyleLarge"        
android:layout_width="wrap_content"        
android:layout_height="wrap_content"        
android:layout_centerVertical="true"        
android:layout_centerHorizontal="true"        
android:indeterminateTintMode="src_atop"        
android:indeterminateTint="@color/colorAccent"        
android:id="@+id/progressBar3" />

    
<ProgressBar        
style="?android:attr/progressBarStyle"        
android:layout_width="wrap_content"        
android:layout_height="wrap_content"        
android:indeterminateTintMode="src_atop"        
android:indeterminateTint="@color/colorPrimary"        
android:layout_centerVertical="true"        
android:layout_centerHorizontal="true"        
android:id="@+id/progressBar" />

    
<ProgressBar        
style="?android:attr/progressBarStyleLarge"        
android:layout_width="200dp"        
android:layout_height="200dp"        
android:indeterminateTintMode="src_atop"        
android:indeterminateTint="@color/colorPrimary"        
android:layout_centerVertical="true"        
android:layout_centerHorizontal="true"        
android:id="@+id/progressBar4" />


</RelativeLayout>











Read more


Explain:-How to get Internal and External Memory Size Programmatically in Android Device ?

explain step by step....

1. you can check  internal & external memory is exist or not .


public static boolean externalMemoryAvailable() {
    return android.os.Environment.
            getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED);
}


2. get Internal memory .


 public static String getTotalInternalMemorySize() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long BlockSize = stat.getBlockSize();
    long TotalBlocks = stat.getBlockCount();
    return formatSize(TotalBlocks * BlockSize);
}


3.get External memory .

public static String getTotalExternalMemorySize() {
    if (externalMemoryAvailable()) {
        File path = Environment.
                getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long BlockSize = stat.getBlockSize();
        long TotalBlocks = stat.getBlockCount();
        return formatSize(TotalBlocks * BlockSize);
    } else {
        return ERROR;
    }
}


4. Convert Memory  size MB & KB Format.

 public static String formatSize(long size) {
        String suffixSize = null;

        if (size >= 1024) {
            suffixSize = "KB";
            size /= 1024;
            if (size >= 1024) {
                suffixSize = "MB";
                size /= 1024;
            }
        }

        StringBuilder BufferSize = new StringBuilder(
                Long.toString(size));

        int commaOffset = BufferSize.length() - 3;
        while (commaOffset > 0) {
            BufferSize.insert(commaOffset, ',');
            commaOffset -= 3;
        }

        if (suffixSize != null) BufferSize.append(suffixSize);
        return BufferSize.toString();
    }
}


 
Read more


Explain:-How to Convert Memory size in MB & KB  Format ?


In this tutorial implement conversion size in MB & KB format parameter type String method, below code . and explain how to Pass External And Internal Memory size  in this method..


// get Internal memory size...

public static String getTotalInternalMemorySize() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long totalBlocks = stat.getBlockCount();
    return formatSize(totalBlocks * blockSize);// pass memory size in this method
}








// format Convert Method.......
public static String formatSize(long size) {
    String suffixSize = null;

    if (size >= 1024) {
        suffixSize = "KB";
        size /= 1024;
        if (size >= 1024) {
            suffixSize = "MB";
            size /= 1024;
        }
    }

    StringBuilder BufferSize = new StringBuilder(
            Long.toString(size));

    int commaOffset = BufferSize.length() - 3;
    while (commaOffset > 0) {
        BufferSize.insert(commaOffset, ',');
        commaOffset -= 3;
    }

    if (suffixSize != null) BufferSize.append(suffixSize);
    return BufferSize.toString();
}





Read more


Get All hardware and software Device Information In ListView .For Example:- Android device Storage , SDK Version,Manufacture Name,Model Number ,Serial Number etc


In this blog we will explain how to get android device information programmatically .explain step by step..........

first you can add permission in android manifest file.


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

activity_main.xml
...........................................................................................................
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:tools="http://schemas.android.com/tools"    
android:id="@+id/activity_main"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:paddingBottom="@dimen/activity_vertical_margin"   
 android:paddingLeft="@dimen/activity_horizontal_margin"    
android:paddingRight="@dimen/activity_horizontal_margin"    
android:paddingTop="@dimen/activity_vertical_margin">
    
    
<TextView        
android:layout_width="fill_parent"        
android:layout_height="50dp"        
android:gravity="center"       
 android:textSize="20dp"        
android:textStyle="bold"        
android:textColor="@android:color/white"        
android:background="@color/colorAccent"        
android:text="Hardware/ Software Details"        
android:id="@+id/textView" />

    
<ListView        
android:layout_width="match_parent"        
android:layout_height="match_parent"        
android:layout_below="@+id/textView"        
android:layout_alignParentStart="true"        
android:id="@+id/listDetails"        
android:layout_marginStart="11dp"        
android:layout_marginTop="4dp" />

</RelativeLayout>
...........................................................................................................

list_row.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">

    
<TextView        
android:text="TextView"        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:padding="5dp"        
android:textSize="16dp"        
android:textStyle="bold"        
android:textColor="#066001"        
android:id="@+id/Hardwarename" />

    
<TextView        
android:text="TextView"        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:padding="5dp"        
android:textSize="13dp"        

android:textColor="#c91616"        
android:id="@+id/HardwarenameDetail" />
</LinearLayout>
...........................................................................................................

DeviceInfo.java
...........................................................................................................
public class DeviceInfo {
    private  String HW_SW_Name;
    private  String HW_SW_Info;

    private DeviceInfo(){

    }

    public DeviceInfo(String HW_SW_Name, String HW_SW_Info){
        this.HW_SW_Info=HW_SW_Info;
        this.HW_SW_Name=HW_SW_Name;

    }

    public String getHW_SW_Name() {
        return HW_SW_Name;
    }

    public void setHW_SW_Name(String HW_SW_Name) {
        this.HW_SW_Name = HW_SW_Name;
    }

    public String getHW_SW_Info() {
        return HW_SW_Info;
    }

    public void setHW_SW_Info(String HW_SW_Info) {
        this.HW_SW_Info = HW_SW_Info;
    }
}
...........................................................................................................

DetailListAdapter.java
..........................................................................................................
public class DetailListAdapter  extends BaseAdapter {
    private Context context;

    ArrayList myList = new ArrayList();

    public DetailListAdapter(Context context, ArrayList<DeviceInfo> myList) {
        this.context = context;
        this.myList = myList;
       // this.arraylist = new ArrayList<ReportItem>();        //this.arraylist.addAll(myList);
    }

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

    @Override    public DeviceInfo getItem(int position) {

        return (DeviceInfo) myList.get(position);
    }

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

    @Override    public View getView(int position, View convertView, ViewGroup parent) {
        DeviceInfo specification = getItem(position);
        final ViewHolder holder;
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) context                    .getSystemService(context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_row, null);
        }
        holder = new ViewHolder();
        try {
            holder.Name = (TextView) convertView.findViewById(R.id.Hardwarename);
            holder.Name.setText(specification.getHW_SW_Name());

            holder.Deatils = (TextView) convertView.findViewById(R.id.HardwarenameDetail);
            holder.Deatils.setText(specification.getHW_SW_Info());

        } catch (Exception e) {
            e.printStackTrace();
        }
        convertView.setTag(holder);
        return convertView;
    }

    static class ViewHolder {

        TextView Name,Deatils ;

    }
}
..........................................................................................................

MainActivity.java
...........................................................................................................
 public class MainActivity extends AppCompatActivity {
    ListView detailList;
    ArrayList<DeviceInfo> DetailList=new ArrayList<>();

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        detailList=(ListView)findViewById(R.id.listDetails);
        try{



       // TelephonyManager tm = (TelephonyManager)getSystemService(this.TELEPHONY_SERVICE);         //   String IMEI=tm.getDeviceId();        ActivityManager actManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
        actManager.getMemoryInfo(memInfo);
        long totalMemory = memInfo.totalMem;

      /************************************************************      Insert hardware and software Device Information In ListView       ************************************************************/
        DetailList.add(new DeviceInfo("SERIAL",Build.SERIAL.toString()));
        DetailList.add(new DeviceInfo("MODEL",Build.MODEL.toString()));
        DetailList.add(new DeviceInfo("ID",Build.ID.toString()));
        DetailList.add(new DeviceInfo("MANUFACTURER",Build.MANUFACTURER.toString()));
        DetailList.add(new DeviceInfo("USER",String.valueOf(Build.USER)));
        DetailList.add(new DeviceInfo("BASE",String.valueOf(Build.VERSION_CODES.BASE)));
        DetailList.add(new DeviceInfo("INCREMENTAL",String.valueOf( Build.VERSION.INCREMENTAL)));
        DetailList.add(new DeviceInfo("SDK",String.valueOf(Build.VERSION.SDK)));
        DetailList.add(new DeviceInfo("BOARD",Build.BOARD.toString()));
        DetailList.add(new DeviceInfo("HOST",Build.HOST.toString()));
        DetailList.add(new DeviceInfo("FINGERPRINT",Build.FINGERPRINT.toString()));
        DetailList.add(new DeviceInfo("VERSION CODE",String.valueOf( Build.VERSION.RELEASE)));
        //DetailList.add(new DeviceInfo("IMEI",IMEI));        DetailList.add(new DeviceInfo("TOTAL RAM SIZE",String.valueOf(totalMemory)));
        DetailList.add(new DeviceInfo("USED RAM SIZE",getTotalRAM()));
        DetailList.add(new DeviceInfo("AVAILABLE INTERNAL MEMORY",getAvailableInternalMemorySize()));
        DetailList.add(new DeviceInfo("TOTAL INTERNAL MEMORY",getTotalInternalMemorySize()));
        DetailList.add(new DeviceInfo("AVAILABLE EXTERNAL MEMORY",getAvailableExternalMemorySize()));
        DetailList.add(new DeviceInfo("TOTAL EXTERNAL MEMORY",getTotalExternalMemorySize()));
        DetailList.add(new DeviceInfo("USED RAM SIZE",getTotalRAM()));
        DetailList.add(new DeviceInfo("ANROID ID", Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID)));
        }catch (Exception e){
            e.printStackTrace();
        }

        DetailListAdapter adapter=new DetailListAdapter(
                this,DetailList);
        detailList.setAdapter(adapter);

    }

    public String getTotalRAM() {
        RandomAccessFile reader = null;
        String load = null;
        DecimalFormat twoDecimalForm = new DecimalFormat("#.##");
        double totRam = 0;
        String lastValue = "";
        try {
            reader = new RandomAccessFile("/proc/meminfo", "r");
            load = reader.readLine();

            // Get the Number value from the string            Pattern p = Pattern.compile("(\\d+)");
            Matcher m = p.matcher(load);
            String value = "";
            while (m.find()) {
                value = m.group(1);
                // System.out.println("Ram : " + value);            }
            reader.close();

            totRam = Double.parseDouble(value);
            // totRam = totRam / 1024;
            double mb = totRam / 1024.0;
            double gb = totRam / 1048576.0;
            double tb = totRam / 1073741824.0;

            if (tb > 1) {
                lastValue = twoDecimalForm.format(tb).concat(" TB");
            } else if (gb > 1) {
                lastValue = twoDecimalForm.format(gb).concat(" GB");
            } else if (mb > 1) {
                lastValue = twoDecimalForm.format(mb).concat(" MB");
            } else {
                lastValue = twoDecimalForm.format(totRam).concat(" KB");
            }



        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            // Streams.close(reader);        }

        return lastValue;
    }

    public static boolean externalMemoryAvailable() {
        return android.os.Environment.
                getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
    }

    public static String getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return formatSize(availableBlocks * blockSize);
    }

    public static String getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return formatSize(totalBlocks * blockSize);
    }

    public static String getAvailableExternalMemorySize()
    {
        if (externalMemoryAvailable()) {
            File path = Environment.
                    getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return formatSize(availableBlocks * blockSize);
        } else {
            return ERROR;
        }
    }

    public static String getTotalExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.
                    getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return formatSize(totalBlocks * blockSize);
        } else {
            return ERROR;
        }
    }

    public static String formatSize(long size) {
        String suffix = null;

        if (size >= 1024) {
            suffix = "KB";
            size /= 1024;
            if (size >= 1024) {
                suffix = "MB";
                size /= 1024;
            }
        }

        StringBuilder resultBuffer = new StringBuilder(
                Long.toString(size));

        int commaOffset = resultBuffer.length() - 3;
        while (commaOffset > 0) {
            resultBuffer.insert(commaOffset, ',');
            commaOffset -= 3;
        }

        if (suffix != null) resultBuffer.append(suffix);
        return resultBuffer.toString();
    }
}
...........................................................................................................



Read more