Share your knowledge

Saturday 11 March 2017

Android External Storage

There are several ways(Shared preferences, Internal storage, External storage, SQLite) to save data in android. Here we will discuss about Internal Storage.

Here is our final output:





Here you can download the source code: download

External storage is used to write and read data. User has a permission to access these files at anytime.

Primary External Storage: Inbuilt shared storage

Second External Storage: Removable storage (Ex: SD Card)

1. Open AndroidManifest.xml and below two permissions


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


2. Open activity_main.xml and paste below code:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.externalstorage.MainActivity">


    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:fontFamily="monospace"
        android:hint="Write some data here..."
        android:paddingLeft="10dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/file_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:padding="10dp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/file_path"
        android:gravity="center">

        <Button
            android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="save" />

        <Button
            android:id="@+id/read"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/save"
            android:text="read" />

    </RelativeLayout>


</RelativeLayout>



3. Open MainActivity.java and paste below code



package com.externalstorage;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

    private EditText data;
    private Button save, read;
    private TextView filePathTextView;

    private String fileName = "noteFile.txt";
    private String filePath = "myStore";
    private File noteFile;
    private StringBuilder dataBuilder = new StringBuilder();

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

        data = (EditText) findViewById(R.id.editText);

        save = (Button) findViewById(R.id.save);
        read = (Button) findViewById(R.id.read);

        filePathTextView = (TextView) findViewById(R.id.file_path);


        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (data.getText().toString().length()>0){
                    try {
                        FileOutputStream fileOutputStream = new FileOutputStream(noteFile);

                        fileOutputStream.write(data.getText().toString().getBytes());

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

                    filePathTextView.setText("");
                    filePathTextView.setText("noteFile.txt file saved to external storage");

                }
                else{
                    Toast.makeText(MainActivity.this,"Enter some data",Toast.LENGTH_SHORT).show();
                }


            }
        });

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    FileInputStream fileInputStream = new FileInputStream(noteFile);

                    //creating instance of DataInputStream
                    DataInputStream dataInputStream = new DataInputStream(fileInputStream);

                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));
                    String line;

                    while ((line=bufferedReader.readLine())!=null){
                        dataBuilder.append(line);
                    }

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

                filePathTextView.setText("");
                filePathTextView.setText("noteFile.txt data recieved from external storage");

                data.setText(dataBuilder.toString());
            }
        });


        //checking whether external storage is avialble or not
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            //external storage is not available and is not writable, so we are making save button as not clickable

            save.setEnabled(false);
        } else {

            //if external storage is avilable and is writable
            noteFile = new File(getExternalFilesDir(filePath),fileName);
        }
    }

    private static boolean isExternalStorageAvailable() {

        /**
         * Returns the current state of the primary shared/external storage media.
         *
         * @see #getExternalStorageDirectory()
         * @return one of {@link #MEDIA_UNKNOWN}, {@link #MEDIA_REMOVED},
         *         {@link #MEDIA_UNMOUNTED}, {@link #MEDIA_CHECKING},
         *         {@link #MEDIA_NOFS}, {@link #MEDIA_MOUNTED},
         *         {@link #MEDIA_MOUNTED_READ_ONLY}, {@link #MEDIA_SHARED},
         *         {@link #MEDIA_BAD_REMOVAL}, or {@link #MEDIA_UNMOUNTABLE}.
         */
        String exeStoragestate = Environment.getExternalStorageState();

        if (exeStoragestate.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    private static boolean isExternalStorageReadOnly() {
        //if storage is only for read, then we can't do any write operations

        String exeStorageState = Environment.getExternalStorageState();

        if (exeStorageState.equalsIgnoreCase(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            return true;
        }
        return false;
    }
}


Android Internal Storage Example

There are several ways(Shared preferences, Internal storage, External storage, SQLite) to save data in android. Here we will discuss about Internal Storage.

Note: Saving files to the internal storage are private to the application, and other applications will not have access to these files.

Output will look like below:



Download code from here: internal storage

1. Create a project and name it as Internal Storage

2. Open activity_main.xml and paste below code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.internalstorage.MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:fontFamily="monospace"
        android:hint="Enter some data here"
        android:paddingLeft="10dp"
        android:textStyle="bold" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:layout_marginTop="20dp"
        android:gravity="center">

        <Button
            android:id="@+id/write"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="write" />

        <Button
            android:id="@+id/read"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/write"
            android:gravity="center"
            android:text="read" />
    </RelativeLayout>

</RelativeLayout>

3. Open MainActivity.java and paste below code



package com.internalstorage;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private EditText enteredData;
    private Button write, read;

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

        enteredData = (EditText) findViewById(R.id.editText);

        write = (Button) findViewById(R.id.write);
        read = (Button) findViewById(R.id.read);

        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (enteredData.getText().toString().length() > 0) {
                    writeData(enteredData.getText().toString());
                } else {
                    showMessage();
                }

            }
        });


        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                enteredData.setText(readData());
            }
        });
    }

    private void showMessage() {
        Toast.makeText(MainActivity.this, "Please enter some data", Toast.LENGTH_SHORT).show();
    }

    private void writeData(String data) {

        try {
            //Using FileOutputStream we can write data to the specified file
            //openFileOutput method will take file name and mode as parameters, and return instance of fileOutputStream

            //openFileOutput method is used to create and save a file
            FileOutputStream fileOutputStream = openFileOutput("notes", MODE_PRIVATE);
            fileOutputStream.write(data.getBytes());
            fileOutputStream.close();

            Toast.makeText(MainActivity.this,"Data saved successfully",Toast.LENGTH_SHORT).show();

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

    }

    private String readData() {

        int c;
        StringBuilder data = new StringBuilder();
        try {
            //openFileInput method is used to open and read a file
            FileInputStream fileInputStream = openFileInput("notes");
            //checking for end of file
            while ((c = fileInputStream.read()) != -1) {
                data.append(Character.toString((char) c));
            }
            fileInputStream.close();

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

        return data.toString();
    }
}








Android ListView

ListView: is a View which groups several items and display them in a vertical scrollable list.

Adapter: Adapter is bridge between UI component and the data which fills that UI component.

Out put will look like below:




Here is the source codelistview

1. Create Project with name ListView with Activity name as MainActivity.java.

2. Open activity_main.xml and paste below code(for listview)

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.listview.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listview"
        >
        
    </ListView>

</RelativeLayout>



2. Open strings.xml and paste below code.


    <string-array name="friends">

        <item>Friend A</item>
        <item>Friend B</item>
        <item>Friend C</item>
        <item>Friend D</item>
        <item>Friend E</item>
        <item>Friend F</item>
        <item>Friend G</item>
        <item>Friend H</item>
        <item>Friend I</item>
        <item>Friend J</item>
        <item>Friend K</item>
        <item>Friend L</item>
        <item>Friend M</item>
        <item>Friend N</item>
        <item>Friend O</item>
        <item>Friend P</item>

    </string-array>


2. create list_item inside res ->values
paste below code


<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/friend_name"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:padding="10dp"
    android:text="asdf"
    android:layout_centerHorizontal="true"
    android:textSize="20dp"
    android:textAllCaps="true"
    android:textStyle="bold" >
</TextView>

3. Open MainActivity.java and paste below code


package com.listview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //creating object of listview
        listView = (ListView)findViewById(R.id.listview);

        //getting string array from resourses(values->strings.xml->friends)
       final String[] friends = getResources().getStringArray(R.array.friends);

        //creating array adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,friends);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //showing toast message
                Toast.makeText(getApplicationContext(),friends[position],Toast.LENGTH_LONG).show();

            }
        });
    }
}








