segunda-feira, 7 de maio de 2012

Lendo texto do Conteúdo Raw na pasta Resource.

( Android )


É possível armazenar o conteúdo na pasta raw e fazer a leitura utilizando o método abaixo ...

Primeiros passos: 

1. Crie uma pasta raw em res/
2. Crie um arquivo de texto e salve na pasta res/raw, que você acabou de criar
3. Criar Método chamado readTextResource() 
4. Utilize o código abaixo para ler os dados

StringBuffer strBuffer = new StringBuffer();
  InputStream inputStream = null;
  try {
   inputStream = owner.getResources().openRawResource(resourceId);
   BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
   String str = br.readLine();
   while (str != null) {
    strBuffer.append(str);
    str = br.readLine();
   }
  } catch (IOException e) {   
  } finally {
   try {
    if (inputStream != null) {
     inputStream.close();
    }
   } catch (IOException e) {    
   }
  }


5. Retorna o valor StringBuffer.
6. Se você precisa de um formato html, você pode usar a classe util html
Html.fromHtml (text); 



Exemplo completo do código 


public class MinhaActivity extends Activity {

 private Spanned mText = null;
 private TextView mTextView;

 public void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  mTextView = (TextView) findViewById(R.id.sampleText);

  if (mText == null) {

// Passando o nome do arquivo como parametro utilizando a Class R e o contexto
   String text = readTextResource(R.raw.meuarquivo, this);

   mText = Html.fromHtml(text);
  }
  mTextView.setText(mText);
 }

 public String readTextResource(int resourceId, Activity owner) {

  StringBuffer strBuffer = new StringBuffer();  
  InputStream inputStream = null;

  try {

   inputStream = owner.getResources().openRawResource(resourceId);

   BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

   String str = br.readLine();
   while (str != null) {

    strBuffer.append(str);
    str = br.readLine();

   }
  } catch (IOException e) {   
  } finally {
   try {
    if (inputStream != null) {
     inputStream.close();
    }
   } catch (IOException e) {    
   }
  }

  return strBuffer.toString();

 }   
}



Nenhum comentário:

Postar um comentário