This is featured post 1 title

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation test link ullamco laboris nisi ut aliquip ex ea commodo consequat.

This is featured post 2 title

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation test link ullamco laboris nisi ut aliquip ex ea commodo consequat.

This is featured post 3 title

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation test link ullamco laboris nisi ut aliquip ex ea commodo consequat.

This is featured post 4 title

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation test link ullamco laboris nisi ut aliquip ex ea commodo consequat.

This is featured post 5 title

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation test link ullamco laboris nisi ut aliquip ex ea commodo consequat.


Custom Search
Showing posts with label Android Basic. Show all posts
Showing posts with label Android Basic. Show all posts

Bitmap operations like re sizing, rotating bitmap and other operations

0 comments

In programming, Image processing is the most difficult work. All though i am not going to discuss image processing in depth but we will discuss about bitmap basic operation like re sizing, rotating bitmap, how to create bitmap from file , input stream and resource.we will discuss it step by step and finally you will get source in which you can enjoy playing with it. img is the ImageView object in my project.
As we are going to discuss bitmap to we need to study how to avoid Memory Over Flow while using big image


1) Creating bitmap from resource drawable - If we have image in drawable folder then we can easily create bitmap from it. Later in my project i have a image view on which i will set a newly created bitmap

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img);
img.setImageBitmap(bitmap);

2) Creating bitmap from a file stored in sdcard - Give complete string path from sdcard .if you want to select path dynamically then you can see File explorer.

        /**
*Creating bitmap from a file
*Permission needed in manifest
*<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
*/
try{
Bitmap bit=BitmapFactory.decodeFile("file path");
img.setImageBitmap(bit);
}catch(Exception e){
e.getMessage();
}

3) Creating bitmap from URL - Give complete url in to string and create a URL from this

        /**
* Creating bitmap from Input stream
* <uses-permission android:name="android.permission.INTERNET"/>
*/
try{
InputStream is=(new URL("image Url")).openStream();
Bitmap bit=BitmapFactory.decodeStream(is);
img.setImageBitmap(bit);
}catch(Exception e){
e.getMessage();
}

4) Changing bitmap to drawable and drawable to bitmap - Some times we need to change drawable to bitmap and bitmap to drawable

        /**
* Changing drawable to bitmap, android bitmap to drawable
*/
Drawable d=new BitmapDrawable(bitmap);
//use drawable where ever you want
BitmapDrawable bitmDraw=(BitmapDrawable) d;
Bitmap mp=bitmDraw.getBitmap();
//Now use mp where you want

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img);
img.setImageBitmap(bitmap);

5) Rotating a bitmap anticlockwise and clock wise - Matrix is used to rotate bitmap as per our requirement. I have two button to rotate image as you want

        /**
* Rotate a bitmap clockwise and anticlockwise
*/
btn_clock = (Button) findViewById(R.id.btn_clockWise);
btn_clock.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Matrix mMatrix = new Matrix();
Matrix mat=img.getImageMatrix();
mMatrix.set(mat);
mMatrix.setRotate(90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), mMatrix, false);
img.setImageBitmap(bitmap);
}
});
        btn_antiClock = (Button) findViewById(R.id.btn_AnticlockWise);
btn_antiClock.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Matrix mMatrix = new Matrix();
Matrix mat=img.getImageMatrix();
mMatrix.set(mat);
mMatrix.setRotate(-90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), mMatrix, false);
img.setImageBitmap(bitmap);
}
});



6) Zoom in and zoom out image using bitmap scale option - we will scale bitmap and then set it to  image view object that is img in my project code

        btn_zoomin = (Button) findViewById(R.id.btn_in);
btn_zoomin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
zoomScale+=zoomScale;
bitmap=Bitmap.createScaledBitmap(bitmap,bitmap.getWidth()+zoomScale,
bitmap.getHeight()+zoomScale,false);
img.setImageBitmap(bitmap);
}
});
btn_zoom_out = (Button) findViewById(R.id.btn_zoomout);
btn_zoom_out.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
zoomScale-=zoomScale;
bitmap=Bitmap.createScaledBitmap(bitmap,bitmap.getWidth()-zoomScale,
bitmap.getHeight()-zoomScale,false);
img.setImageBitmap(bitmap);
}
});
}

