如何获取 ListView 的值并在单击时显示该值?
我从 mysql 数据库中获取值。
public class SearchlistviewActivity extends Activity {
/** Called when the activity is first created. */
private ListView lv1;
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
private ArrayList<String> map= new ArrayList<String>();
protected int selected;
//private ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String>>();
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.listView1);
getServerData(strURL);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , map));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView arg0, View v, int position,
long id) {
Toast.makeText(SearchlistviewActivity.this,"Listed", Toast.LENGTH_SHORT).show();
}
});
}
public static final String strURL = "http://192.168.0.2/ville.php";
private String getServerData(String returnString ) {
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("ville",""));
try {
HttpClient httpclient = new DefaultHttpClient();
String http="http://" ;
String myip ="192.168.0.2" ;
String vil="/ville.php";
String myurl=http+myip+vil;
HttpPost httppost = new HttpPost(myurl);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
} catch(Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// Parse les donnA©es JSON
try {
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","CostumerOrder: "+json_data.getString("CostumerOrder")+
", OrderPrice: "+json_data.getString("OrderPrice")
);
map.add(json_data.getString("CostumerOrder").toString());
}
} catch(JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}