domingo, 23 de diciembre de 2012

Recursos Externos Assets

URL ORIGEN: http://mylifewithandroid.blogspot.com/2009/06/assets.html
http://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
http://developer.android.com/reference/android/content/res/AssetManager.html
http://www.javacodegeeks.com/2012/02/android-read-file-from-assets.html


La carpeta Raw es una sub-carpeta de res, donde android guarda todos los recursos, por tanto android generará un ID automático para todo el contenido de la carpeta Raw y estos recursos podrán ser accedidos directamente desde la clase R, lo que brinda un acceso rápido a otras clases y métodos en Android

La carpeta Assets es un direcctorio adicional (un "apéndice") que se incluye en el paquete *.apk de la aplicación por tanto la clase R no genera ID's para estos archivos, por tanto es menos compatible con las clases de android y su acceso puede ser mas dificultoso para las clases y métodos. También hay un limite de 1mb para los archivos que pueden ser colocados en esta carpeta.  Sin embargo el directorio es mucho más flexible y permite almacenar tipos de archivos que no pueden ser incluidos en la carpeta res y por tanto no se pueden incluir en su carpeta hija raw, lo que permite que ciertas operaciones sean más fáciles, la carpeta es ideal para por ejemplo copiar un archivo de base de datos en la memoria del sistema. No hay manera (fácil) para crear en Android una referencia XML a los archivos dentro de la carpeta assets.


El codigo a usar para implementar el asset seria el sisguiente:


01package pete.android.study;
02
03import java.io.IOException;
04import java.io.InputStream;
05
06import android.app.Activity;
07import android.graphics.drawable.Drawable;
08import android.os.Bundle;
09import android.widget.ImageView;
10import android.widget.TextView;
11
12public class Main extends Activity {
13
14    ImageView mImage;
15    TextView mText;
16
17    @Override
18    public void onCreate(Bundle savedInstanceState) {
19        super.onCreate(savedInstanceState);
20        setContentView(R.layout.main);
21
22        mImage = (ImageView)findViewById(R.id.image);
23        mText = (TextView)findViewById(R.id.text);
24        loadDataFromAsset();
25    }
26
27    public void loadDataFromAsset() {
28        // load text
29        try {
30            // get input stream for text
31            InputStream is = getAssets().open("text.txt");
32            // check size
33            int size = is.available();
34            // create buffer for IO
35            byte[] buffer = new byte[size];
36            // get data to buffer
37            is.read(buffer);
38            // close stream
39            is.close();
40            // set result to TextView
41            mText.setText(new String(buffer));
42        }
43        catch (IOException ex) {
44            return;
45        }
46
47        // load image
48        try {
49            // get input stream
50            InputStream ims = getAssets().open("avatar.jpg");
51            // load image as Drawable
52            Drawable d = Drawable.createFromStream(ims, null);
53            // set image to ImageView
54            mImage.setImageDrawable(d);
55        }
56        catch(IOException ex) {
57            return;
58        }
59
60    }
61}


Description:
First of all, let me give you a link: AssetManager, through this class we can easily access any files lying inside the Assets directory of android application. (or any sub-folders inside the Assets directory).
Now, we can have an object of AssetManager class by using getAssets() method:
1AssetManager assetManager = getAssets(); 
And the rest of the procedure i have given and described by making comments in the example so now go through the full solutions provided below with the output snap.
Solution:
ReadFileAssetsActivity.java
01package com.paresh.readfileasset;
02 
03import java.io.IOException;
04import java.io.InputStream;
05 
06import android.app.Activity;
07import android.content.res.AssetManager;
08import android.graphics.drawable.Drawable;
09import android.os.Bundle;
10import android.widget.ImageView;
11import android.widget.TextView;
12 
13/**
14 * @author Paresh N. Mayani
16 */
17public class ReadFileAssetsActivity extends Activity {
18 
19 /** Called when the activity is first created. */
20 
21 @Override
22 public void onCreate(Bundle savedInstanceState) {
23 
24  super.onCreate(savedInstanceState);
25  setContentView(R.layout.main);
26 
27  TextView txtContent = (TextView) findViewById(R.id.txtContent);
28  TextView txtFileName = (TextView) findViewById(R.id.txtFileName);
29  ImageView imgAssets = (ImageView) findViewById(R.id.imgAssets);
30 
31  AssetManager assetManager = getAssets();
32 
33  // To get names of all files inside the "Files" folder
34  try {
35   String[] files = assetManager.list("Files");
36 
37   for(int i=0; i<files.length; i++)="" {="" txtfilename.append("\n="" file="" :"+i+"="" name=""> "+files[i]);
38   }
39  catch (IOException e1) {
40   // TODO Auto-generated catch block
41   e1.printStackTrace();
42  }
43 
44  // To load text file
45        InputStream input;
46  try {
47   input = assetManager.open("helloworld.txt");
48 
49          int size = input.available();
50          byte[] buffer = new byte[size];
51          input.read(buffer);
52          input.close();
53 
54          // byte buffer into a string
55          String text = new String(buffer);
56 
57          txtContent.setText(text);
58  catch (IOException e) {
59   // TODO Auto-generated catch block
60   e.printStackTrace();
61  }
62 
63  // To load image
64     try {
65      // get input stream
66      InputStream ims = assetManager.open("android_logo_small.jpg");
67 
68      // create drawable from stream
69      Drawable d = Drawable.createFromStream(ims, null);
70 
71      // set the drawable to imageview
72      imgAssets.setImageDrawable(d);
73     }
74     catch(IOException ex) {
75      return;
76     }
77 }
78}
79</files.length;>
main.xml
Note: Please consider scrollview as ScrollView, textview as TextView….etc. Its just problem inside the code plugin.
01<!--?xml version="1.0" encoding="utf-8"?-->
02 
03<scrollview xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent" android:layout_height="fill_parent">
04 
05<linearlayout android:layout_width="fill_parent" android:layout_height="fill_parent"android:orientation="vertical">
06 
07    <textview android:layout_width="fill_parent" android:layout_height="wrap_content"android:text="@string/hello" android:id="@+id/txtContent">
08 
09 <imageview android:layout_width="fill_parent" android:layout_height="wrap_content"android:id="@+id/imgAssets">
10 
11  <textview android:layout_width="fill_parent" android:layout_height="wrap_content"android:id="@+id/txtFileName">
12</textview></imageview></textview></linearlayout>
13 
14</scrollview>
Download Full source code from here: Android – Read file from Assets
Reference: Android – Read file from Assets from our JCG partner Paresh N. Mayani at the TechnoTalkative blog.














No hay comentarios:

Publicar un comentario