Android - Pasar el texto de un archivo a un TextView

 
Vista:

Pasar el texto de un archivo a un TextView

Publicado por ana (2 intervenciones) el 20/01/2019 00:45:19
Hola a tod@s,

Les comento mi situación:

Estoy obteniendo datos por el puerto serie en Android, y quiero visualizarlos en un TextView.

He comprobado que recibo correctamente los datos mediante la Shell de Android:

cat /dev/ttyS0

131
132
133
133
134
… (se sigue actualizando)

Esos números son la temperatura que me manda el Arduino, visualizados desde la Shell Android.



Bien, pasemos a mi código JAVA:


public void start(View view) throws InterruptedException {

Button empezar = (Button) findViewById(R.id.empezar);

Process process = null;

DataOutputStream dos = null;


try
{

process = Runtime.getRuntime().exec("su");

dos = new DataOutputStream(process.getOutputStream());
dos.writeBytes("exec 3</dev/ttyS0" + "\n"); //REDIRECT SERIAL OUTPUT TO FD 3.
dos.flush(); // Enter???
dos.writeBytes("cat <&3 > /sdcard/temperatura.txt & PID=$!" + "\n"); //REDIRECT SERIAL OUTPUT TO FILE
dos.flush();
dos.writeBytes("kill $PID" + "\n"); //KILL CAT PROCESS
dos.flush();
dos.writeBytes("exec 3<&-" + "\n"); // FREE FD 3
dos.flush();
dos.close();
} catch (IOException gpio) {
gpio.printStackTrace();
}

Con esta parte consigo crear en la memoria externa virtual (0/sdcard) un archivo temperatura.txt que se va actualizando con la información recibida por serie. Si abro temperatura.txt puedo ver los valores del serial:

131
132
133
133
134
… (se sigue actualizando temperatura.txt)





Ahora viene mi PROBLEMA:

Quiero pasar esos datos, bien desde el archivo situado en la memoria interna /dev/ttyS0 o bien desde /sdcard/temperatura.txt, a un TextView.

He probado los métodos que se describen en la web para pasar texto de un archivo a una String, pero no consigo que al presionar el botón identificado como start se muestre la información de temperatura.txt en un TextView. Al presionar el botón ocurren otros eventos que tengo programados, pero no me muestra los datos deseados en el TextView. El código completo sería:




public void start(View view) throws InterruptedException {

Button empezar = (Button) findViewById(R.id.empezar);

Process process = null;

DataOutputStream dos = null;

try
{

process = Runtime.getRuntime().exec("su");

dos = new DataOutputStream(process.getOutputStream());
dos.writeBytes("exec 3</dev/ttyS0" + "\n"); //REDIRECT SERIAL OUTPUT TO FD 3.
dos.flush(); // Enter???
dos.writeBytes("cat <&3 > /sdcard/temperatura.txt & PID=$!" + "\n"); //REDIRECT SERIAL OUTPUT TO FILE
dos.flush();
dos.writeBytes("kill $PID" + "\n"); //KILL CAT PROCESS
dos.flush();
dos.writeBytes("exec 3<&-" + "\n"); // FREE FD 3
dos.flush();
dos.close();
} catch (IOException gpio) {
gpio.printStackTrace();

class LeeFichero {
public void main(String[] arg) {
File archivo = null;
FileReader fr = null;
BufferedReader br = null;

try {
archivo = new File (Environment.getExternalStorageDirectory().getPath(), "temperatura.txt");
fr = new FileReader (archivo);
br = new BufferedReader(fr);

// File read
String linea = br.readLine();
while((linea=br.readLine())!=null)

// Write string to the textView
{
TextView temperatura = (TextView)findViewById(R.id.temperatura);
temperatura.setText (linea);
}

}
catch(Exception e){
e.printStackTrace();
}finally{
try{
if( null != fr ){
fr.close();
}
}catch (Exception e2){
e2.printStackTrace();
}
}
}
}
***También he probado a copiar temperatura.txt a data/data/myapk/files e introducir el siguiente código:



try
{
BufferedReader fin =
new BufferedReader(
new InputStreamReader(
openFileInput("temperatura.txt")));

String texto = fin.readLine();
fin.close();
TextView temp = (TextView)findViewById(R.id.temperatura);
temp.setText((CharSequence) texto);
}
catch (Exception ex)
{
Log.e("Ficheros", "Error al leer fichero desde memoria interna");
}

{
TextView temp = (TextView) findViewById(R.id.temperatura);
temp.setText("texto");
}

De ninguna manera consigo visualizar los datos de temperatura.txt en el TextView.

Que hago mal?

Muchas gracias!
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Pasar el texto de un archivo a un TextView

Publicado por ivan (2 intervenciones) el 20/01/2019 04:38:53
Buenas, haciendo pruebas, si creo un archivo.txt mediante el código JAVA:

1
2
3
4
5
6
7
8
9
try {
    OutputStreamWriter fout= new OutputStreamWriter(openFileOutput("temperatura1.txt", Context.MODE_PRIVATE));
    fout.write("Esto es una prueba!");
    fout.close();
}
catch (Exception ex)
{
    Log.e("Ficheros", "Error al escribir fichero a memoria interna");
}

SI lo puedo mandar a un TextView:

1
2
3
4
5
6
7
8
9
10
11
try{
    BufferedReader fin = new BufferedReader(new InputStreamReader(openFileInput("juan.txt")));
    String texto = fin.readLine();
    TextView temp = (TextView)findViewById(R.id.temperatura);
    temp.setText((CharSequence) texto);
    fin.close();
}
catch (Exception ex)
{
    Log.e("Ficheros", "Error al leer fichero desde memoria interna");
}


PERO si copio un archivo a mano dentro de /data/data/miapk/files, no se muestra el contenido en el textview al usar el método InputStreamReader(openFileInput()).

Es decir, copio un archivo prueba.txt , con contenido "prueba"en data/data/…, ejecuto el siguiente código y...:

1
2
3
4
5
6
7
8
9
10
11
try{
    BufferedReader fin = new BufferedReader(new InputStreamReader(openFileInput("prueba.txt")));
    String texto = fin.readLine();
    TextView temp = (TextView)findViewById(R.id.temperatura);
    temp.setText((CharSequence) texto);
    fin.close();
}
catch (Exception ex)
{
    Log.e("Ficheros", "Error al leer fichero desde memoria interna");
}

NADA!, no se visualiza en el TextView.

Hace falta algún formato especial en el txt que copio a ese directorio, o que problema hay?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar