我是Android新手。我试图从Web服务的数组列表中填充列表视图。我没有运气找到任何使用数组到listview的在线教程。我在令牌“final”上收到语法错误,无效的类型
这是我的java代码:
public class LocationFragment extends Fragment {
ListView tv;
public LocationFragment() {
}
private String TAG = "Vik";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_location, container, false);
tv = (ListView) rootView.findViewById(R.id.listView1);
AsyncCallWS task = new AsyncCallWS();
task.execute();
return rootView;
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
location();
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
}
@Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
@Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
public void location()
{
String SOAP_ACTION = "http://example.com/getlocations";
String METHOD_NAME = "getlocations";
String NAMESPACE = "http://example.com/";
String URL = "http://localhost/example/Service.asmx";
try {
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
Request.addProperty("get locations", "null");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE transport= new HttpTransportSE(URL);
transport.call(SOAP_ACTION, envelope);
Object result=(Object)envelope.getResponse();
final results = (String[]) result;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
ArrayAdapter<MyObject> adapter = new ArrayAdapter<MyObject>(this,
android.R.layout.simple_list_item_1, results);
tv.setAdapter(adapter);
}
});
}
catch(Exception ex) {
Log.e(TAG, "Error: " + ex.getMessage());
}
}
}
此处是我的网络服务,我们将不胜感激。
[WebMethod]
public string[] getlocations()
{
SqlConnection cn = new SqlConnection("Data Source=DEV-SQL1;Initial Catalog=portal;User Id=wstest;Password=wstest;");
List<string> locations = new List<string>();
cn.Open();
string sqlquery = string.Format("SELECT LocationName FROM ts_locations where CompanyID = '130' ORDER by LocationName");
SqlCommand com = new SqlCommand(sqlquery, cn);
SqlDataReader sqlReader = com.ExecuteReader();
while (sqlReader.Read())
{
locations.Add(sqlReader.GetString(0));
}
cn.Close();
return locations.ToArray();
}
答案 0 :(得分:0)
看看this tutorial,我调用json web服务将响应数据填充到ArrayList中,并使用该ArrayList填充ListView
关注这一行:
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,titleCollection);
其中titleCollection是ArrayList<String>