Category Archives: Files

How to copy a file to another saved in SDCARD in Android?

Hello all…

This tutorial explains how to copy a file contents to another in Android. The file to copy is saved in SDCARD, however you can change the path to save it in your application sandbox.
if you want to save it in your sandbox, change the path to

/data/data/your_packagename/your_file.extension

Now we will see the layout for the program.


<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".CopyFileActivity" >

    <TextView
        android:id="@+id/tv1"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/tv2"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Copy First file to second" />
    
      <TextView
        android:id="@+id/tv3"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

Now this is the java program that does the copying.

package com.coderzheaven.copyfiletoanother;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class CopyFileActivity extends Activity {

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

		Button btn = (Button) findViewById(R.id.btn1);
		TextView tv1 = (TextView) findViewById(R.id.tv1);
		final TextView tv2 = (TextView) findViewById(R.id.tv2);
		final TextView tv3 = (TextView) findViewById(R.id.tv3);

		final String path1 = Environment.getExternalStorageDirectory()
				+ "/first_file.txt";
		final String path2 = Environment.getExternalStorageDirectory()
				+ "/second_file.txt";

		File file1 = new File(path1);
		tv1.setText("First File  : " + file1.getPath() + "(" + file1.length()
				+ " Bytes)\nFirst file contents : \n" + readFromSD(path1));

		File file2 = new File(path2);
		tv2.setText("Second File  : " + file2.getPath() + "(" + file2.length()
				+ " Bytes)");

		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (copyFile(path1, path2))
					Toast.makeText(getApplicationContext(), "File Copied.",
							Toast.LENGTH_LONG).show();
				else
					Toast.makeText(getApplicationContext(), "File Not Copied.",
							Toast.LENGTH_LONG).show();

				tv3.setText("Second File Contents :" + readFromSD(path2));

			}
		});

	}

	public static boolean copyFile(String from, String to) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(from);
			if (oldfile.exists()) {
				InputStream inStream = new FileInputStream(from);
				FileOutputStream fs = new FileOutputStream(to);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		}
	}

	public String readFromSD(String path) {
		File file = new File(path);
		StringBuilder text = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;
			while ((line = br.readLine()) != null) {
				text.append(line);
				text.append('\n');
			}
		} catch (IOException e) {
		}
		return text.toString();
	}

}

Note : if you are writing to Sdcard, then always give this permission in the AndroidManifest file.

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

Another important thing is here I am not creating the file to copy, simply assuming that the first file is present in the sdcard in the correct path.

Copy File

Copy File

Download complete Android source code from here.

Download the tutorial PDF from here.

How to store an Image from Android to a SQlite and retrieve it?

Hello all…

In today’s post I will show you how to store an image in an SQLite database and retrieve it.

Check out the output after running the program.

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

This is the layout for the MainActivity.

<ScrollView 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"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/get_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Get Image" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:src="@drawable/ic_action_search"
            android:visibility="gone" />

        <Button
            android:id="@+id/save_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Save Image in DB" />

        <Button
            android:id="@+id/read_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Read Image from DB" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            tools:context=".MainActivity" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:layout_marginBottom="40dp"
            android:src="@drawable/ic_action_search" />
    </LinearLayout>

</ScrollView>

Now the code for the Activity.

MainActivity.java

