选择列表视图项并按ID获取项目信息

时间:2015-02-21 11:47:34

标签: android-intent android-activity getjson listviewitem post-parameter

我想

    当用户点击其中一个时,
  • 在另一个页面中获取项目详细信息 列表视图的项目
  • 按ID获取详细信息。

如何发布项目ID的参数并获取json详细信息?

以下是我的代码:

(第一个活动)listview活动的一部分:

 private void updateList() {

    ListAdapter adapter = new SimpleAdapter(this, mCommentList,
            R.layout.single_post, new String[] { TAG_TITLE, TAG_ADDRESS,
            TAG_OPHOURS }, new int[] { R.id.title, R.id.address,
            R.id.ophours });

    setListAdapter(adapter);

    // when the user clicks a list item 
    ListView lv = getListView();
    lv.setSelector( R.drawable.listselector);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
     public void onItemClick(AdapterView<?> parent,    View view,    int position,    long id) {
            //pass id of item
         Intent r = new Intent(listview.this, Record.class);
         Bundle b = new Bundle();
         b.putString("key", TAG_ID);
         r.putExtras(b);
         startActivity(r);
     }
                              }
    );
}

(第二项活动)Record.class:

public class Record extends ListActivity

{

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//testing on Emulator:
private static final String READ_SPECIFIC_RECORD_URL = "http://xxx.xxx.xx.xxx:8888/searchdb/record.php";

//JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_ADDRESS = "address";
private static final String TAG_OPHOURS = "ophours";
private static final String TAG_CONTACT = "contact";
private static final String TAG_CONTACT2 = "contact2";
private static final String TAG_CAT = "cat";
private static final String TAG_BRAND = "brand";
private static final String TAG_COMPANY = "company";
private static final String TAG_RATINGS = "avrgrating";


//An array of all of our comments
private JSONArray mComments = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //note that use read_comments.xml instead of our single_post.xml
    setContentView(R.layout.details);

}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    //loading the comments via AsyncTask
    new LoadRecords().execute();
}

/**
 * Retrieves json data of comments
 */
/**
 * Retrieves recent post data from the server.
 */
public void updateJSONdata() {

    // Instantiate the arraylist to contain all the JSON data.
    // we are going to use a bunch of key-value pairs, referring
    // to the json element name, and the content, for example,
    // message it the tag, and "I'm awesome" as the content..

    Bundle b = getIntent().getExtras();
    String id = b.getString("key");

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("id", id));

    Log.d("request!", "starting");

    //Posting user data to script
    JSONObject json = jsonParser.makeHttpRequest(
            READ_SPECIFIC_RECORD_URL, "POST", params);

    // full json response
    Log.d("Search attempt", json.toString());


    mCommentList = new ArrayList<HashMap<String, String>>();

    //when parsing JSON stuff, we should probably
    //try to catch any exceptions:
    try {

        //I know I said we would check if "Posts were Avail." (success==1)
        //before we tried to read the individual posts, but I lied...
        //mComments will tell us how many "posts" or comments are
        //available
        mComments = json.getJSONArray(TAG_POSTS);

        // looping through all posts according to the json object returned
        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);

            //gets the content of each tag
            String title = c.getString(TAG_TITLE);
            String address = c.getString(TAG_ADDRESS);
            String ophours = c.getString(TAG_OPHOURS);
            String contact = c.getString(TAG_CONTACT);
            String contact2 = c.getString(TAG_CONTACT2);
            String cat = c.getString(TAG_CAT);
            String brand = c.getString(TAG_BRAND);
            String company = c.getString(TAG_COMPANY);
            String avrgrating = c.getString(TAG_RATINGS);


            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            map.put(TAG_TITLE, title);
            map.put(TAG_ADDRESS, address);
            map.put(TAG_OPHOURS, ophours);
            map.put(TAG_CONTACT, contact);
            map.put(TAG_CONTACT2, contact2);
            map.put(TAG_CAT, cat);
            map.put(TAG_BRAND, brand);
            map.put(TAG_COMPANY, company);
            map.put(TAG_RATINGS, avrgrating);
            // adding HashList to ArrayList
            mCommentList.add(map);

            //annndddd, our JSON data is up to date same with our array list
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
/**
 * Inserts the parsed data into our listview
 */
private void updateList() {
    // For a ListActivity we need to set the List Adapter, and in order to do
    //that, we need to create a ListAdapter.  This SimpleAdapter,
    //will utilize our updated Hashmapped ArrayList,
    //use our single_post xml template for each item in our list,
    //and place the appropriate info from the list to the
    //correct GUI id.  Order is important here.
    ListAdapter adapter = new SimpleAdapter(this, mCommentList,
            R.layout.single_record, new String[] { TAG_TITLE, TAG_ADDRESS,
            TAG_OPHOURS, TAG_CONTACT, TAG_CONTACT2, TAG_CAT, TAG_BRAND, TAG_COMPANY, TAG_RATINGS },
            new int[] { R.id.outletname, R.id.outletaddress, R.id.outletophours, R.id.outletcontact,
            R.id.outletcontact2, R.id.outletcat, R.id.outletbrand, R.id.outletcompany, R.id.ratings});

    // I shouldn't have to comment on this one:
    setListAdapter(adapter);

    // Optional: when the user clicks a list item we
    //could do something.  However, we will choose
    //to do nothing...
}

public class LoadRecords extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Record.this);
        pDialog.setMessage("Loading details...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    @Override
    protected Boolean doInBackground(Void... arg0) {
        //we will develop this method in version 2
        updateJSONdata();
        return null;

    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        pDialog.dismiss();
        //we will develop this method in version 2
        updateList();
    }
}

}

Read_specific_record_url php:

<?php

require("config.inc.php");

if (!empty($_POST)) {
$query_params = array(
            $id = $_POST['id']
                );

//initial query
$query = "SELECT * FROM `repairsvc` WHERE `id` = '".$id."'";

//execute query
try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));
}

// Finally, we can retrieve all of the found rows into an array using fetchAll 
$rows = $stmt->fetchAll();


if ($rows) {
    $response["success"] = 1;
    $response["posts"]   = array();

    foreach ($rows as $row) {
        $post             = array();
        $post["title"] = $row["title"];
        $post["address"]    = $row["address"];
        $post["ophours"]  = $row["ophours"];
        $post["contact"]  = $row["phone 1"];
        $post["contact2"]  = $row["phone 2"];
        $post["cat"]  = $row["cat"];
        $post["brand"]  = $row["brand"];
        $post["company"]  = $row["company"];
        $post["avrgrating"]  = $row["avrgrating"];


        //update our repsonse JSON data
        array_push($response["posts"], $post);
    }

    // echoing JSON response
    echo json_encode($response);


} else {
    $response["success"] = 0;
    $response["message"] = "Sorry, the record is unavailable now!";
    die(json_encode($response));
        }

} else {
?>
        <h1>Search Records with ID</h1> 
        <form name="form1" action="record.php" method="post"> 
            Enter Search:<br /> 
            <input type="text" name="id" id="id" placeholder="Enter Record ID"/> 
            <br /><br /> 
            <input type="submit" value="Search Now" name="completedsearch"  /> 
        </form> 
    <?php
}

?> 

0 个答案:

没有答案