Payday Loan Payday Loan

Archive for the ‘SDCARD’ Category

Hi,
Today i want to show you how you can save like a image file a user gestures. Also you can learn how to draw gestures on a view and also how to erase the gestures.
There is a similar post…but simply do not works plug and play like this improved example.
The following class is an Dialog activity which is just a plug and play class.
Copy and paste and it will work.
All you need are some setups. For example you need to add in your strings/ folder a item called external_dir.
Here will be saved the png image file.
First create a Hello World application. Can look like this:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class MyApplication extends Activity {
 
    public static final int MY_ACTIVITY = 1;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        Button getSignature = (Button) findViewById(R.id.signature);
        getSignature.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent(MyActivity.this, CaptureSignature.class); 
                startActivityForResult(intent,MY_ACTIVITY);
            }
        });
    }
 
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch(requestCode) {
        case MY_ACTIVITY: 
            if (resultCode == RESULT_OK) {
 
                Bundle bundle = data.getExtras();
                String status  = bundle.getString("status");
                if(status.equalsIgnoreCase("done")){
                    Toast toast = Toast.makeText(this, "Signature capture successful!", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP, 105, 50);
                    toast.show();
                }
            }
            break;
        }
 
    }  
 
}

As you saw we have called from a button the Activity CaptureSignature…
You need to declare this activity in your manifest like this:

<activity
            android:name=".CaptureSignature"
            android:theme="@android:style/Theme.Dialog"
             />

Also in Manifest you need to add permission to write on SDCARD like this:

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

After you have done this modifications you need to create the class CaptureSignature.java
In this file you need the following code:

 
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
 
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
 
public class CaptureSignature extends Activity { 
 
    LinearLayout mContent;
    Signature mSignature;
    Button mClear, mGetSign, mCancel;
    public static String tempDir;
    public int count = 1;
    public String current = null;
    private Bitmap mBitmap;
    View mView;
    File mypath;
 