Download source code from here ..please click on advertisement and keep visiting my blog :)


                             Download Source Code


Getting started with Android Database ; Inserting, Updating, deleting.

0 comments

All though we know mobile do not have large memory to save data in comparison of Desktop and Laptop
but data base is highly important in android (and other mobile OS also).
In android we use Sq-lite data base. Sq-lite is light wight and design according to support mobile device limited memory.
First i am listing some basic operation and will explain every thing with example
1) Creating data base - In android, we have an API classes to create it that is  SQLiteOpenHelper to create data base. Best way is to create a different class and extends SQLiteOpenHelper

package com.gu;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHub extends SQLiteOpenHelper {

private static final String dbname = "demo.db";
private static final int version = 2;
public static String Ename="Ename";
public static String Eid="Eid";
public static String Eadd="Eadd";
public static String Emp="Emp";

public DataBaseHub(Context context) {
super(context, dbname, null, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
String employee1 = "create table "+Emp+"("+Eid+" integer primary key,"+Ename+" tex t,"+Eadd+" text)";
db.execSQL(employee1);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

if (oldVersion < newVersion) {
String employee1 = "create table emp("+Eid+" integer,"+Ename+" text,"+Eadd+" t ext)";
db.execSQL(employee1);
}
}
}



Creating a data base Table

String employee1 = "create table "+Emp+"("+Eid+" integer primary key,"+Ename+" text,"+Eadd+" text)";
db.execSQL(employee1);

2)Open Data Base - when we open data base in two way either we want to open data base only for reading or for writing into data base. If we open data base in writing mode then we will get access to reading automatically.

  DataBaseHub dbh=new DataBaseHub(activitycontext);                                       SqliteDatabase db= dbhgetWritableDatabase();                                                    SqliteDatabase db= dbh.getReadableDatabase();

3) Inserting Values into data base - Now we have created data base and open it for performing operation on it so basic operation is to insert value into data base. I have taken table so i will insert values into this table

DataBaseHub dbh=new DataBaseHub(this);
SQLiteDatabase db=dbh.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(DataBaseHub.Eid,101);
cv.put(DataBaseHub.Ename,"Tofeeq");
cv.put(DataBaseHub.Eadd,"142,Ananad Delhi");
long i=db.insert(DataBaseHub.Emp, null, cv);
Log.i("Row ID=",String.valueOf(i));

4) Deleting particular row from data base -  Deleting  particular row in data base is damn simple. We have to specify column name( to identify which row we want to delete)
DataBaseHub dbh=new DataBaseHub(this);
SQLiteDatabase db=dbh.getWritableDatabase();
i=db.delete(DataBaseHub.Emp, DataBaseHub.Eid+"=?",new String[]{"101"});
Log.i("Number of Row=",String.valueOf(i)););

5)Updating a row into data base - Updating row into data base is little bit complicated so i will explain there in code

DataBaseHub dbh=new DataBaseHub(this);
SQLiteDatabase db=dbh.getWritableDatabase();
// Create content values that contains the name of the column you want to update and the value you want to assign to it
ContentValues cv = new ContentValues();
cv.put("my_column", "5");
String where = DataBaseHub.Eid+"=?"; // The where clause to identify which columns to update.
String[] value = { "2" }; // The value for the where clause.
// Update the database (all columns in TABLE_NAME where my_column has a value of 2 will be changed to 5)
db.update(DataBaseHub.Emp, cv, where, value);

6) Reading record from data base - you can read all record by querying a table it will store table records into Cursor. Use cursor method's cusor.movetoNext() cursor.movetToprevious()

