2012年9月17日 星期一

IO -- (4) SDCARD



IO: 列出SDCARD裡的夾子與檔案 & 讀取SDCARD裡某檔案的內容 

public class IO_ListSDCardFilesActivity extends Activity {
    /** Called when the activity is first created. */

private final String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/fileio";
private final String FILE_NAME = "test02.txt";
private final String ENCODING = "UTF-8";

FileInputStream fis = null; // 這裡要設定,否則無法用

TextView tv;
ListView lv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        tv = (TextView) findViewById(R.id.textView);
     
        //列出Sdcard 裡的夾子和檔案,放上LISTVIEW
        try {
        File sdcardPATH = Environment.getExternalStorageDirectory();// 找SD的入徑
        String [] fileNamesArrayStr = sdcardPATH.list(); // 用list(),將SD裡的資料夾和檔案以字串的方式收集在array
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileNamesArrayStr);// 以 listView 顯示在螢幕上
        lv = (ListView) findViewById(R.id.listView1);
        lv.setAdapter(adapter);
        } catch (Exception e) {
        e.printStackTrace();
        }
 
     
        readFile(); //讀出指定的檔到TEXTVIEW上
     
    }// end of onCreate
 
 
 
    public void readFile () {
   
    String result = "";
    try {
   
    File mFilePath = new File (SD_PATH + FILE_PATH);
    String mFileName = mFilePath + "/" + FILE_NAME;
    File fileText = new File (mFileName);
   
    fis = new FileInputStream(fileText);
    int length = fis.available();
    byte [] buffer = new byte [length];
    fis.read(buffer);
    result = EncodingUtils.getString(buffer, ENCODING);
    fis.close();
    tv.setText(result);
   
    } catch (Exception e) {
    e.printStackTrace();
    }
    }// end of readFile();
}

IO: (6) + TTS 給英聽練習使用


IO + TTS : 給英聽練習使用


主程式:


//設計英語英聽口說練習
public class IO_TTS_EnglishSpeakingActivity extends Activity implements OnInitListener{
    /** Called when the activity is first created. */
private final String SDCARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/fileio";
// private final String ENCODING = "UTF-8";
private File [] filesArray;
private File mDataPath;
private FileInputStream fis = null;
TextView tv;
ListView lv;
private String aFileName;
String [] strings;
 
private TextToSpeech mTTS;
private Button answerBtn;
private Button goBackBtn;
String result = "";
private static int NO_OF_QUESTIONS = 5;
private String [] questionsStr = new String [NO_OF_QUESTIONS];
private int flag; //判斷是否還留在原來的試卷裡
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tv= (TextView) findViewById(R.id.textView01);
//        tv.setMovementMethod(ScrollingMovementMethod.getInstance());
        
        mDataPath = new File (SDCARD_PATH + FILE_PATH);
        filesArray = mDataPath.listFiles();
        
        listFiles();//列出所有的檔案
        
        mTTS = new TextToSpeech(getApplicationContext(), this);//初始化
        answerBtn = (Button) findViewById(R.id.button2);
        answerBtn.setOnClickListener(answerListener);
        
        goBackBtn = (Button) findViewById(R.id.goBackButton);
        goBackBtn.setOnClickListener (goBackListener);
        
        flag = 1;
           
    }// end of onCreate
    
    
    //列出所有英聽的檔案,顯示在ListView上
    private void listFiles() {
    
    String fileNames = ""; // to receive every single file name
        for (int i = 0; i < filesArray.length; i++) {
        if (filesArray[i].isFile()) { //get rid of directories
        String tempStr = ""; //會多出入徑的字串
        tempStr = filesArray[i].toString();
        String strSub = ""; //to subtract the uneccessary part: /mnt/sdcard/fileio/ (19 個字元)
        strSub = tempStr.substring(19, tempStr.length()).toString();
        fileNames += strSub + "--";
        }
        }
        
        //Handle to subtraction of the final "--" in fileNames string
        String result = "";
        result = fileNames.substring(0, fileNames.length()-2);
        strings = TextUtils.split(result, "--");
        
        
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings);
        lv = (ListView) findViewById(R.id.listView1);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(listener);
    
    }// end of listFiles ();
    
    
    
