package com.example.ghomi.chapter8_4;

import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class viewActivity extends AppCompatActivity {
    TextView showText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);
        showText = (TextView)findViewById(R.id.getText);
    }

    public void back(View view){
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    public void getPublic (View view){
        File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);
        File myFile = new File(folder,"data1.txt");
        String text = getData(myFile);
        if(text != null)
             showText.setText(text);
         else
             showText.setText("No data");
    }

    public void getPrivate(View view){
        File folder = getExternalFilesDir("testghomi");
        File  myFile = new File(folder, "data2.txt");
        String text = getData(myFile);
        if(text != null)
            showText.setText(text);
        else
            showText.setText("No data");


    }


    private String getData(File myFile){
        FileInputStream input = null;
        try {
            input = new FileInputStream(myFile);
            int i = -1;
            StringBuffer buffer = new StringBuffer();
            while((i = input.read()) != -1){
               buffer.append((char) i);
            }
            return buffer.toString();
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if (input != null){
                try{
                    input.close();
                }catch (IOException e){
                    e.printStackTrace();
                }

            }
        }
        return null;
    }
}
