Thursday, April 18, 2013

Reading and Writing files to Internal Stoarage

Writing  file to Internal Storage


public static void writeFileInternalStorage(String strWrite, Context context,String fileName)
            {
                    try
                    {
                             // Check if Storage is Readable
                            if (isSdReadable())   // isSdReadable()e method is define at bottom of the post
                            {
                                    String smsfilename = fileName;
                                    FileOutputStream fos = context.openFileOutput(smsfilename,Context.MODE_PRIVATE);
                                    fos.write(strWrite.getBytes());
                                    fos.flush();
                                    fos.close();
                                   
                            }
                    }
                    catch (Exception e)
                    {
                        // Your Code
                    }
            }



Write File to SD Card  




public static void writeFileOnSDCard(String strWrite, Context context,String fileName)
            {


                    try
                    {
                            if (isSdReadable())   // isSdReadable()e method is define at bottom of the post
                            {
                                    String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                                    File myFile = new File(fullPath + File.separator + "/"+fileName);

                                    FileOutputStream fOut = new FileOutputStream(myFile);
                                    OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                                    myOutWriter.append(strWrite);
                                    myOutWriter.close();
                                    fOut.close();
                            }
                    }
                    catch (Exception e)
                    {
                            //do your stuff here
                    }
            }



Read file from Internal Stoarge 




public static String readFileFromSDCard(String fileName,Context context)
            {
                        String stringToReturn = "";
                        try
                        {
                                if(isSdReadable())    // isSdReadable()e method is define at bottom of the post
                                {
                                        String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "/"+fileName;

                                        InputStream inputStream = context.openFileInput(fullPath);
            
                                        if ( inputStream != null )
                                        {
                                                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                                                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                                                String receiveString = "";
                                                StringBuilder stringBuilder = new StringBuilder();
                
                                                while ( (receiveString = bufferedReader.readLine()) != null )
                                                {
                                                        stringBuilder.append(receiveString);
                                                }
                                                inputStream.close();
                                                stringToReturn = stringBuilder.toString();
                                        }
                                }
                        }
                        catch (FileNotFoundException e)
                        {
                                    Log.e("TAG", "File not found: " + e.toString());
                        }
                        catch (IOException e)
                        {
                                Log.e("TAG", "Can not read file: " + e.toString());
                        }
   
                        return stringToReturn;
            }


Read File from SD Card



public static String readFileInternalStorage(String fileName, Context context)
            {
                    String stringToReturn = " ";
                    try
                    {
                            if(isSdReadable())   // isSdReadable()e method is define at bottom of the post
                            {
                                    String sfilename = fileName;
                                    InputStream inputStream = context.openFileInput(sfilename);
            
                                    if ( inputStream != null )
                                    {
                                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                                            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                                            String receiveString = "";
                                            StringBuilder stringBuilder = new StringBuilder();
                
                                            while ( (receiveString = bufferedReader.readLine()) != null )
                                            {
                                                    stringBuilder.append(receiveString);
                                            }
                                            inputStream.close();
                                            stringToReturn = stringBuilder.toString();
                                    }
                            }
                    }
                    catch (FileNotFoundException e)
                    {
                            Log.e("TAG", "File not found: " + e.toString());
                    }
                    catch (IOException e)
                    {
                            Log.e("TAG", "Can not read file: " + e.toString());
                    }
   
                    return stringToReturn;
            }
           

Method to Check whether Storage is Readable


public static boolean isSdReadable()
            {

                    boolean mExternalStorageAvailable = false;
                    try
                    {
                            String state = Environment.getExternalStorageState();

                            if (Environment.MEDIA_MOUNTED.equals(state))
                            {
                                    // We can read and write the media
                                    mExternalStorageAvailable = true;
                                    Log.i("isSdReadable", "External storage card is readable.");
                            }
                            else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
                            {
                                    // We can only read the media
                                    Log.i("isSdReadable", "External storage card is readable.");
                                    mExternalStorageAvailable = true;
                            }
                            else
                            {
                                    // Something else is wrong. It may be one of many other
                                    // states, but all we need to know is we can neither read nor
                                    // write
                                    mExternalStorageAvailable = false;
                            }
                    } catch (Exception ex)
                    {

                    }
                    return mExternalStorageAvailable;
            }


 