DataBaseHub dbh=new DataBaseHub(this);
SQLiteDatabase db = dbh.getReadableDatabase();
Cursor cursor = db.query("Table_name",null,null,null,null,
null, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
//Now you can read record from cursor easily

7) Deleting Table from data base - Deleting table in android data base is very important. E.g if you are making Music Player. Then you need to create dynamic table while you creating play list

DataBaseHub dbh=new DataBaseHub(this);
SQLiteDatabase db=dbh.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

8) Deleting complete data base - all though we do not need this operation generally but in case if you need to delete your data base you can delete easily by using activity context.


context.deleteDatabase(DATABASE_NAME);









Simple example of service in android

0 comments

Service is one of core component of android application. Every one knows service is very important part. we use it but sometimes we do not know exact power and depth of service, today i am going to discuss it in details.
After this article we will also let you know difference between Thread and Service, and how to perform real time task in service


In the end you will also get source code.

Service -A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.


Difference between a Thread , service and asynchronous task


1)  Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.


2)  A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.


3)  An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are two methods that run on UI thread, which is good to update UI components

Other one difference between service and thread is that thread is not intelligent enough to recognize that is it already running or not? Every time you create a new object of thread and start again it will create a new instance and a new thread start running.
But if service is already running and you start again it will not created again.So that is very important difference



Step to create simple service example

Step 1) create a a new project. change your xml to include two button to start and stop service

<?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" >

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="StartService"
android:id="@+id/start"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="StopService"
android:id="@+id/stop" />

</LinearLayout>

Step 2) create  a new class to create service. and extends service in this class

package com.demo;

import java.util.Random;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class ServiceExample extends Service {

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service Created",300);
}

@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this,"Service Destroy",300);
}

@Override
public void onLowMemory() {
super.onLowMemory();
Toast.makeText(this,"Service LowMemory",300);
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this,"Service start",300);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

Toast.makeText(this,"task perform in service",300);
ThreadDemo td=new ThreadDemo();
td.start();
return super.onStartCommand(intent, flags, startId);
}

private class ThreadDemo extends Thread{
@Override
public void run() {
super.run();
try{
sleep(70*1000);
handler.sendEmptyMessage(0);
}catch(Exception e){
e.getMessage();
}
}
}
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//showAppNotification();
}
};
}


service onCreate() called only once when service first started then other method followed by it. In onstarteCommand() i started a thread to do some background task. after completion of thread you can give a notification to user that task has been completed. For this i have taken a Handler


Now we will take an activity to show user inter face for starting service



package com.demo;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ReceiverCallNotAllowedException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class ServiceDemoActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.start).setOnClickListener(this);
findViewById(R.id.stop).setOnClickListener(this);
}

private Intent inetnt;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:

inetnt=new Intent(this,ServiceExample.class);
startService(inetnt);
break;
case R.id.stop:

inetnt=new Intent(this,ServiceExample.class);
stopService(inetnt);
break;
}
}

@Override
protected void onResume() {
super.onResume();
}

@Override
protected void onDestroy() {
super.onDestroy();
//
}
}

service can be started in two way Context.startService() and Context.bindService(). second option is  used to bind service with activity or something else in this case we unbind service when activity destroy 


Enjoy and play with my code by downloading it and mention service in activity inside application tag like


<service android:name=".ServiceExample"/>

                                    Download source code

Utility Function Call, Email, Send SMS in android Using Intent

0 comments

Generally while we making an android application then sometimes we need small piece of code like how to call a number on button click, how to send an email, how to send a sms. But problem is that it does not available at one place. So i am giving all possible Utility code here

1) How to call a number in android application

 Intent callIntent = new Intent(Intent.ACTION_CALL);  
callIntent.setData(Uri.parse("tel:123456789"));
startActivity(callIntent);


2) How to send an email in android application

 Intent(android.content.Intent.ACTION_SENDTO);
emailIntent.setType("text/html");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "testing email send.");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<b>this is html text in email body.</b>"));
startActivity(Intent.createChooser(emailIntent, "Email to Friend"));



