如何在我的 Listview 中添加 onItemClick 以使用 Asynctask 从 MYSQL 获取数据

how to add onItemClick in my Listview that get data from MYSQL with Asynctask

我是 Android 编程的初学者。我只想问一下如何使用 Asynctask 在我的列表视图中添加 onItemClick。这是代码

 public class ListUser extends Activity {
 private String jsonResult;
 private String url = "http://gspelocator.net46.net/test/list_user.php";
 private ListView listView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main_list);
  listView = (ListView) findViewById(R.id.listView1);
  accessWebService();
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 // Async Task to access the web
 private class JsonReadTask extends AsyncTask<String, Void, String> {
  @Override
  protected String doInBackground(String... params) {
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(params[0]);
   try {
    HttpResponse response = httpclient.execute(httppost);
    jsonResult = inputStreamToString(
      response.getEntity().getContent()).toString();
   }

   catch (ClientProtocolException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
   return null;
  }

  private StringBuilder inputStreamToString(InputStream is) {
   String rLine = "";
   StringBuilder answer = new StringBuilder();
   BufferedReader rd = new BufferedReader(new InputStreamReader(is));

   try {
    while ((rLine = rd.readLine()) != null) {
     answer.append(rLine);
    }
   }

   catch (IOException e) {
    // e.printStackTrace();
    Toast.makeText(getApplicationContext(),
      "Error..." + e.toString(), Toast.LENGTH_LONG).show();
   }
   return answer;
  }

  @Override
  protected void onPostExecute(String result) {
   ListDrwaer();
  }
 }// end async task

 public void accessWebService() {
  JsonReadTask task = new JsonReadTask();
  // passes values for the urls string array
  task.execute(new String[] { url });
 }

 // build hash set for list view
 public void ListDrwaer() {
  List<Map<String, String>> userList = new ArrayList<Map<String, String>>();

  try {
   JSONObject jsonResponse = new JSONObject(jsonResult);
   JSONArray jsonMainNode = jsonResponse.optJSONArray("users");

   for (int i = 0; i < jsonMainNode.length(); i++) {
    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
    String username = jsonChildNode.optString("username");
    String telp = jsonChildNode.optString("telp");
    String outPut = username + " - " + telp;
    userList.add(createUser("users", outPut));
   }
  } catch (JSONException e) {
   Toast.makeText(getApplicationContext(), "Error" + e.toString(),
     Toast.LENGTH_SHORT).show();
  }

  SimpleAdapter simpleAdapter = new SimpleAdapter(this, userList,
    android.R.layout.simple_list_item_1,
    new String[] { "users" }, new int[] { android.R.id.text1 });
  listView.setAdapter(simpleAdapter);


 }

 private HashMap<String, String> createUser(String username, String telp) {
  HashMap<String, String> userNameTelp = new HashMap<String, String>();
  userNameTelp.put(username, telp);
  return userNameTelp;
 }
}

这是 XML 文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ListUser" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp" >
</ListView>

当我单击项目时,我想打开另一个 Activity 并将 "username" 从该列表视图发送到我的 php 代码:

<?php
$user = $_POST['username'];

$con=mysql_connect("xxx","xxx","xxx");
mysql_select_db('xxx', $con);


$date = date('Y-m-d');

$query = "SELECT * from table WHERE username = '.$user.' AND timestamp like '%$date%'";
$result = mysql_query($query) or die(mysql_error());

$records = array();

while($row = mysql_fetch_assoc($result)){
    $records[]= $row;
}

mysql_close($con);
$data = "{\"users\" : ".json_encode($records)."}";
echo $data;
?>

我该怎么做?请帮助我..谢谢

您可以通过以下方式实现listItem点击

 listview.setOnItemClickListener(new OnItemClickListener(){
@Override
   public void onItemClick(AdapterView<?>adapter,View v, int position){

ItemClicked item = adapter.getItem(position);

Intent intent = new Intent(Activity.this,Activity2.class);
//based on item add info to intent
startActivity(intent);

}
});
in your adapters getItem you have to write
public ItemClicked getItem(int position){

return items.get(position);
}

在我调用 Intent 的地方你可以执行你的 AsyncTask。 :)