    private String uniqueId;
    private EditText yourFileName;
 
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.signature);
 
        tempDir = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.external_dir) + "/";
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
 
        prepareDirectory();
        yourFileName = (EditText) findViewById(R.id.yourName);
 
 
 
        mContent = (LinearLayout) findViewById(R.id.linearLayout);
        mSignature = new Signature(this, null);
        mSignature.setBackgroundColor(Color.WHITE);
        mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mClear = (Button)findViewById(R.id.clear);
        mGetSign = (Button)findViewById(R.id.getsign);
        mGetSign.setEnabled(false);
        mCancel = (Button)findViewById(R.id.cancel);
        mView = mContent;
 
 
 
        mClear.setOnClickListener(new OnClickListener() 
        {        
            public void onClick(View v) 
            {
                Log.v("log_tag", "Panel Cleared");
                mSignature.clear();
                mGetSign.setEnabled(false);
            }
        });
 
        mGetSign.setOnClickListener(new OnClickListener() 
        {        
            public void onClick(View v) 
            {
                Log.v("log_tag", "Panel Saved");
                boolean error = captureSignature();
                if(!error){
                    mView.setDrawingCacheEnabled(true);
                    mSignature.save(mView);
                    Bundle b = new Bundle();
                    b.putString("status", "done");
                    Intent intent = new Intent();
                    intent.putExtras(b);
                    setResult(RESULT_OK,intent);   
                    finish();
                }
            }
        });
 
        mCancel.setOnClickListener(new OnClickListener() 
        {        
            public void onClick(View v) 
            {
                Log.v("log_tag", "Panel Canceled");
                Bundle b = new Bundle();
                b.putString("status", "cancel");
                Intent intent = new Intent();
                intent.putExtras(b);
                setResult(RESULT_OK,intent);  
                finish();
            }
        });
 
    }
 
    @Override
    protected void onDestroy() {
        Log.w("GetSignature", "onDestory");
        super.onDestroy();
    }
 
    private boolean captureSignature() {
 
        boolean error = false;
        String errorMessage = "";
 
 
        if(yourFileName.getText().toString().equalsIgnoreCase("")){
            errorMessage = errorMessage + "Please enter your FileName\n";
            error = true;
        } else {
        	uniqueId = getTodaysDate() + "_" + getCurrentTime() + "_"+yourFileName.getText().toString();
            current = uniqueId + ".png";
            mypath= new File(tempDir,current);
        }
 
        if(error){
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP, 105, 50);
            toast.show();
        }
 
        return error;
    }
 
    private String getTodaysDate() { 
 
        final Calendar c = Calendar.getInstance();
        int todaysDate =     (c.get(Calendar.YEAR) * 10000) + 
        ((c.get(Calendar.MONTH) + 1) * 100) + 
        (c.get(Calendar.DAY_OF_MONTH));
        Log.w("DATE:",String.valueOf(todaysDate));
        return(String.valueOf(todaysDate));
 
    }
 
    private String getCurrentTime() {
 
        final Calendar c = Calendar.getInstance();
        int currentTime =     (c.get(Calendar.HOUR_OF_DAY) * 10000) + 
        (c.get(Calendar.MINUTE) * 100) + 
        (c.get(Calendar.SECOND));
        Log.w("TIME:",String.valueOf(currentTime));
        return(String.valueOf(currentTime));
 
    }
 
 
    private boolean prepareDirectory() 
    {
        try
        {
            if (makedirs()) 
            {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) 
        {
            e.printStackTrace();
            Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
            return false;
        }
    }
 
    private boolean makedirs() 
    {
        File tempdir = new File(tempDir);
        if (!tempdir.exists())
            tempdir.mkdirs();
 
        if (tempdir.isDirectory()) 
        {
            File[] files = tempdir.listFiles();
 
        }
        return (tempdir.isDirectory());
    }
 
    public class Signature extends View 
    {
        private static final float STROKE_WIDTH = 5f;
        private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
        private Paint paint = new Paint();
        private Path path = new Path();
 
        private float lastTouchX;
        private float lastTouchY;
        private final RectF dirtyRect = new RectF();
 
        public Signature(Context context, AttributeSet attrs) 
        {
            super(context, attrs);
            paint.setAntiAlias(true);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeWidth(STROKE_WIDTH);
        }
 
        public void save(View v) 
        {
            Log.v("log_tag", "Width: " + v.getWidth());
            Log.v("log_tag", "Height: " + v.getHeight());
            if(mBitmap == null)
            {
                mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
            }
            Canvas canvas = new Canvas(mBitmap);
            try
            {
                FileOutputStream mFileOutStream = new FileOutputStream(mypath);
 
                v.draw(canvas); 
                mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream); 
                mFileOutStream.flush();
                mFileOutStream.close();
            //    String url = Images.Media.insertImage(getContentResolver(), mBitmap, "title", null);
             //   Log.v("log_tag","url: " + url);
                //In case you want to delete the file
                //boolean deleted = mypath.delete();
                //Log.v("log_tag","deleted: " + mypath.toString() + deleted);
                //If you want to convert the image to string use base64 converter
 
            }
            catch(Exception e) 
            { 
                Log.v("log_tag", e.toString()); 
            } 
        }
 
        public void clear() 
        {
            path.reset();
            invalidate();
        }
 
        @Override
        protected void onDraw(Canvas canvas) 
        {
            canvas.drawPath(path, paint);
        }
 
        @Override
        public boolean onTouchEvent(MotionEvent event) 
        {
            float eventX = event.getX();
            float eventY = event.getY();
            mGetSign.setEnabled(true);
 
            switch (event.getAction()) 
            {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(eventX, eventY);
                lastTouchX = eventX;
                lastTouchY = eventY;
                return true;
 
            case MotionEvent.ACTION_MOVE:
 
            case MotionEvent.ACTION_UP:
 
                resetDirtyRect(eventX, eventY);
                int historySize = event.getHistorySize();
                for (int i = 0; i < historySize; i++) 
                {
                    float historicalX = event.getHistoricalX(i);
                    float historicalY = event.getHistoricalY(i);
                    expandDirtyRect(historicalX, historicalY);
                    path.lineTo(historicalX, historicalY);
                }
                path.lineTo(eventX, eventY);
                break;
 
            default:
                debug("Ignored touch event: " + event.toString());
                return false;
            }
 
            invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
                    (int) (dirtyRect.top - HALF_STROKE_WIDTH),
                    (int) (dirtyRect.right + HALF_STROKE_WIDTH),
                    (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
 
            lastTouchX = eventX;
            lastTouchY = eventY;
 
            return true;
        }
 
        private void debug(String string){
        }
 
        private void expandDirtyRect(float historicalX, float historicalY) 
        {
            if (historicalX < dirtyRect.left) 
            {
                dirtyRect.left = historicalX;
            } 
            else if (historicalX > dirtyRect.right) 
            {
                dirtyRect.right = historicalX;
            }
 
            if (historicalY < dirtyRect.top) 
            {
                dirtyRect.top = historicalY;
            } 
            else if (historicalY > dirtyRect.bottom) 
            {
                dirtyRect.bottom = historicalY;
            }
        }
 
        private void resetDirtyRect(float eventX, float eventY) 
        {
            dirtyRect.left = Math.min(lastTouchX, eventX);
            dirtyRect.right = Math.max(lastTouchX, eventX);
            dirtyRect.top = Math.min(lastTouchY, eventY);
            dirtyRect.bottom = Math.max(lastTouchY, eventY);
        }
    }
}

