dongqu4443 2015-03-27 08:47
浏览 64
已采纳

如何在我的Listview中添加onItemClick,它从带有Asynctask的MYSQL中获取数据

I'm a beginner with Android Programming. I just want to ask how can i add onItemClick in My Listview with Asynctask. here is the code

 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;
 }
}

here's the XML file :

<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>

and when I click on item, i want to open another Activity and send "username" from that listview to my php code :

<?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;
?>

How can i do that? please help me.. Thanks

  • 写回答

1条回答 默认 最新

  • doumeng3345 2015-03-27 08:51
    关注

    you can achieve listItem click in following manner.

     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);
    }
    

    where I am calling Intent you can execute your AsyncTask. :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加