Create/Edit file (txt) on Android

Asked

Viewed 1,290 times

0

Hello... sorry if I posted in the wrong place or wrong way, because I’m new in the forum (although I always read it).

Lollipop helped me a lot with the explanation: /a/48228/68502

But I have three questions:

  1. If I want to keep the data it contains in the created file "Myfile" adding or deleting the content, that is, so that even close the App, while opening it again can recover and continue editing keeping the data,and if you want to clean the contents of the file "Myfile" can do?
  2. If I just want to create the file without content, I just need remove the Cód lines.:

    ... 
    String content = "Olá todos?"; //retirar
    ... 
    outputStream.write(content.getBytes()); //retirar
    ...
    
  3. I can create the directory and the blank files (no content) on project root so that I don’t need to create when running the App since I will only use them?


Edited below!

Please I’m stuck in that part someone... help me!!!

Estrutura do Projeto:

Mainactivity.java

package br.com.aime.aimeappauditoria;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import static android.os.Environment.getDataDirectory;
import static br.com.aime.aimeappauditoria.R.id.btNovoBalanco;
import static br.com.aime.aimeappauditoria.R.id.nomeAuditor;
import static br.com.aime.aimeappauditoria.R.id.nomeFilial;
import static br.com.aime.aimeappauditoria.R.string.local;

public class MainActivity extends AppCompatActivity {

    @SuppressLint("SimpleDateFormat")
    public final SimpleDateFormat data = new SimpleDateFormat("dd/MM/yyyy");
    public final Calendar c = Calendar.getInstance();


    public EditText editTextBuscar;
    public TextView textViewBipados;
    public TextView textViewUltimosItens;
    public TextView textViewLocal;
    public TextView textViewAuditor;
    public TextView textViewTotal;
    public TextView textViewData;

    public Button btnRecomecar;
    public Button btnNovoBalanco;
    public Button btnFinalizar;
    String fileData = "data.txt";
    // String fileAuditor = "auditor.txt";
    // String fileBalanco = "balanco.txt";
    // String fileLocal = "local.txt";


    View popup1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textViewData = (TextView) findViewById(R.id.textViewData);
        textViewTotal = (TextView) findViewById(R.id.textViewTotal);
        textViewAuditor = (TextView) findViewById(R.id.textViewAuditor);
        textViewLocal = (TextView) findViewById(R.id.textViewLocal);
        editTextBuscar = (EditText) findViewById(R.id.editTextBuscar);
        textViewUltimosItens = (TextView) findViewById(R.id.textViewUltimosItens);
        textViewBipados = (TextView) findViewById(R.id.textViewBipados);

        btnNovoBalanco = (Button) findViewById(btNovoBalanco);
        btnFinalizar = (Button) findViewById(R.id.btnFinalizar);
        btnRecomecar = (Button) findViewById(R.id.btnRecomecar);