Now you will need the xml file called signature.xml
This is the code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/linearLayout1"
    android:layout_width="fill_parent" android:layout_height="400dp"
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:layout_height="wrap_content"
        android:id="@+id/linearLayout2" android:layout_width="match_parent">
        <Button android:layout_height="50dp" android:layout_weight=".30"
            android:text="@string/cancel" android:layout_width="0dp" android:id="@+id/cancel" />
        <Button android:layout_height="50dp" android:layout_weight=".35"
            android:text="@string/clear" android:layout_width="0dp" android:id="@+id/clear" />
        <Button android:layout_height="50dp" android:layout_weight=".35"
            android:text="@string/save" android:layout_width="0dp" android:id="@+id/getsign" />
    </LinearLayout>
    <TableLayout android:layout_height="wrap_content"
        android:id="@+id/tableLayout1" android:layout_width="match_parent">
        <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:id="@+id/textView2"
                android:text="@string/filename" android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="wrap_content" android:paddingLeft="10sp"
                android:layout_gravity="left" />
 
        </TableRow>
        <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        <EditText android:layout_height="wrap_content" android:id="@+id/yourName"
                android:layout_weight="1" android:layout_width="match_parent"
                android:hint="@string/signature_hint"
                android:maxLength="30">
                <requestFocus />
            </EditText>
        </TableRow>
        <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
 
            <TextView android:layout_height="wrap_content" android:id="@+id/textView5"
                android:text="@string/sign_below" android:maxLength="30"  
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="wrap_content" />
        </TableRow>
    </TableLayout>
    <LinearLayout android:layout_height="match_parent"
        android:id="@+id/linearLayout" android:layout_width="match_parent" />
</LinearLayout>

Here you will need to update the strings in your string/ folder
but i can give you a hint on how it looks at mine

<resources>
<string name="app_name">Myapp</string>    
<string name="external_dir">WeJob</string>
    <string name="filename">Filename:</string>
    <string name="signature_hint">Ex: mySignature</string>
    <string name="sign_below">Please sign below...</string>
    <string name="cancel">Cancel</string>
    <string name="clear">Clear</string>
    <string name="save">Save</string>
</resources>

Thanks and happy coding!

||||| 0 I Like It! |||||

Hi, for today I choose to show you how to get and display all the images from SD card.

For this we’ll create an activity SDImagesGallery (the gallery), and an adapter GalleryAdapter (the adapter for the gallery).

1. Let’s begin with the xml layout for the SDImageGallery activity:

gallery_layout.xml

 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <ImageView android:id="@+id/image_view_gallery" 
        android:layout_width="match_parent" 
	android:layout_height="match_parent"
	android:contentDescription="@string/gallery"/>
 
    <Gallery 
	android:id="@+id/gallery" 
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:layout_weight="0"/>
 
</LinearLayout>

2. Create SDImageGallery activity as follows:
(Important: In order not to block the UI thread we’ll use an AsyncTask class to get the images)

 
import java.util.ArrayList;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
 
 
public class GalleryActivity extends Activity {
 
