我是android編程新手,請原諒。這是我的第一個應用程序,其目的是在用戶放置在SD卡上的txt中查找在搜索小部件中鍵入的字符串。我幾乎完成了它,但我最後的目標是添加一個功能,允許用戶決定在搜索後有多少答案。所以我添加了一個EditText字段,我可以鍵入一個數字。這是我的問題:我無法檢索我在EditText字段中輸入的數據,但我不知道爲什麼。這是我的創作。Android從EditText檢索數據
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText editText = (EditText) findViewById(R.id.enter_a_number); // I think this is the firs part of my problem...
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
int number = Integer.valueOf(editText.getText().toString()); // ...and that is the second
do_my_search(query, number);
}
}
和do_my_search方法:
public void do_my_search(String query, int number) {
//Find the directory for the SD Card using the API
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"fragment.txt");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "windows-1250"),8192);
String line;
String[] text = new String[5];
int i = 0;
TextView textView1 = (TextView)findViewById(R.id.textView1);
textView1.setMovementMethod(new ScrollingMovementMethod());
while ((line = br.readLine()) != null) {
if(line.toLowerCase().contains(query.toLowerCase()) == true && i < number){
text[i] = i + 1 + "." + line + "\n";
i++;
}
}
for(i = 0; i < number ; i ++){
if(text[i] == null)
text[i] = "";
}
StringBuilder builder = new StringBuilder();
for (String value : text) {
builder.append(value);
}
String final_string = builder.toString();
Spannable wordtoSpan = new SpannableString(final_string);
for(i = 0;;){
int k = final_string.indexOf(query,i);
if (k == -1)
break;
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), k, k + query.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
i = k + query.length();
}
textView1.setText(wordtoSpan);
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
}
一切,但文本字段工作正常。我瀏覽過一些類似的線程,我認爲我的問題是變量數字在字段中輸入任何內容之前都會獲取值,即使它顯示了不同的內容,它也會選擇默認文本。我知道我的代碼中可能會出現一些錯誤,但現在我對解決這個特定問題感興趣:我應該如何讓我的可變數字選擇我在edittext字段中輸入的值?是否有可能沒有添加按鈕或TextWatcher?
您可以發佈您activity_main.xml中的文件裏面? – Nick
http://pastebin.com/pDtjmHqk –