        btnNovoBalanco.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openPopupStart(v);
                lerData();
            }
        });

        btnRecomecar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lerData();
            }
        });

    }

    public void lerData() {
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
        ArrayList<String> dataTXT;
        String dataConteudo = "";


        try {


            FileReader dataOut2 = new FileReader((fileData));
            BufferedReader dataLer = new BufferedReader(dataOut2);
            dataTXT = new ArrayList<>();
            while (dataLer.readLine() != null) {
                dataTXT.add(dataConteudo);
                textViewData.setText(dataConteudo);
                dataOut2.close();
            }

        }catch( Exception e){
           e.printStackTrace();
         }

    }






    public void criarDataTXT(){
        String data = c.getTime().toString();
        //String auditor = textViewAuditor.getText().toString();
        // String local = textViewLocal.getText().toString();
        // String balanco = "";

        File path = new File(getDataDirectory().getAbsolutePath(), "files");
        File fileTXT = new File(path,fileData);


            try {

                FileWriter dataOut = new FileWriter(fileTXT);
                BufferedWriter dataPrint = new BufferedWriter(dataOut);
                dataPrint.write(data);
                dataPrint.flush();
                dataOut.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }



    public void criarBalanco(){

        criarDataTXT();

    }

    public void openPopupStart(final View start) {

        this.popup1 = start;

        LayoutInflater layoutInflater = LayoutInflater.from(this);
        @SuppressLint("InflateParams") View promptView = layoutInflater.inflate(R.layout.popup_start, null);
        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Iniciar processo de balanço");
        alert.setView(promptView);

        final EditText input = (EditText) promptView.findViewById( nomeFilial);
        final EditText inputAuditor = (EditText) promptView.findViewById( nomeAuditor);

        input.requestFocus();
        input.setHint( local);
        input.setTextColor(Color.BLACK);


        alert.setPositiveButton( R.string.OK, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                String nomeFilial = input.getText().toString();
                String nomeAuditor = inputAuditor.getText().toString();

//                textViewLocal.setText( nomeFilial );
//                textViewData.setText( data.format( c.getTime() ) );
//                textViewAuditor.setText( nomeAuditor );

                try {
                    if (nomeFilial.equals( "" ) || nomeAuditor.equals( "" )) {
                        input.setError( getString( R.string.localVazio ) );
                        inputAuditor.setError( getString( R.string.auditorVazio ) );
                        Toast.makeText( getApplicationContext(),
                                "Digite o Local e Auditor", Toast.LENGTH_SHORT ).show();
                        openPopupStart( null );
                    } else {
                        criarBalanco();
                        Toast.makeText( getApplicationContext(),
                                "Novo Balanço Criado!!!", Toast.LENGTH_SHORT ).show();

                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }
        } ).setNegativeButton( "Cancelar",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                        Toast.makeText( getApplicationContext(),
                                "Novo Balanço cancelado!!!", Toast.LENGTH_SHORT ).show();

                    }
                } );


        // create an alert dialog
        AlertDialog popup = alert.create();

        popup.show();

    }


}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_popup"
    tools:context="br.com.aime.aimeappauditoria.MainActivity">

    <TextView
        android:id="@+id/textViewData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textViewLocal"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:layout_toStartOf="@+id/textViewLocal"
        android:background="@drawable/borda3"
        android:ems="10"
        android:gravity="center"
        android:labelFor="@+id/activity_main"
        android:padding="5dp"
        android:paddingBottom="5dp"
        android:paddingEnd="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingStart="5dp"
        android:paddingTop="5dp"
        android:text="@string/_00_00_0000"
        android:textAllCaps="true"
        android:textSize="17sp"
        android:textStyle="italic"
        android:theme="@style/AppTheme" />

    <TextView
        android:id="@+id/textViewLocal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginBottom="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/borda3"
        android:ellipsize="middle"
        android:ems="10"
        android:gravity="center"
        android:labelFor="@+id/activity_main"
        android:padding="5dp"
        android:paddingBottom="5dp"
        android:paddingEnd="5dp"
        android:paddingLeft="5dp"

        android:paddingRight="5dp"
        android:paddingStart="5dp"
        android:paddingTop="5dp"
        android:text="@string/local"
        android:textAllCaps="true"
        android:textSize="18sp"
        android:textStyle="italic"
        android:theme="@style/AppTheme" />

    <TextView
        android:id="@+id/textViewAuditor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textViewLocal"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="@drawable/borda3"
        android:elevation="0dp"
        android:ems="10"
        android:gravity="center"
        android:labelFor="@+id/activity_main"
        android:outlineProvider="bounds"
        android:padding="5dp"
        android:paddingBottom="5dp"
        android:paddingEnd="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingStart="5dp"

        android:paddingTop="5dp"
        android:text="@string/auditor"
        android:textAllCaps="true"
        android:textSize="18sp"
        android:textStyle="italic"
        android:theme="@style/AppTheme" />

    <TextView
        android:id="@+id/textViewTotal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textViewAuditor"
        android:layout_alignParentEnd="true"
        android:layout_alignTop="@+id/textViewAuditor"
        android:layout_marginEnd="5dp"
        android:layout_marginLeft="5dp"

        android:layout_marginRight="5dp"
        android:layout_marginStart="5dp"
        android:layout_toEndOf="@+id/textViewAuditor"
        android:background="@drawable/borda2"
        android:elegantTextHeight="true"
        android:ellipsize="start"
        android:gravity="center"
        android:labelFor="@+id/activity_main"
        android:padding="5dp"
        android:paddingBottom="5dp"
        android:paddingEnd="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingStart="5dp"
        android:paddingTop="5dp"
        android:text="@string/_0"
        android:textAlignment="inherit"
        android:textSize="20sp"
        android:textStyle="bold|italic"
        android:theme="@style/AppTheme"
        tools:ignore="RtlHardcoded" />

    <TextView
        android:id="@+id/textViewBipados"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_above="@+id/linearLayout"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"

        android:layout_below="@+id/textViewUltimosItens"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="@drawable/borda3"
        android:elegantTextHeight="true"
        android:ems="10"
        android:foregroundGravity="left"
        android:gravity="start"
        android:labelFor="@+id/activity_main"
        android:padding="5dp"
        android:paddingBottom="5dp"
        android:paddingEnd="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingStart="5dp"
        android:paddingTop="5dp"
        android:textAlignment="textStart"
        android:textSize="18sp"
        android:textStyle="italic"
        android:theme="@style/AppTheme"
        tools:ignore="RelativeOverlap" />

    <TextView
        android:id="@+id/textViewUltimosItens"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/editTextBuscar"
        android:layout_marginBottom="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginStart="5dp"
        android:background="@drawable/borda3"

        android:drawableLeft="@drawable/itens"
        android:elegantTextHeight="true"
        android:elevation="1dp"
        android:ellipsize="start"
        android:gravity="center_vertical"
        android:labelFor="@+id/activity_main"
        android:padding="5dp"
        android:paddingBottom="5dp"
        android:paddingEnd="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingStart="5dp"
        android:paddingTop="5dp"
        android:text="   Itens Bipados"
        android:textAlignment="inherit"
        android:textSize="18sp"
        android:textStyle="italic"
        android:theme="@style/AppTheme"
        tools:ignore="HardcodedText,RtlHardcoded" />

    <EditText
        android:id="@+id/editTextBuscar"
        android:layout_width="wrap_content"

        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textViewAuditor"
        android:layout_margin="5dp"
        android:layout_marginBottom="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/borda"
        android:cursorVisible="true"
        android:drawableLeft="@drawable/leitor"
        android:drawingCacheQuality="high"
        android:ellipsize="middle"
        android:gravity="center|start"
        android:hint="   Use o leitor..."
        android:imeOptions="actionDone"
        android:inputType="text"
        android:keepScreenOn="true"
        android:labelFor="@+id/activity_main"
        android:maxLines="1"
        android:padding="10dp"
        android:paddingBottom="5dp"
        android:paddingEnd="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingStart="10dp"
        android:paddingTop="5dp"
        android:selectAllOnFocus="true"
        android:soundEffectsEnabled="true"
        android:textSize="18sp"
        android:textStyle="italic"
        tools:ignore="HardcodedText,LabelFor,RtlHardcoded" />

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/textViewBipados"
        android:layout_alignParentBottom="true"
        android:layout_alignStart="@+id/textViewBipados"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnRecomecar"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5sp"
            android:layout_marginBottom="5sp"
            android:layout_marginEnd="5sp"
            android:layout_marginLeft="5sp"
            android:layout_marginRight="5sp"
            android:layout_marginStart="5sp"
            android:layout_marginTop="5sp"
            android:layout_weight="0.40"
            android:text="@string/recomecar"
            android:textSize="12sp" />

        <Button
            android:id="@+id/btNovoBalanco"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5sp"
            android:layout_marginBottom="5sp"
            android:layout_marginEnd="5sp"
            android:layout_marginLeft="5sp"
            android:layout_marginRight="5sp"
            android:layout_marginStart="5sp"
            android:layout_marginTop="5sp"
            android:layout_weight="0.77"
            android:onClick="openPopupStart"
            android:text="@string/novo_balanco"
            android:textAllCaps="false"
            android:textSize="12sp"
            android:visibility="visible" />

        <Button
            android:id="@+id/btnFinalizar"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5sp"
            android:layout_marginBottom="5sp"
            android:layout_marginEnd="5sp"
            android:layout_marginLeft="5sp"
            android:layout_marginRight="5sp"
            android:layout_marginStart="5sp"
            android:layout_marginTop="5sp"
            android:layout_weight="1"
            android:text="@string/finalizar"
            android:textSize="12sp"
            tools:ignore="RelativeOverlap" />
    </LinearLayout>

</RelativeLayout>

Androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="br.com.aime.aimeappauditoria">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:screenOrientation="portrait"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
        <activity android:name="br.com.aime.aimeappauditoria.Splash">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="br.com.aime.aimeappauditoria.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden" />

    </application>

</manifest>

  • Dude, you can do anything within logic. If it makes sense to you, it has how to create, delete, redo, upload, bla bla bla, various file types and directories. What you have to take care of is in creating a file that can be edited, because depending on the situation, can compromise your application.

  • For example, you create a txt that can be accessed with another application and deleted, but your application depends on that content. This will cause your app to stop working, or something like that.

  • So this I could understand but I think about creating using MODE PRIAVATE in a specific directory, I think I can only access the file through the application, I also believe that to share permissions by ID, but I’m not very worried about it.. and yes on how stage it has any hint? Regarding logic even as all examples I visualized.. they explain how to create a new one and not edit the existing file... that was created in case it does not exist, occurred in another application run. Thank you for your attention!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.