我需要你的帮助。我想发送一个URL请求,获取响应并创建一个JSON对象。我的第一次尝试完全错了。现在我找到了一个教程,并进行了新的尝试。
我的活动看起来像:
public class Patienten extends Activity {
//Beacon Elemente
private String UUID;
private String Major;
private String Minor;
private TextView output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patienten);
output = (TextView) findViewById(R.id.output);
UpdateBeaconInformation();
Button cmdHit = (Button) findViewById(R.id.cmd_hit);
cmdHit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
}
});
setTitle(Surname + ", " + FirstName);
// output.setText(output.getText().toString() + "Gefundener Patient:n" + "Name: " + Surname + ", " + FirstName + "nGeb.-Dat: " + Birthdate);
}
然后我创建了一个新的Java类,并用它构建了一个asyncTask。但我无法访问onPostExecute中的textview输出来更新它。
public class JSONTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
//http://kusber-web.de/JsonTest.txt
//http://nilsbenning.selfhost.me/PatientFinder.php?beacon_comID=5181f8a3-7354-46ac-b22d-952ec395ab06&beacon_major=12&beacon_minor=249
URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
output.setText(result);
}
}我犯了什么错?为什么我无法访问它?我认为这是一个解决方案,但没有让它发挥作用:
https://stackoverflow.com/a/12252717/5743912
希望你现在能帮助我!:)
您可能想要修复此问题(删除前导斜杠):
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
在JSONTask中,您可以使用Patienten.this
引用Patienten的成员。因此,在onPostExecute
中,您应该更改以下内容:
output.setText(result);
至:
Patienten.this.output.setText(result);