Android Implicit and Explicit Intents

Intents: Intents are used to start components (activity, service, or broadcast receivers) or send data between one component to other component.

Here is the output:



Download source code from here: Intents example

Explicit Intent: 
1. We need to specify name of the component.
2. Explicit intents are used to start the components in the same application
3. Below is the example to start WelcomeActivity



Intent explicitIntent = new Intent(MainActivity.this, WelcomeActivity.class);
startActivity(explicitIntent);



Implicit Intent:


1. Will not specify name of the component
2. System automatically shows the applications(using data in intent filters of other applications) which can handle our task.
3. when starting implicit intent, and if there is no application which can handle your task, then app may crash, so before starting the activity, we have to check whether any application is there to handle our task using resolveActivity.





Example:1

1. suppose we want to view my blogspot("http://andytechs.blogspot.in/")
2. we need webview to load this url
3. instead of using our own webview, i will ask for the system to open any application which canhandle my task(opening that url in the webview)
4. this can be done by using Actions
5. During an implicit intent, the Android system searches for all the registered
components(through intent filters) for the specific action and data type.


If only one component is found, that is triggered but when several of them are identified a dialog ispresented to the user from which he can make a suitable selection.

Intent implicitIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://andytechs.blogspot.in/"));
startActivity(implicitIntent);

  
Example2:

1. let suppose we want to share(send) data in gmail, whatsapp, facebook etc...
2. specify the action(send)
3. setType is used to set the MIME type(In the previous example, we passed url and the system determines theappropriate MIME type required bye the intent.
4. But in the second example we should specify the MIME type using setType(which helps android in determiningwhich activivities should recieve the intent.
5. put extra is used to put the data which we want to share


Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,"Welcome to android learning tutorials by suresh yadam");

startActivity(shareIntent);