3) How to send SMS in android application

 SmsManager sm = SmsManager.getDefault();
String number = "6508570720";
sm.sendTextMessage(number, null, "Test SMS Message", null, null);


Note : Never forget to mention for sending SMS <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

Now enjoy these Utility in your application and feel free to support me by commenting and giving feedback

How to pick an Email from contact in android

0 comments

Picking email, Phone number, and other detail from android in built contact is very easy if you use ACTION_PICK.Action Pick activity syntax will be like


Intent intent1=new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent1,100);


Note : it need permission .so do not forget to mention it in manifest

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

It will start a default activity that will list all contact. On item select that activity will finish automatically and it will return result in OnActivityResult. default activity return complete Intent with all available information with particular select contact.



The main issue is now to handle Intent result in OnActivityResult. So now we will handle Intent



if(requestCode==100){
try{
if(resultCode==Activity.RESULT_OK){
Uri uri=data.getData();
String[] projection = new String[] {
ContactsContract.Contacts._ID,ontactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA
};
Cursor emailCur=getContentResolver().query(uri,null, null, null,null);
emailCur.moveToFirst();
String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
Log.i("dddd",""+email+"djdjdj"+emailType);
emailCur.close();
}
catch(Exception e){
e.getCause();
}
}
}


                                    Download Sample

Creating Horizontal ListView in Android

0 comments

Today i am going to describing a powerful tool of android, Horizontal Listview with complete source in the end.
Horizontal ListView sometimes is very useful and it save our day.

If you need some explanation then read complete step else download code with link in the end and play with it



Step 1) Create one new Project name HorizontalListviewDemo

Step 2) Change your main activity to as follow class



 package com.ahmad;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;


public class SecondActivity extends Activity implements OnClickListener {
 Button btn1, btn2, btn3, btn4;
 public LinearLayout middle;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  btn1 = (Button) findViewById(R.id.btn1);
  btn1.setOnClickListener(this);
  btn2 = (Button) findViewById(R.id.btn2);
  btn2.setOnClickListener(this);
  btn3 = (Button) findViewById(R.id.btn3);
  btn3.setOnClickListener(this);
  try {
   btn4 = (Button) findViewById(R.id.btn4);
   btn4.setOnClickListener(this);
  } catch (Exception e) {
   e.getMessage();
  }
 }


 @Override
 public void onClick(View v) {
  if (v.getId() == R.id.btn1) {
   Toast.makeText(this, "Second Act Btn1 Clicked", Toast.LENGTH_LONG)
     .show();
  } else if (v.getId() == R.id.btn2) {
   Toast.makeText(this, "Second Act Btn 2 Clicked", Toast.LENGTH_LONG)
     .show();
  } else if (v.getId() == R.id.btn3) {
   Toast.makeText(this, "Second Act Btn 3 Clicked", Toast.LENGTH_LONG)
     .show();
  } else if (v.getId() == R.id.btn4) {
   Toast.makeText(this, "Second Act Btn 4 Clicked", Toast.LENGTH_LONG)
     .show();
  }
 }
}


Step 3)Change your main.xml to following



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


    <RelativeLayout
        android:id="@+id/top"
        android:layout_width="fill_parent"
        android:layout_height="55dp"
        android:layout_alignParentTop="true"
        android:background="@drawable/header" >


        <Button
            android:id="@+id/btn_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="5dp"
            android:text="@string/back" />
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_centerVertical="true"
            android:text="@string/title"
            android:textColor="#FFF"
            android:textSize="20dp"
            android:textStyle="bold" />
        <Button
            android:id="@+id/btn_unknown"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="5dp"
            android:text="@string/unknow" />
    </RelativeLayout>
    <HorizontalScrollView
        android:id="@+id/bottom"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:fadeScrollbars="false"
        android:scrollbars="none" >
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/header"
            android:orientation="horizontal" 
            android:paddingTop="5dp" >
            <Button
                android:id="@+id/btn1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btn1" />
            <Button
                android:id="@+id/btn2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btn2" />
            <Button
                android:id="@+id/btn3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btn3" />
            <Button
                android:id="@+id/btn4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btn4" />
        </LinearLayout>
         </HorizontalScrollView>
        <LinearLayout
        android:id="@+id/middlebar"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/bottom"
        android:layout_below="@id/top" >
       </LinearLayout>
      </RelativeLayout>
  
