Recipe 10.6 Attaching Files to Your Project

Android versions
Level 1 and above
Permissions
None
Source code to download from Wrox.com
FileAttachment.zip

Besides creating files during runtime, it is also very common for developers to attach documents to a project during design time so that they are available during runtime. For example, you might want to attach HTML files to your project so that you can load them onto a WebView view later.

Solution

To attach a file to your project, create a raw folder under the res folder (see Figure 10-6). Add a file to it and name it, say, textfile.txt. Populate it with the string shown in the figure.

To read from the text file, use the InputStream class and refer to the file stored in the raw folder using the get.Resources().openRawResource() method:

package net.learn2develop.fileattachment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        InputStream is = 
                this.getResources().openRawResource(R.raw.textfile);
        BufferedReader br = 
 new BufferedReader(new InputStreamReader(is)); ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.