// 看答案的按鈕
private OnClickListener answerListener = new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

if (questionsStr[0] == null) {
Toast.makeText(Cq_IO01Activity.this, "請選擇試卷!",
Toast.LENGTH_SHORT).show();
tv.setMarqueeRepeatLimit(-1);
} else if (flag == 1){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
Cq_IO01Activity.this,
android.R.layout.simple_list_item_1, questionsStr);
lv.setAdapter(adapter);
answerBtn.setText("不看題目");
answerBtn.setTextColor(Color.MAGENTA);
flag = 0;
} else if (flag == 0) {
listFiles();

answerBtn.setText("觀看題目");
answerBtn.setTextColor(Color.BLACK);
flag = 1;
}
}
};
    
    
  //按下按鈕回到原先列出全部英聽檔案的畫面
  private OnClickListener goBackListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mTTS != null) {
mTTS.stop();
}
listFiles();
tv.setText("請選擇下列試題卷練習英聽口說:");
tv.setTextColor(Color.RED);
tv.setMarqueeRepeatLimit(-1);
answerBtn.setText("觀看題目");
answerBtn.setTextColor(Color.BLACK);
}
};
  
  
    //選擇要唸出的檔案; 將內容的五個問題分別間隔唸出
    private OnItemClickListener listener = new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
aFileName = strings[position].toString();

tv.setText("正在播放 " + aFileName + " 練習,一共五題,每題播放兩次:");
tv.setTextColor(Color.GREEN);
tv.setMarqueeRepeatLimit(-1);
readSingleLine(aFileName); //讀出每個問題
}
};// end of listener
    
private void readSingleLine (String aFileName) {
try {
String mFileName = mDataPath + "/" + aFileName;
File fileContent = new File (mFileName);
fis = new FileInputStream(fileContent);
DataInputStream dis = new DataInputStream(fis);
for (int i = 0; i< NO_OF_QUESTIONS; i++) {
String tempStr = "";
tempStr = dis.readLine() + "\n";
questionsStr[i] = tempStr;
//讀出所選檔案的內容
mTTS.speak(tempStr, TextToSpeech.QUEUE_ADD, null); //用QUEUE_ADD可以再接其他的字串;queue_flush將無法做到                                                       //唸第一次
mTTS.playSilence(2000, TextToSpeech.QUEUE_ADD, null);   //停頓兩秒
mTTS.speak(tempStr, TextToSpeech.QUEUE_ADD, null);        //唸第二次
mTTS.playSilence(2000, TextToSpeech.QUEUE_ADD, null);   //停頓兩秒
mTTS.speak("Please answer now.", TextToSpeech.QUEUE_ADD, null); //請使用者回答
mTTS.playSilence(8000, TextToSpeech.QUEUE_ADD, null);                  //給予八秒的時間回答

}
} catch (Exception e) {
e.printStackTrace();
}
}// end of readSingleLine ()

@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
mTTS.setSpeechRate(0.9f);// 正常速度是 1.0f; 小過它會變慢
mTTS.speak("I'm ready for listening and speaking practice.", TextToSpeech.QUEUE_FLUSH, null);
}else {
System.out.println("Oops!");
}
}


@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mTTS.shutdown();
}


@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mTTS != null) {
mTTS.stop();
}
}
}


**********************************
res/layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/sunset" >

    <TextView
        android:id="@+id/textView01"
        android:layout_width="350px"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:text="請選擇下列試題卷練習英聽口說:"
        android:ellipsize="marquee"
        android:scrollHorizontally="true"
        android:singleLine="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textColor="#FF0000"
        android:textSize="22dp" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="75dp"
        android:layout_weight="0.70"
        
        android:divider="@drawable/list_item_divider"
        android:cacheColorHint="#00FF0000"
        android:dividerHeight="5px"    >
        
    </ListView>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        
        <Button
        android:id="@+id/button2"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:text="觀看題目" />
        
        <Button
        android:id="@+id/goBackButton"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:text="選擇新試卷" />
        
    </LinearLayout>

    
</LinearLayout>

*******************************
res/drawable/list_item_divider:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="line" >
   <stroke 
       android:width="1dp"
       android:color="#8F8F8F"
       android:dashWidth="1dp"
       android:dashGap="1dp"/>
</shape>