2014年6月23日 星期一

Android SQLite Error: attempt to re-open an already-closed object

attempt to re-open an already-closed object

例外事件是因為你的SQLite資源沒有關閉所造成的問題。

修正方式:
在使用SQLiteDatabase、ContentValues、Cursor三個物件類別時,在最後要記得使用close();方法關閉。
且在使用Cursor如下範例:
SQLiteDatabase db=this.getWritableDatabase(); //在使用Cursor類別時,建議加上這段,因為我把它寫成全域變數,並在一開始Create實作會出錯,所以我都在用它(Cursor)前,都會寫上這段就沒問題了~
Cursor c = db.query(xxxx); //SQL查詢函數用法參考此網站
實作內容.......
用完後在最後加上
c.close();
db.close();
就可以了~建議順序是這樣喔!!



2014年6月5日 星期四

Android Search

Android Search 實作分兩種
1.Search Dialog
2.Search Widget
差別在於Search Dialog只會顯示在最上方,而Search widget可以放置在任意地方。

Search Widget必須實作 SearchView,如下:
//取得SearchView和設定 searchable configuration
SearchManager searchManager=(SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView=(SearchView)findViewById(R.id.searchView1);

searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); //效果是一開始出現輸入的方框,如果沒這行,則是點下icon才出現輸入方框
searchView.setSubmitButtonEnabled(true); //出現submit 按鈕在方框右邊。


Android SQLite truncate table (清空table的方法)

SQLite沒有像SQL有 truncate語法,所以我們可以如下操作:
//清空data
public void cleanHistoryTable(){
SQLiteDatabase db=this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS history"); //刪除history table
this.onCreate(db); //在onCreate去新增
db.close();
}

Android AlertDialog 彙整

AlertDialog.Builder 方法:
AlertDialog.Builder dialog=new AlertDialog.Builder(getActivity()); //實作
1. dialog.setCancelable(false); //此設定是你必須按下dialog裡的按鈕,不能按下如「返回鍵」、其他區塊跳離。
2.dialog.show(); //顯示出dialog。

2014年5月13日 星期二

PHP 文字轉語音(Text To Speech,TTS) Google Translation 下載成mp3檔案

      今天終於解決困擾我整個下午的程式問題,語音轉文字(TTS)問題,問題如標題所說,我想把這個網址(http://translate.google.com/translate_tts?tl=zh_TW&q=你好 )存成mp3檔案,但你如果是使用這個網址(http://translate.google.com/translate_tts?tl=en&q=hello), 透過php 的file_get_contents(url網址)函數下載是可行,而使用繁體中文就不行(會出現錯誤的語音),一開始想說是編碼上出了錯誤,但是不管我怎麼試(轉UTF-8、big5、UTF-16)都還是不行,最後我終於爬到我要的資料~原因出在少了一個query參數ie=utf-8。
程式碼如下:
<?php
 //http get query參數設定 tl設定國家語言(ex:en、zh_TW)  q設定要語音的 內容
$qs = http_build_query(array("ie" => "utf-8","tl" => 'zh_TW', "q" => '你好'));
$ctx = stream_context_create(array("http"=>array("method"=>"GET","header"=>"Referer: \r\n")));
$soundfile = file_get_contents("http://translate.google.com/translate_tts?".$qs, false, $ctx);
  //設定檔頭為影音檔
header("Content-type: audio/mpeg");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
 
echo($soundfile);
?>