我需要我的 ArrayAdapter 将加载来自 HTTP 请求的数据。
我的 onCreate 方法:
private Spinner spiCities;
private ArrayAdapter<String> citiesAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread() {
@Override
public void run() {
LoadCities lc = new LoadCities();
lc.execute();
}
}.start();
}
我在 Activity 中有一个内部类:
class LoadCities extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
BufferedReader br = null;
try {
URL url = new URL("http://10.0.2.2/inter/api/loadCities.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if ( con.getResponseCode() != 200 ) {
throw new RuntimeException( "Error: " + con.getResponseMessage() );
}
br = new BufferedReader( new InputStreamReader( con.getInputStream() ) );
} catch ( MalformedURLException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
}
if ( null == br ) {
return "[]";
}
else {
StringBuilder sb = new StringBuilder();
try {
String linha;
while ( (linha = br.readLine()) != null ) {
sb.append( linha );
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
s = s.substring(1);
s = s.substring(0, s.length()-1);
List<String> listCities = new ArrayList<>();
String s1;
for ( String aux : s.split(",") ) {
s1 = aux.substring(1);
s1 = s1.substring(0, s1.length()-1);
listaCidades.add(s1);
}
小唯快跑啊
智慧大石
随时随地看视频慕课网APP
相关分类