我希望获得匹配的行,以" a"开头。并结束例如" 140807"在dir.txt中读取此行并将读取数据设置为我的TextView(如下所示:a152z140807)。我不知道为什么,但我的代码在TextView中设置了空白文本。
即使我改变了
data = inputLine;
为:
data = "something";
TextView中的文本设置为空白。提前谢谢。
TextView poleTextowe;
public void mButton (View view){
URLConnection nbpUrl;
String data = null;
try {
nbpUrl = new URL("http://www.nbp.pl/Kursy/xml/dir.txt").openConnection();
InputStream is = nbpUrl.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
if (inputLine.startsWith("a") && inputLine.endsWith("140807")) {
data = inputLine;
}
}
is.close();
}catch(Exception e){
e.printStackTrace();
}
poleTextowe = (TextView)findViewById(R.id.pole1);
poleTextowe.setText(data);
}
下面的xml文件:
<TextView
android:text="@string/hello_world"
android:id="@+id/pole1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/tekst"
android:onClick="mButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/pole1"
android:text="Click"/>
答案 0 :(得分:1)
你可能有这个例外:
android.os.NetworkOnMainThreadException
Android不允许您在主(ui)线程上进行联网。 例如,创建异步任务以执行网络任务。
答案 1 :(得分:0)
这很简单,您的代码会引发异常,具体而言是android.os.NetworkOnMainThreadException
。这意味着data
保持null
,并且没有显示任何内容。在AsyncTask
或Thread
这是一个非常常见的例子。将其设为Activity
public class MainActivity extends Activity {
public void onCreate(Bundle b) {
//usual stuff
}
public void doStuff() {
new LongOperation().execute(); //run asynctask
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
InputStream is = null;
try {
Log.d(TAG, "starting connection");
URLConnection nbpUrl = new URL("http://www.nbp.pl/Kursy/xml/dir.txt").openConnection();
is = nbpUrl.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
if (inputLine.startsWith("a") && inputLine.endsWith("140807")) {
return inputLine; //because if the line's found, no need to look for other lines
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (is != null)
is.close(); //close inputstream in finally block, so it always gets closed
}
Log.d(TAG, "asynctask ran");
return "NOT FOUND";
}
@Override
protected void onPostExecute(String data) {
poleTextowe = (TextView) findViewById(R.id.pole1);
poleTextowe.setText(data);
}
@Override
protected void onPreExecute() { }
@Override
protected void onProgressUpdate(Void... values) { }
}
}