	private Gallery mGallery;
	private ImageView mImageView;
	private ProgressDialog mProgressDialog;
	private ArrayList<String> mImages = new ArrayList<String>();
	private int currentIndex;
	private GetImagesAsync getImagesAsync; 
 
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gallery_layout);
 
		mGallery = (Gallery) findViewById(R.id.gallery);
		mImageView = (ImageView) findViewById(R.id.image_view_gallery);
 
		GalleryAdapter adapter = new GalleryAdapter(this);
		mGallery.setAdapter(adapter);
 
		mImageView.setImageResource(0);
 
		setViews();	
 
		getImagesAsync = new GetImagesAsync();
		getImagesAsync.execute((Void) null);
	}
 
	public void setView() {
		mGallery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				mImageView.setImageURI(Uri.parse(mImages.get(arg2)));
			}
		});
 
		mGallery.setCallbackDuringFling(false);		
		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
 
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				mImageView.setImageURI(Uri.parse(mImages.get(arg2)));
			}
 
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
 
		});
	}
 
	public class GetImagesAsync extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			mProgressDialog = ProgressDialog.show(ImageAlbums.this,
					null, "Loading images...", true, false);
		}
 
		@Override 
		protected Boolean doInBackground(Void...voids) {
			result = getImages();
 
			return result;
		}
 
		@Override
		protected void onPostExecute(Boolean result) {
			mProgressDialog.dismiss();
			if(result) {
				adapter.setData(mImages);
				adapter.notifyDataSetChanged();	
			}else {
				Toast.makeText(SDImageGallery.this, "No SD card available", Toast.LENGTH_LONG).show();
			}
		}
	}
 
	private boolean getImages() {
 
		if(!isSdAvailable()){
			return false;
		}
 
		String[] projection = {MediaStore.Images.Media.DATA};
		String ord = MediaStore.Images.Media.DATA;
 
		ContentResolver cr = getContentResolver();
		Cursor mCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
  				projection, 
  				null, 
  				null, 
  				ord + " ASC");	
 
  		if (mCursor != null && mCursor.moveToFirst()) 
  		{
			while(!mCursor.isAfterLast())
			{
	        		String data = mCursor.getString(mCursor.getColumnIndexOrThrow(ord));
	        		mImages.add(data);
	        		mCursor.moveToNext();
			}
			mCursor.close();
  		}
 
  		return true;
 
	}
 
	private boolean isSdAvailable()
	{
		boolean state = android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		return state;
	}
 
}

3. Create an adapter for the gallery:

 
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
 
import java.util.ArrayList;
 
public class GalleryAdapter extends BaseAdapter{
 
	Context mContext;
	int mGalleryItemBackground;
	ArrayList<String> mImages = new ArrayList<String>();
	Resources resources;
 
	public GalleryAdapter(Context context) {
		mContext = context;
		TypedArray a = mContext.obtainStyledAttributes(R.styleable.Gallery1);
        	mGalleryItemBackground = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
        	a.recycle();
        	resources = context.getResources();
	}
 
	@Override
	public int getCount() {
		return mImages.size();
	}
 
	@Override
	public String getItem(int index) {
		return mImages.get(index);
	}
 
	@Override
	public long getItemId(int id) {
		return id;
	}
 
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView i = new ImageView(mContext);
 
		i.setImageURI(Uri.parse(mImages.get(position)));
		i.setLayoutParams(new Gallery.LayoutParams(resources.getDimension(R.dimen.mThumbnailWidth), resources.getDimension(R.dimen.mThumbnailHeight)));
		i.setBackgroundResource(mGalleryItemBackground);
 
    		return i;
	}
 
	public void setData(ArrayList<String> images) {
		mImages.addAll(images);
	}
 
	public void clearData() {
		mImages.clear();
	}
}

R.dimen.mThumbnailWidth and R.dimen.mThumbnailHeight can be defined in res/values/dimens.xml as follows:

 
<resources>
 
    <dimen name="mThumbnailWidth">120dp</dimen>
    <dimen name="mThumbnailHeight">68dp</dimen>
 
</resources>

Happy coding,
Bogdan

||||| 1 I Like It! |||||

Hi.
Once again, this is Bogdan with another article for androidgenuine.com.

Today I will show you a simple but very usefull thing. I will show you how to start anactivityforresult to the camera and how the taken photo will be transformed into a bitmap a seen on an imageview.

The tutorial is simple and pretty short. I have only one class : ImageCapture.class and an xml file : mylayout.xml (like usual, I am too lazy to change the name of the layout).

Here is the Java code for ImageCapture class:

public class ImageCapture extends Activity implements View.OnClickListener{	
	//The declaration part...
	Button b;
	ImageView iv;
	final static int cameraData = 0;
	Bitmap  bmp;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mylayout);
		//We call for initialize method
		initialize();
		//We use the inputstream to get the drawable resource
		InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
		bmp = BitmapFactory.decodeStream(is);
	}
	private void initialize() {
		// TODO Auto-generated method stub
		//Stuff with imageview and button, I suppose you know these.
		iv = (ImageView) findViewById(R.id.ivReturnedPic);
		b = (Button) findViewById (R.id.bTakePic);
 
		b.setOnClickListener(this);
	}
	 public void onClick(View v) {
		// TODO Auto-generated method stub
 
		 //Here is the intent that we use to start the Camera
			Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			//Here we start the activity for result with the unique code "cameraData" and intent i.
			startActivityForResult(i, cameraData);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		//Check the unique code if it matches with the RESULT_OK
		if (resultCode == RESULT_OK){
			//The bundle where we collect the extras
			Bundle extras = data.getExtras();
			// Here is our bitmap - the photo we'd just taken
			bmp = (Bitmap) extras.get("data");
			//Here we set the bitmap to our imageview
			iv.setImageBitmap(bmp);
		}
	}
 
}