Now enjoy after running it.complete source link is below.See more article on ListView in blog tag Android ListView
                                                    Download Complete Project

Asynchronous task, Updating UI from background in android

0 comments

As all we know in android there are two ways to perform background task such as downloading image and other task that include long operation
  • Using Thread 
  • Asynchronous Task                          
Using Thread, there is one dis-advantage that we can not update user interface other wise we will get Looper.loop() exception

So its efficient to use Asynchronous task.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.


Let take one example of downloading images from URL's Array.So body of Asynchronous task 's body will be like this
 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     
protected Long doInBackground(URL... urls) {
         
int count = urls.length;
         
long totalSize = 0;
         
for (int i = 0; i < count; i++) {
             totalSize
+= Downloader.downloadFile(urls[i]);
             publishProgress
((int) ((i / (float) count) * 100));
         
}
         
return totalSize;
     
}

     
protected void onProgressUpdate(Integer... progress) {
         setProgressPercent
(progress[0]);
     
}

     
protected void onPostExecute(Long result) {
         showDialog
("Downloaded " + result + " bytes");
     
}
 
}
 
    Like Thread we can create asynchronous task like this
 new DownloadFilesTask().execute(url1, url2, url3);
    Now asynchronous has three generic type.Let have a look on their requirement 
    



  • Params, the type of the parameters sent to the task upon execution.
  • Progress, the type of the progress units published during the background computation.
  • Result, the type of the result of the background computation.

  •     
    But its not necessary to use all type.you can set like this if you do not want to use 
    private class MyTask extends AsyncTask<Void, Void, Void> { ... }
     Now it has four step -
    1)  onPreexecute() -Before it start executing it call this method .It call before it goes to perform task in background so we can display a ProgressDialog here )doInBackground() - perform long background task here

    3)onProgressUpdate() - Update your progress of dialog to show to user

    4)onPostExecute() - Post or show your result here .Dismiss progress dialog  box here
    There are a few threading rules that must be followed for this class to work properly:

    Zipping File and Folder in android

    0 comments


    While we are attaching any folder/file to mail or other attachment so we really need to attach folder with more than one sub folder. So we need to compress it so called zipping . It necessary in Mobile OS as in Windows.

    So for this android provide ZipOutPutStream  and ZipEntry. ZipOutPutStream read complete folder and then ZipEntry zip all the file inside folder to a new compress folder.

    Zipping File is very easy.If you want dynamically select which file/folder to zipped then see this


    import android.util.Log; 
    import java.io.BufferedInputStream; 
    import java.io.BufferedOutputStream; 
    import java.io.FileInputStream; 
    import java.io.FileOutputStream; 
    import java.util.zip.ZipEntry; 
    import java.util.zip.ZipOutputStream; 
     
     
    public class Compress { 
      private static final int BUFFER = 2048
     
      private String[] _files; 
      private String _zipFile; 
     
      public Compress(String[] files, String zipFile) { 
        _files = files; 
        _zipFile = zipFile; 
      } 
     
      public void zip() { 
        try  { 
          BufferedInputStream origin = null
          FileOutputStream dest = new FileOutputStream(_zipFile); 
     
          ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); 
     
          byte data[] = new byte[BUFFER]; 
     
          for(int i=0; i < _files.length; i++) { 
            Log.v("Compress""Adding: " + _files[i]); 
            FileInputStream fi = new FileInputStream(_files[i]); 
            origin = new BufferedInputStream(fi, BUFFER); 
            ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1)); 
            out.putNextEntry(entry); 
            int count; 
            while ((count = origin.read(data, 0, BUFFER)) != -1) { 
              out.write(data, 0, count); 
            } 
            origin.close(); 
          } 
     
          out.close(); 
        } catch(Exception e) { 
          e.printStackTrace(); 
        } 
     
      } 
     
    In constructor we have two string parameter.first pass array of file inside a folder .Then file path to which zipped folder will save if it is not present then this code will create new zip folder.

    Android File explorer ,pick image, video, Audio from your phone drive

    0 comments

    In android we know sdcard is main drive to store information. Sometimes we need to read/write file from sdcard. In this case we can give static path and easily can read/write using FileInputStream and FileOutputStream. But in most case we need to select it  dynamically on user demand.After selecting it we can modify it, we can share or we can send it to anywhere


    So today I am going to make a simple application like File-explorer. It will help in my next Article Ziping and Unziping Folder in android.


    Step1) Create one project File-Explorer 

    Step 2) Change your activity to following code





    package com.AndroidExplorer;


    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    import android.app.AlertDialog;
    import android.app.ListActivity;
    import android.content.DialogInterface;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;


    public class AndroidExplorer extends ListActivity {
    private List<String> item = null;
    private List<String> path = null;
    private String root = "/sdcard";
    private TextView myPath;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.explorer);
    myPath = (TextView) findViewById(R.id.path);
    getDir(root);
    }
    private void getDir(String dirPath) {
    myPath.setText("Location: " + dirPath);
    item = new ArrayList<String>();
    path = new ArrayList<String>();
    File f = new File(dirPath);
    File[] files = f.listFiles();
    if (!dirPath.equals(root)) {
    item.add(root);
    path.add(root);
    item.add("../");
    path.add(f.getParent());
    }
    for (int i = 0; i < files.length; i++) {
    File file = files[i];
    path.add(file.getPath());
    if (file.isDirectory())
    item.add(file.getName() + "/");
    else
    item.add(file.getName());
    }
    ArrayAdapter<String> fileList = new ArrayAdapter<String>(this,
    R.layout.explorer_row, item);
    setListAdapter(fileList);
             }
           File file;
           @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    file = new File(path.get(position));
    if (file.isDirectory()) {
      if (file.canRead())
    getDir(path.get(position));
    else {
    new AlertDialog.Builder(this)
    .setIcon(R.drawable.icon)
    .setTitle("[" + file.getName()+ "] folder can't be read!")
    .setPositiveButton("OK",new DialogInterface.OnClickListener() {
       @Override public void onClick(DialogInterface dialog,int which) {
     }}).show();
    }
    } else {
        new AlertDialog.Builder(this)
       .setIcon(R.drawable.icon)
       .setTitle("Select")
       setMessage("Select " + file.getName() + "to server ?")
      .setPositiveButton("Select",new DialogInterface.OnClickListener() {
             @Override public void onClick(DialogInterface dialog,int which) {
    Toast.makeText(
                         AndroidExplorer.this,"" + file.getAbsolutePath()+ " iss selected ",300)
    .show();
        }
    })
    .setNegativeButton("No",new DialogInterface.OnClickListener() {
    @Override
              public void onClick(DialogInterface dialog,int which) {
    dialog.dismiss();
    }
    }).show();
    }
        }
          } 
    Step 3 Now our coding part has been done.We will create two xml. As i have take one List-Activtiy   so it need two layout one main.xml and another one to inflating into ListView row.Click me for advance ListView


    explorer.xml inside res/layout folder


     <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <TextView
    android:id="@+id/path"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        />
    <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:cacheColorHint="#B26B00"
        android:fadingEdge="none"
    />
    <TextView
    android:id="@android:id/empty"
    android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="No Data"
    />
    </LinearLayout>


    explorer_row in same folder



    <?xml version="1.0" encoding="utf-8"?>
    <TextView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowtext" android:padding="10dp"
    android:background="#C0C0C0" android:textColor="#000"
    android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="23sp" />


    Now enjoy you can download this complete project from this link.

                                          Download this Project


    These are the screen shot of that project