package com.coderzheaven.saveimageindb;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	protected static TextView textView;
	protected static ImageView image1, image2;
	protected Button get_image, save_image, read_image;
	private String selectedImagePath;
	private static final int SELECT_PICTURE = 1;
	String DB_NAME = Environment.getExternalStorageDirectory() + "/test.db";
	String TABLE_NAME = "mytable";

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

		image1 = (ImageView) findViewById(R.id.imageView1);
		image2 = (ImageView) findViewById(R.id.imageView2);
		textView = (TextView) findViewById(R.id.textView1);

		get_image = (Button) findViewById(R.id.get_image);
		get_image.setOnClickListener(this);

		save_image = (Button) findViewById(R.id.save_image);
		save_image.setOnClickListener(this);

		read_image = (Button) findViewById(R.id.read_image);
		read_image.setOnClickListener(this);

	}

	public void onClick(View v) {

		int id = v.getId();
		switch (id) {

		case R.id.get_image:
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					SELECT_PICTURE);
			break;

		case R.id.save_image:
			createTable();
			saveInDB();
			break;

		case R.id.read_image:
			readFromDB();
			break;
		default:
			break;

		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				selectedImagePath = getPath(selectedImageUri);
				System.out.println("Image Path : " + selectedImagePath);
				image1.setVisibility(View.VISIBLE);
				image1.setImageURI(selectedImageUri);
			}
		}
	}

	@SuppressWarnings("deprecation")
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	void createTable() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		String MySQL = "create table if not exists "
				+ TABLE_NAME
				+ " (_id INTEGER primary key autoincrement, name TEXT not null, image BLOB);";
		myDb.execSQL(MySQL);
		myDb.close();
	}

	void saveInDB() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		byte[] byteImage1 = null;
		String s = myDb.getPath();

		myDb.execSQL("delete from " + TABLE_NAME); 			// clearing the table
		ContentValues newValues = new ContentValues();
		String name = "CoderzHeaven";
		newValues.put("name", name);
		try {
			FileInputStream instream = new FileInputStream(selectedImagePath);
			BufferedInputStream bif = new BufferedInputStream(instream);
			byteImage1 = new byte[bif.available()];
			bif.read(byteImage1);
			newValues.put("image", byteImage1);
			long ret = myDb.insert(TABLE_NAME, null, newValues);
			if (ret < 0)
				textView.append("Error");
		} catch (IOException e) {
			textView.append("Error Exception : " + e.getMessage());
		}
		myDb.close();
		textView.append("\n Saving Details \n Name : " + name);
		textView.append("\n Image Size : " + byteImage1.length + " KB");
		textView.append("\n Saved in DB : " + s + "\n");
		Toast.makeText(this.getBaseContext(),
				"Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
	}

	void readFromDB() {
		byte[] byteImage2 = null;
		SQLiteDatabase myDb;
		myDb = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
		Cursor cur = myDb.query(TABLE_NAME, null, null, null, null, null, null);
		cur.moveToFirst();
		while (cur.isAfterLast() == false) {
			textView.append("\n Reading Details \n Name : " + cur.getString(1));
			cur.moveToNext();
		}

		// /////Read data from blob field////////////////////
		cur.moveToFirst();
		byteImage2 = cur.getBlob(cur.getColumnIndex("image"));
		setImage(byteImage2);
		cur.close();
		myDb.close();
		Toast.makeText(this.getBaseContext(),
				"Image read from DB successfully.", Toast.LENGTH_SHORT).show();
		Toast.makeText(this.getBaseContext(),
				"If your image is big, please scrolldown to see the result.",
				Toast.LENGTH_SHORT).show();
	}

	void setImage(byte[] byteImage2) {
		image2.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
				byteImage2.length));
		textView.append("\n Image Size : " + byteImage2.length + " KB");
	}

}

Please leave your valuable comments.

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to read and write files to SDCARD and application SandBox in Android – A complete example?

Here is a complete example of How to read and write files to SDCARD and application SandBox in Android.

First create a new project and inside the mainActivity paste this code.

package com.coderzheaven.filesexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	EditText edittext;
	Button b1, b2, b3, b4;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        edittext = (EditText)findViewById(R.id.ed);
        edittext.setLines(10);
        b1 = (Button)findViewById(R.id.button1);
        b2 = (Button)findViewById(R.id.button2);
        b3 = (Button)findViewById(R.id.button3);
        b4 = (Button)findViewById(R.id.button4);
        
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        b4.setOnClickListener(this);        
        
    }
	@Override
	public void onClick(View v) {
		int id = v.getId();
		MyFile file = new MyFile(v.getContext());
		
		switch(id){
			case R.id.button1:
				if(!edittext.getText().toString().trim().equals("")){
					file.writeToSD(edittext.getText().toString());
				}else{
					Toast.makeText(v.getContext(), "Please enter some contents for the file", Toast.LENGTH_LONG).show();
				}
				break;
				
			case R.id.button2:
				edittext.setText(file.readFromSD());
				break;
			
			case R.id.button3:
				if(!edittext.getText().toString().trim().equals("")){
					file.writeToSandBox(edittext.getText().toString());
				}else{
					Toast.makeText(v.getContext(), "Please enter some contents for the file", Toast.LENGTH_LONG).show();
				}
				break;
				
			case R.id.button4:
				edittext.setText(file.readFromSandBox());
				break;
		}
		
		
		
	}

}

