duannaikuang1301 2014-02-14 10:04
浏览 67

如何在ListView中检索一个项目的数据并打开另一个ListView

I am doing an android application that display list of patients in listview. When i click an item in the list another list will display which is the list prescriptions. my problem is how will i retrieve all list of prescription for that particular patient only.

First, click one of this patient in listview

enter image description here

patient table structure

enter image description here

then go to next listview for prescription

This is my prescription table structure

enter image description here

and i want to display this in listview

enter image description here

this is the relational view for fkey

enter image description here

Here is my Code for lists of Prescriptions.

public class DocListPrescription extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;
   TextView docusername;
    Button btndelete;

    String uid;
    // Creating JSON Parser object
    JSONParser2 jParser = new JSONParser2();

    ArrayList<HashMap<String, String>> patientsList;

    // url to get all products list
   // private static String url_all_patients = "http://192.168.43.6/android_connect/get_all_patients.php";
    private static String url_all_patients = "http://10.0.2.2/android_connect/get_all_prescriptions.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRESCRIPTION = "prescription";
    private static final String TAG_PRES_ID = "pres_id";
    private static final String TAG_UID = "uid";
    private static final String TAG_NAME = "pres_name";
    private static final String TAG_DATE = "date";
    private static final String TAG_DOCUSERNAME = "docusername";

    private ListView lv1;
    // products JSONArray
    JSONArray patients = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listpatient);
        //docusername = (TextView) findViewById(R.id.docusername);

            Intent i = getIntent();

        // getting product id (pid) from intent
        uid = i.getStringExtra(TAG_UID);


        // Hashmap for ListView
        patientsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView lv = getListView();


        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String pres_id = ((TextView) view.findViewById(R.id.pres_id)).getText()
                        .toString();


                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        AddPrescription.class);

                // sending id to next activity
                //in.putExtra(TAG_USERNAME,docusername.getText().toString());

                in.putExtra(TAG_PRES_ID, pres_id);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
                //startActivity(i);

            }
        });
        lv1 = (ListView) findViewById(android.R.id.list);
        registerForContextMenu(lv1);



    }
    /*
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
      if (v.getId()==R.id.list) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        menu.setHeaderTitle(Countries[info.position]);
        String[] menuItems = getResources().getStringArray(R.menu.menu);
        for (int i = 0; i<menuItems.length; i++) {
          menu.add(Menu.NONE, i, i, menuItems[i]);
        }
      }
    }
 */

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        //userFunctions.logoutUser(getApplicationContext());
        Intent intent = new Intent(this, DocMenuActivity.class);
        intent.putExtra(TAG_DOCUSERNAME,docusername.getText().toString());
        // Close all views before launching Dashboard
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //startActivity(dashboard);
        startActivity(intent);
    }
    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(DocListPrescription.this);
            pDialog.setMessage("Loading precriptions. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("uid", uid));

            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_patients, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Prescriptions: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    patients = json.getJSONArray(TAG_PRESCRIPTION);

                    // looping through All Products
                    for (int i = 0; i < patients.length(); i++) {
                        JSONObject c = patients.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PRES_ID);
                        String details = c.getString(TAG_NAME);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_PRES_ID, id);
                        map.put(TAG_NAME, details);

                        // adding HashList to ArrayList
                        patientsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            AddPrescription.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            DocListPrescription.this, patientsList,
                            R.layout.rowprescrip, new String[] { TAG_PRES_ID,
                                    TAG_NAME},
                            new int[] { R.id.pres_id, R.id.pres_name });

      /*


        */           
                    // updating listview
                    setListAdapter(adapter);
                }
            });



        }

    }

}

From this code. I passed the uid of patient from ListofPatients to this activity so that i will get the uid of that particular item(patient).

Here is my PHP to retrieve all prescriptions for that patient

<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();


// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT *FROM prescription") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["prescription"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $prescription = array();
        $prescription["pres_id"] = $row["pres_id"];
        $prescription["pres_name"] = $row["pres_name"];
       // $prescription["created_at"] = $row["created_at"];
        $prescription["date"] = $row["date"];



        // push single product into final response array
        array_push($response["prescription"], $prescription);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?>

From this code. I dont know how to retrieve that prescription using the foreign_key of patient uid. Please help. How can i do this? Thanks in advance. I really need help now.

展开全部

  • 写回答

1条回答 默认 最新

  • dongqiyang3711 2014-02-14 11:25
    关注

    Since, your requirement is just to get data of a specific patient from prescription table, use the below code.

    select * from prescription where patient_user_fkey= mysql_real_escape_string($patient_id); 
    

    If you want patient details along with it, you can use JOIN to get the data. I am still not sure this is your requirement ? if it is not, atleast let us know what should be your desired output be

    评论
    编辑
    预览

    报告相同问题?

    手机看
    程序员都在用的中文IT技术交流社区

    程序员都在用的中文IT技术交流社区

    专业的中文 IT 技术社区,与千万技术人共成长

    专业的中文 IT 技术社区,与千万技术人共成长

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    客服 返回
    顶部