2014-02-28 129 views
2

我試圖做一個簡單的詞典,它搜索txt文件中的單詞。我創建了txt文件並存儲了一些英文單詞。我想寫這個詞給EditText。然後,這個單詞將被找到並顯示在TextView上。這是我的代碼。它顯示整個txt文件。我怎樣才能找到具體的詞?我如何從android txt文件中讀取特定文本

public class MainActivity extends Activity { 

//creating variables 
TextView myText; 
EditText myEdit; 
Button myButton; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //initializing the TextView EditText and Button 
    myText=(TextView) findViewById(R.id.idTextView); 
    myEdit=(EditText) findViewById(R.id.idEditText); 
    myButton=(Button) findViewById(R.id.idButton); 


    myButton.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      String saveData=myEdit.getText().toString(); 
      try{ 
      myText.setText(readfile()); 
      }catch(IOException e){ 
       e.printStackTrace(); 
      } 

     } 

    }); 

} 

private String readfile()throws IOException {  

    String str="";   
    InputStream is = getResources().openRawResource(R.raw.translate);  
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    String line=reader.readLine(); 

    while (line!=null) 
    { 
     str = str + line + "\n"; 
     line = reader.readLine(); 

    } 
    reader.close(); 

    return str; 

} 

} 

回答

1

這一切都取決於你的readFile()是如何實現的。我建議您修改它以接受String參數。這樣一來,它會搜索這個詞在文件中,並通過setText()

myText.setText(readFile(saveData))); 

返回其含義另一個String可以分配到TextView是建議的落實會是什麼樣子。


在此方法中,當你讀文件中的行由行,檢查String你只是從文件中讀取包含所需的字。這可以使用方法完成。

1

以爲你是個簡單的檢查後是:

String fileText = readFile(); 

Boolean textFound = fileText.contains(saveData); 

如果布爾值爲true,那麼你會在框中顯示的saveData值。如果你想要,你可以把這個操作放在一個循環中,並搜索多個單詞。