Now create another class named MyFile.java and copy this code into it.

package com.coderzheaven.filesexample;

import java.io. BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class MyFile {

	String TAG = "MyFile";
	Context context;
	public MyFile(Context context){
		this.context = context;
	}
	
	public Boolean writeToSD(String text){
		Boolean write_successful = false;
		 File root=null;  
	        try {  
	            // check for SDcard   
	            root = Environment.getExternalStorageDirectory();  
	            Log.i(TAG,"path.." +root.getAbsolutePath());  
	  
	            //check sdcard permission  
	            if (root.canWrite()){  
	                File fileDir = new File(root.getAbsolutePath());  
	                fileDir.mkdirs();  
	  
	                File file= new File(fileDir, "samplefile.txt");  
	                FileWriter filewriter = new FileWriter(file);  
	                BufferedWriter out = new BufferedWriter(filewriter);  
	                out.write(text);  
	                out.close();  
	                write_successful = true;
	            }  
	        } catch (IOException e) {  
	            Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());  
	            write_successful = false;
	        }  
		return write_successful;
	}
	
	public String readFromSD(){
		File sdcard = Environment.getExternalStorageDirectory();
		File file = new File(sdcard,"samplefile.txt");
		StringBuilder text = new StringBuilder();
		try {
		    BufferedReader br = new BufferedReader(new FileReader(file));
		    String line;
		    while ((line = br.readLine()) != null) {
		        text.append(line);
		        text.append('\n');
		    }
		}
		catch (IOException e) {
		}
		return text.toString();
	}

	@SuppressLint("WorldReadableFiles")
	@SuppressWarnings("static-access")
	public Boolean writeToSandBox(String text){
		Boolean write_successful = false;
		try{
			FileOutputStream fOut = context.openFileOutput("samplefile.txt",
					context.MODE_WORLD_READABLE);
			OutputStreamWriter osw = new OutputStreamWriter(fOut); 
			osw.write(text);
			osw.flush();
			osw.close();
		}catch(Exception e){
			write_successful = false;
		}
		return write_successful;
	}
	public String readFromSandBox(){
		String str ="";
		String new_str = "";
		try{
			FileInputStream fIn = context.openFileInput("samplefile.txt");
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader br=new BufferedReader(isr);
           
			while((str=br.readLine())!=null)
            {
				new_str +=str;
				System.out.println(new_str);
            }            
		}catch(Exception e)
		{			
		}
		return new_str;
	}
}

Now the layout for the xml file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/ed"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
		android:lines="5" android:gravity="top|left" android:inputType="textMultiLine"
		android:scrollHorizontally="false" 
		android:minWidth="10.0dip"
		android:maxWidth="5.0dip"
        android:layout_weight="1"/>


    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Write File to SDCARD" />
    
    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Read File from SDCARD" />
    
    <Button
        android:id="@+id/button3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Write File to Application SandBox" />
    
    <Button
        android:id="@+id/button4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Read File from Application SandBox" />

</LinearLayout>

Note you should give this permission in the AndroidManifest file.

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

OK Done. Now run the project.

To view the files

1. To see the SDCARD
Open File explorer -> expand sdcard (or mnt/sdcard).
2. To see the Application SANDBOX
Open File explorer -> expand data/data/your_package_name/files.

Files Example

Download
.

Please leave your valuable comments on this post.

Join the Forum discussion on this post