我有一个包含从文本文件读入的字符串的ArrayList。我希望这些字符串填充一个微调器,但我的代码不起作用,并且当我将鼠标悬停在该行上时它说“无法解析构造函数”:
ArrayAdapter adp = new ArrayAdapter(this, android.R.layout.simple_spinner_item, devicesAL);
以下是我的其余代码,我提供了所有代码,因为我不知道原因在哪里。该特定位在第二个try块中。有人可以帮忙吗?
package com.example.iotdevicestatus;
public class MainActivity extends AppCompatActivity {
String statusLink = "http://redacted.uk/pmt/status.txt";
String deviceLink = "http://redacted.uk/pmt/devices.txt";
String status = "status testttest";
ArrayList<String> devicesAL = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
// Set up connection to device.txt on web server
URL deviceUrl = new URL (deviceLink);
URLConnection deviceConn = deviceUrl.openConnection();
deviceConn.setDoOutput(true);
deviceConn.connect();
InputStream dis = deviceConn.getInputStream();
InputStreamReader disr = new InputStreamReader(dis, "UTF-8");
BufferedReader dbr = new BufferedReader(disr);
String deviceLine;
// Set up connection to status.txt on web server
URL statusUrl = new URL(statusLink);
URLConnection statusConn = statusUrl.openConnection();
statusConn.setDoOutput(true);
statusConn.connect();
InputStream sis = statusConn.getInputStream();
InputStreamReader sisr = new InputStreamReader(sis, "UTF-8");
BufferedReader sbr = new BufferedReader(sisr);
String statusLine;
try {
while ((deviceLine = dbr.readLine()) != null) {
System.out.println(deviceLine);
devicesAL.add(deviceLine);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adp = new ArrayAdapter(this, android.R.layout.simple_spinner_item, devicesAL);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adp);
}
while ((statusLine = sbr.readLine()) != null) {
System.out.println(statusLine);
status = statusLine;
System.out.println("Status = " + status);
//al.add(line); - use in case of multiple statuses
TextView output = (TextView) findViewById(R.id.textView);
System.out.println(status);
output.setText(status);
}
for (String str : devicesAL) {
System.out.println(str);
}
} finally {
sbr.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
答案 0 :(得分:1)
请注意,匿名类中的this
引用该匿名类。你想要的是MainActivity
的实例,而不是Runnable
匿名子类的实例。
ArrayAdapter adp = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, devicesAL);
由于您的Spinner仍未填充,您可以
devicesAL
adp.notifyDataSetChanged()
。Activity#runOnUiThread()
内的用户界面相关的所有内容。