Advance Android Topics


                   Customizing Toast In Android 
                   Showing Toast for Longer Time
                   Customizing the Display Time of Toast
                   Using TimePickerDialog and DatePickerDialog In android
                   Animating A Button In Android
                    Populating ListView With DataBase

                    Customizing Checkboxes In Android 
                    Increasin Size of Checkboxes
                    Android ProgressBar
                    Designing For Different Screen Sizes
                    Handling Keyboard Events

More Android Topics:



  

Android : Introduction


       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app


         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


       Activity

                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View

       Toast

                     Customizing Toast In Android
                     Customizing the Display Time of Toast
                     Customizing Toast At Runtime
                     Adding Image in Toast
                     Showing Toast for Longer Time

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android

    ListView:

               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android

      TelephonyManager

                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States In Android
 

    Miscellaneous

                   Notifications In Android
                   How To Vibrate The Android Phone
                   Sending Email In Android
                  Opening a webpage In Browser
                   How to Access PhoneBook In Android
                   Prompt User Input with an AlertDialog

   Storage:  Storing Data In Android


               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 
                           

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android





Android Button Animation Example

The Android Development Tutorials blog contains Basic as well as Advanced android tutorials.Go to Android Development Tutorials to get list of all Android Tutorials.

How To Animate a Button

We need a xml file that will define the Animation.

Create a folder named  "anim"  in res folder

Create a xml file named vanish.xml,  in this file we will define our Animation.

vanish.xml

<set xmlns:android="http://schemas.android.com/apk/res/android" >
   
<scale android:duration="300"     // duration in miliseconds
       android:fromXScale="1.0"    //  X scaling to start from
       android:fromYScale="1.0"    // Y scaling to start from
       android:toXScale="1.5"      
       android:toYScale="1.5"
       android:pivotX="40%"
       android:pivotY="40%"
       android:interpolator="@android:anim/decelerate_interpolator"/>
      

<alpha android:duration="300"
       android:fromAlpha="1.0"
       android:toAlpha="0.0"
       android:interpolator="@android:anim/decelerate_interpolator"/>
   
</set>



In your Activity class create the reference of the Button on which you want apply the animation.

Animation vanish =AnimationUtils.loadAnimation(this,R.anim.vanish);
findViewById(R.id.youButton).startAnimation(vanish).



You can change the following attributes acoording your requirement

      android:duration="300"         
      android:fromXScale="1.0"    
       android:fromYScale="1.0"         
      android:toXScale="1.5"      
       android:toYScale="1.5"
       android:pivotX="40%"
       android:pivotY="40%"


Android Animation Examples:


Animating  ImageViews




Layout Animations
Sliding Between Screen  Using ViewFlipper





More Android Topics

New Advance Topics:
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swap Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation

 Beginning With Android
      Android : Introduction                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage
Working With Incoming Calls                                             DataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog





Getting User Input With Dialogs

Getting User Input With Dialogs In Android

EditText in Dialog

We can create a dialog with Edittext   and other views like Button, CheckBoxes, RadioButtons etc.

For this we need to Create A xml layout and and  inflate it in AlertDialog



                               

<?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" >
   
   
    <EditText
        android:id="@+id/editTextKeywordsToBlock"
        android:hint="Enter 1 or more keywords. Use space berween two keywords"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>

    <LinearLayout
                 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
           
            android:layout_marginTop="10dp">
                 

     <Button
         android:id="@+id/buttonBlockByKeyword"
         android:layout_marginTop="15dp"
         android:layout_weight="1"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="SAVE"
         />
    
      <Button
         android:id="@+id/buttonCancelBlockKeyword"
         android:layout_marginTop="15dp"
         android:layout_weight="1"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="Cancel"
         />
   
     </LinearLayout>
   

</LinearLayout>


And inflate this Layout at run time    like following



