How to create a log error file in android studio? And also perform read/write operation in a file.

Asked 25-Oct-2018
Viewed 888 times

0

How to create a log error file in android studio? And also perform read/write operation in a file.


1 Answer


1

“Log file in an android studio” 

In any programming language for tracking our application performance as well as for maintaining the history of any bugs or error, we generally create a log file in any temporary folder. That helps us to save our time for easily finding the bugs in a whole application.

Here we demonstrate the simple example for creating a log file in android studio-

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.msclient009.readwritedatafromfile.MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="File Read/Write Operation"
        android:layout_marginStart="40dp"
        android:textColor="#f00"
        android:textSize="22dp"
        android:gravity="top" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_below="@id/textView1"
        android:orientation="horizontal"
        android:layout_marginStart="0dp"
        android:gravity="right"
        android:layout_height="wrap_content">

    <Button
       android:id="@+id/write_file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="35dp"
        android:text="Write File" />

        <Button
            android:id="@+id/read"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/textView1"
            android:layout_marginTop="35dp"
            android:text="Read File" />
    </LinearLayout>

    <TextView
        android:id="@+id/displayText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:textSize="18dp"
        android:textColor="#07C"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="112dp"
        android:text="Read File Text Display Here..." />

</RelativeLayout>

MainActivity.java

package com.example.msclient009.readwritedatafromfile;

import android.annotation.TargetApi;
import android.content.Context;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    Button readButton, writeButton;
    TextView displayText;
    File file;
    static final int READ_BLOCK_SIZE = 100;
    String fileName;
    //Summernote summernote;

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

        readButton=(Button)findViewById(R.id.read);
        writeButton=(Button)findViewById(R.id.write_file);

        displayText=(TextView)findViewById(R.id.displayText);
     // summernote=(Summernote)findViewById(R.id.summernote);

        writeButton.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.N)
            @Override
            public void onClick(View view) {
                try{
                    int i=10;
                    int j=0;
                    int result=(int)i/j;
                    displayText.setText(" Result :"+result);
                }catch(Exception e){
                    createLogErrorFile(e.toString());
                }
            }
        });


        readButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               // displayText.setText("Read Button Click");
                readFile();
            }
        });


        downloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                displayText.setText("Download Button Click");
            }
        });
    }

    private void readFile() {
        try {

            FileInputStream fileIn=openFileInput(fileName);
            InputStreamReader InputRead= new InputStreamReader(fileIn);

            char[] inputBuffer= new char[READ_BLOCK_SIZE];
            String s="";
            int charRead;

            while ((charRead=InputRead.read(inputBuffer))>0) {
                // char to string conversion
                String readstring=String.copyValueOf(inputBuffer,0,charRead);
                s +=readstring;
            }
            InputRead.close();
            displayText.setText(s);

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



    @RequiresApi(api = Build.VERSION_CODES.N)
    private void createLogErrorFile(String errMessage) {
        try {
            Date todayDate = Calendar.getInstance().getTime();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String currentDate = formatter.format(todayDate);

            fileName = currentDate + "_logFile.txt";
           /* File root = new File(Environment.getExternalStorageDirectory(), "LogErrorFolder");

            if (!root.exists()) { // folder not found
                root.mkdirs();
            }
            file = new File(root, fileName);*/
            displayText.setText(fileName +" is created");

            FileOutputStream fileout=openFileOutput(fileName, MODE_PRIVATE);
            OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
            outputWriter.write(" Log Entry : "+currentDate);
            outputWriter.write("\n Error Message : "+errMessage);
            outputWriter.write("\n ========================================\n\n");
            outputWriter.close();

            fileout.flush();
            fileout.close();

            //display file saved message
            Toast.makeText(getBaseContext(), " Log File Created Successfully!", Toast.LENGTH_SHORT).show();
         }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

Output :
How to create a log error file in android studio? And also perform read/write operation in a file.

After clicking on read file then the following screen will be display-
How to create a log error file in android studio? And also perform read/write operation in a file.


"Thanks!!! For Reading"