package com.example.mobapp_i_gui4;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

	ArrayAdapter<String> adapter;
	ArrayList<String> entries;

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

		entries = new ArrayList<String>();
		adapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, entries);
				
		ListView listView = (ListView) findViewById(R.id.listView1);
		listView.setAdapter(adapter);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void loadFilesRoot(View v)
	{
		entries.clear();
		
		File f = new File("/");
		File[] files = f.listFiles();
		for (File aFile : files ) 
		{
			entries.add(aFile.toString());
		}
		
		adapter.notifyDataSetChanged();
	}
	
	public void loadFilesCur(View v)
	{
		// save a file to ensure that the directory is not empty
		String filename = "myfile";
		String string = "Hello world!";
		FileOutputStream outputStream;

		try {
		  outputStream = openFileOutput(filename, MODE_PRIVATE);
		  outputStream.write(string.getBytes());
		  outputStream.close();
		} catch (Exception e) {
		  e.printStackTrace();
		}
		
		entries.clear();
		
		File f = getFilesDir();
		File[] files = f.listFiles();
		for (File aFile : files ) 
		{
			entries.add(aFile.toString());
		}
		
		adapter.notifyDataSetChanged();
	}
}