And here is the code for the xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <ImageView
        android:id="@+id/ivReturnedPic"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_gravity="center"
        android:layout_marginTop="20dip"
        android:src="@drawable/ic_launcher" />
 
 
 
    <Button
        android:layout_gravity="center"
        android:id="@+id/bTakePic"
        android:layout_width="150dp"
        android:layout_marginTop="10dip"
        android:layout_height="wrap_content"
        android:text="Take picture" />
 
</LinearLayout>

Here is a picture where you can see how the application looks like :

Like always, you can download the entire project from here.

This was all for this tutorial . I hope you enjoyed it and you’ll read my future articles , too. Until next tutorial, bye !

||||| 0 I Like It! |||||

Hi, this is a tutorial which makes something like Astro App but much simpler. Just the browsing of files.
You can use it when your users need to select a file from sdcard or phone.

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.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
 
 
public class FileBrowser extends ListActivity {
 
   private List<String> item = null;
   private List<String> path = null;
   private TextView fileInfo;
   private String[] items;
   private String root = "/";
 
   /** Called when the activity is first created. */
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        fileInfo = (TextView)findViewById(R.id.info);
        getFileList(root);
    }
 
    //To make listview for the list of file
    public void getFileList(String dirPath){
 
       item = new ArrayList<String>(); //Declare as Array list
       path = new ArrayList<String>();
 
 
 
       File file = new File(dirPath); // get the file
       File[] files = file.listFiles(); //get the list array of file
 
       if(!dirPath.equals(root)){
          item.add(root); 
          path.add(root);// to get back to main list
 
          item.add("..");
          path.add(file.getParent()); // back one level 
       }
 
       for (int i = 0; i < files.length; i++){
 
          File fileItem = files[i];
          path.add(fileItem.getPath());
          if(fileItem.isDirectory()){
             item.add("["+fileItem.getName()+"]"); // input name directory to array list
          }
          else {
             item.add(fileItem.getName()); // input name file to array list
          }
       }
       fileInfo.setText("Info: "+dirPath+" [ " +files.length +" item ]");
       items = new String[item.size()]; //declare array with specific number off item
       item.toArray(items); //send data arraylist(item) to array(items
       setListAdapter(new IconicList()); //set the list with icon
    }
 
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id){
       File file = new File(path.get(position));
       if(file.isDirectory()){ 
          if(file.canRead()){
             getFileList(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) {
                  // TODO Auto-generated method stub
 
               }
            }).show();
 
          }
       }
       else {
          new AlertDialog.Builder(this)
          .setIcon(R.drawable.icon)
          .setTitle("["+file.getName()+"]")
          .setPositiveButton("OK", new DialogInterface.OnClickListener() {
 
            @Override
            public void onClick(DialogInterface dialog, int which) {
               // TODO Auto-generated method stub
 
            }
         }).show();
       }
    }
 
    class IconicList extends ArrayAdapter {
 
 
      public IconicList() {
         super(FileBrowser.this, R.layout.row, items);
 
         // TODO Auto-generated constructor stub
      }
 
      public View getView(int position, View convertView, ViewGroup parent){
         LayoutInflater inflater = getLayoutInflater(); //to instantiate layout XML file into its corresponding View objects
         View row = inflater.inflate(R.layout.row, null); //to Quick access to the LayoutInflater  instance that this Window retrieved from its Context.
         TextView label = (TextView)row.findViewById(R.id.label); //access the textview for the name file
         ImageView icon = (ImageView)row.findViewById(R.id.icon);//access the imageview for the icon list
         label.setText(items[position]);
         File f = new File(path.get(position)); //get the file according the position
         if(f.isDirectory()){ //decide are the file folder or file
            icon.setImageResource(R.drawable.folder);
         }
         else {
            icon.setImageResource(R.drawable.text);
         }
         return(row);
      }
 
 
 
    }
}
||||| 0 I Like It! |||||

How to save apps to sdcard in Android

I will show you how you can save data of your app in the external SDCARD.
This feature is brought with the API 8. So if you make apps for minimum API version 8, you can use the following
code for saving large content of apps to SDCARD.
Below API Level 8 such dedicated directory is not available, only the sdcard directory can be queried by the getExternalStorageDirectory() method. It is recommended to store files in the /Android/data/
/files/ directory under the sd card, because for users with a 2.2 system this directory will be still deleted on uninstall.

Environment.getExternalStorageDirectory().toString()+”/data/”+getPackageName()+”/files/”;

||||| 0 I Like It! |||||

Search

Popular

Sponsors