final Dialog dialog = new Dialog(this);

                    dialog.setContentView(R.layout.block_by_keyword);
                    dialog.setTitle("Keyword To Block");

                    final EditText editTextKeywordToBlock=(EditText)dialog.findViewById(R.id.editTextKeywordsToBlock);
                    Button btnBlock=(Button)dialog.findViewById(R.id.buttonBlockByKeyword);
                    Button btnCancel=(Button)dialog.findViewById(R.id.buttonCancelBlockKeyword);
                    dialog.show();


Get The DATA:

String input =  editTextKeywordToBlock.getText().toString();

We can set ClickListiner on Buttons As Well

 btnBlock.setOnClickListener(new View.OnClickListener() {
                  
                    @Override
                    public void onClick(View v)
                    {
                         //  Your Code

                    }
            });
                        

Prompt User Input with an AlertDialog

EditText in Dialog

We can create a dialog with Edittext   and other views like Button, CheckBoxes, RadioButtons etc.

For this we need to Create A xml layout and and  inflate it in AlertDialog



                               

<?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" >
   
   
    <EditText
        android:id="@+id/editTextKeywordsToBlock"
        android:hint="Enter 1 or more keywords. Use space berween two keywords"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>

    <LinearLayout
                 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
           
            android:layout_marginTop="10dp">
                 

     <Button
         android:id="@+id/buttonBlockByKeyword"
         android:layout_marginTop="15dp"
         android:layout_weight="1"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="SAVE"
         />
    
      <Button
         android:id="@+id/buttonCancelBlockKeyword"
         android:layout_marginTop="15dp"
         android:layout_weight="1"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="Cancel"
         />
   
     </LinearLayout>
   

</LinearLayout>


And inflate this Layout at run time    like following



final Dialog dialog = new Dialog(this);

                    dialog.setContentView(R.layout.block_by_keyword);
                    dialog.setTitle("Keyword To Block");

                    final EditText editTextKeywordToBlock=(EditText)dialog.findViewById(R.id.editTextKeywordsToBlock);
                    Button btnBlock=(Button)dialog.findViewById(R.id.buttonBlockByKeyword);
                    Button btnCancel=(Button)dialog.findViewById(R.id.buttonCancelBlockKeyword);
                    dialog.show();


Get The DATA:

String input =  editTextKeywordToBlock.getText().toString();

We can set ClickListiner on Buttons As Well

 btnBlock.setOnClickListener(new View.OnClickListener() {
                  
                    @Override
                    public void onClick(View v)
                    {
                         //  Your Code

                    }
            });
                        

Creating Dialog To Collect User Input

EditText in Dialog

We can create a dialog with Edittext   and other views like Button, CheckBoxes, RadioButtons etc.

For this we need to Create A xml layout and and  inflate it in AlertDialog



                               

<?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" >
   
   
    <EditText
        android:id="@+id/editTextKeywordsToBlock"
        android:hint="Enter 1 or more keywords. Use space berween two keywords"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>

    <LinearLayout
                 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
           
            android:layout_marginTop="10dp">
                 

     <Button
         android:id="@+id/buttonBlockByKeyword"
         android:layout_marginTop="15dp"
         android:layout_weight="1"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="SAVE"
         />
    
      <Button
         android:id="@+id/buttonCancelBlockKeyword"
         android:layout_marginTop="15dp"
         android:layout_weight="1"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="Cancel"
         />
   
     </LinearLayout>
   

</LinearLayout>


And inflate this Layout at run time    like following



final Dialog dialog = new Dialog(this);

                    dialog.setContentView(R.layout.block_by_keyword);
                    dialog.setTitle("Keyword To Block");

                    final EditText editTextKeywordToBlock=(EditText)dialog.findViewById(R.id.editTextKeywordsToBlock);
                    Button btnBlock=(Button)dialog.findViewById(R.id.buttonBlockByKeyword);
                    Button btnCancel=(Button)dialog.findViewById(R.id.buttonCancelBlockKeyword);
                    dialog.show();


Get The DATA:

String input =  editTextKeywordToBlock.getText().toString();

We can set ClickListiner on Buttons As Well

 btnBlock.setOnClickListener(new View.OnClickListener() {
                  
                    @Override
                    public void onClick(View v)
                    {
                         //  Your Code

                    }
            });