Question

I have here listofpatients in a listview. This items are populated from MySql database. Now when i long press the item it will show contextmenu with edit and delete. In edit I want to pass it in EditPatient activity and those values will be passed to Edit page by getting the id(id from database) of an item. For example i need to edit PatientJay with the UID = 34. That UID should be passed to the editpatient activity. I don't know how to this.

Here's the code

ListPatient

public class ListPatientActivity extends ListActivity {

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


    // 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_patients.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PATIENTS = "patients";
    private static final String TAG_UID = "uid";
    private static final String TAG_USERNAME = "username";
    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);

        //imgedit = (ImageButton) findViewById(R.id.imgedit);

        //Bundle i = getIntent().getExtras();
        //docusername.setText(i.getString(TAG_DOCUSERNAME));

        // 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 uid = ((TextView) view.findViewById(R.id.uid)).getText()
                        .toString();


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

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

                in.putExtra(TAG_UID, uid);

                // 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(ListPatientActivity.this);
            pDialog.setMessage("Loading patients. 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>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_patients, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Patients: ", 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_PATIENTS);

                    // 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_UID);
                        String name = c.getString(TAG_USERNAME);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_UID, id);
                        map.put(TAG_USERNAME, name);

                        // adding HashList to ArrayList
                        patientsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            RegisterActivity.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(
                            ListPatientActivity.this, patientsList,
                            R.layout.all_patient, new String[] { TAG_UID,
                                    TAG_USERNAME},
                            new int[] { R.id.uid, R.id.username });

      /*


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



        }

    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {

        super.onCreateContextMenu(menu, v, menuInfo);

        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;

        menu.setHeaderTitle("title");
        //menu.add(0, 0, 0, "Turn alarm on");
        menu.add(0, 1, 0, "Edit");
        menu.setHeaderIcon(R.drawable.edit);
        menu.add(0, 2, 0, "Delete"); 
        }


    @Override
    public boolean onContextItemSelected(MenuItem item) {

    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    int index = info.position;

    if (item.getTitle() == "Edit") {
    Intent intent = new Intent(getApplicationContext(), EditPatientActivity.class);
    intent.putExtra(TAG_UID, patientsList.get(index).toString());
    startActivity(intent);
    return true;

    }return super.onContextItemSelected(item); 
    }
}

EditPatientActivity

public class EditPatientActivity extends Activity implements View.OnClickListener{

    EditText inputfname, inputlname, inputbirthday, inputcontact, inputaddress;
    EditText txtCreatedAt, inputusername, inputpassword;
    TextView inputdate, inputage;
    Spinner inputgender;
    ImageView imgUpdate;
    Button sub, add, pickdate;
    int counter = 0;
    DateFormat formate = DateFormat.getDateInstance();
    Calendar calendar = Calendar.getInstance();
    String uid;


    // Progress Dialog
    private ProgressDialog pDialog;

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

    // single product url
    private static final String url_patient_detials = "http://10.0.2.2/android_connect/get_patient_details.php";

    // url to update product
    private static final String url_update_patient = "http://10.0.2.2/android_connect/updatepatient.php";

    // url to delete product
    //private static final String url_delete_patient = "http://10.0.2.2/android_connect/delete_patient.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PATIENT = "patient";
    private static final String TAG_UID = "uid";
    private static final String TAG_FNAME = "fname";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_PASSWORD = "password";
    private static final String TAG_LNAME = "lname";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    //private static final String TAG_GENDER2 = "female";
    private static final String TAG_CONTACT = "contact";
    private static final String TAG_AGE = "age";
    private static final String TAG_BIRTHDAY = "birthday";


    public void onBackPressed() {
        super.onBackPressed();
        //userFunctions.logoutUser(getApplicationContext());
        Intent intent = new Intent(this, EditMenuActivity.class);
        startActivity(intent);
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_patient);

        // save button
        //btnsave = (Button) findViewById(R.id.btnsave);
        //btndelete = (Button) findViewById(R.id.btndelete);

        // getting product details from intent
        Intent i = getIntent();

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

        // Getting complete product details in background thread
        new GetProductDetails().execute();
        imgUpdate = (ImageView) findViewById(R.id.imgUpdate);
        // save button click event
        imgUpdate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // starting background task to update product
                new SaveProductDetails().execute();
            }
        });

        inputgender = (Spinner) findViewById(R.id.gender);
        inputage = (TextView) findViewById(R.id.number);

        inputdate = (TextView) findViewById(R.id.datetext);//bday
        pickdate = (Button) findViewById(R.id.pickdate);
        pickdate.setOnClickListener(this);
        updateDate();
        //inputdate = (TextView) findViewById(R.id.datetext);

        //gender    
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
                  this, R.array.gender_array, android.R.layout.simple_spinner_item);
                  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                  inputgender.setAdapter(adapter);

        //age form
        add = (Button) findViewById(R.id.add);
        sub = (Button) findViewById(R.id.sub);

          add.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                counter++;
                inputage.setText( "" + counter);
                }
            });

            sub.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                counter--;
                inputage.setText( "" + counter);
                }
            });
    /*  // Delete button click event
        btndelete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // deleting product in background thread
                new DeleteProduct().execute();
            }
        });
     */
    }

    /**
     * Background Async Task to Get complete product details
     * */
    class GetProductDetails extends AsyncTask<String, String, String> {

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

        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("uid", uid));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                url_patient_detials, "GET", params);

                        // check your log for json response
                        Log.d("Single Patient Details", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json
                                    .getJSONArray(TAG_PATIENT); // JSON Array

                            // get first product object from JSON Array
                            JSONObject product = productObj.getJSONObject(0);

                            // product with this pid found
                            // Edit Text
                            inputusername= (EditText) findViewById(R.id.username);
                            inputpassword = (EditText) findViewById(R.id.password);
                            inputfname= (EditText) findViewById(R.id.fname);
                            inputlname = (EditText) findViewById(R.id.lname);
                            inputcontact = (EditText) findViewById(R.id.contacts);
                            inputaddress = (EditText) findViewById(R.id.address);
                            //rdmale = (RadioButton) findViewById(R.id.rdmale);
                            //rdfemale = (RadioButton) findViewById(R.id.rdfemale);




                            // display product data in EditText
                            inputusername.setText(product.getString(TAG_USERNAME));
                            inputpassword.setText(product.getString(TAG_PASSWORD));
                            inputfname.setText(product.getString(TAG_FNAME));
                            inputlname.setText(product.getString(TAG_LNAME));
                            inputcontact.setText(product.getString(TAG_CONTACT));
                            inputaddress.setText(product.getString(TAG_ADDRESS));
                            if(product.getString(TAG_GENDER).equals("male"))    
                                 inputgender.setSelection(0);//if male is at 0 position
                            else
                                 inputgender.setSelection(1);//if female is at 1 position
                            inputage.setText(product.getString(TAG_AGE));
                            inputdate.setText(product.getString(TAG_BIRTHDAY));
                        }else{
                            // product with pid not found
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }


        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }

    /**
     * Background Async Task to  Save product Details
     * */
    class SaveProductDetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditPatientActivity.this);
            pDialog.setMessage("Saving patient ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Saving product
         * */
        protected String doInBackground(String... args) {

            // getting updated data from EditTexts
            String username = inputusername.getText().toString();
            String password = inputpassword.getText().toString();
            String fname = inputfname.getText().toString();
            String lname = inputlname.getText().toString();
            String contact = inputcontact.getText().toString();
            String age = inputage.getText().toString();
            String address = inputaddress.getText().toString();
            //String birthday = inputbirthday.getText().toString();
            String gender = inputgender.getSelectedItem().toString();
            String bday = inputdate.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            //params.add(new BasicNameValuePair(TAG_PID, pid));
            params.add(new BasicNameValuePair(TAG_USERNAME, username));
            params.add(new BasicNameValuePair(TAG_PASSWORD, password));
            params.add(new BasicNameValuePair(TAG_FNAME, fname));
            params.add(new BasicNameValuePair(TAG_LNAME, lname));
            params.add(new BasicNameValuePair(TAG_ADDRESS, address));
            params.add(new BasicNameValuePair(TAG_BIRTHDAY, bday));
            params.add(new BasicNameValuePair(TAG_AGE, age));
            params.add(new BasicNameValuePair(TAG_GENDER, gender));
            params.add(new BasicNameValuePair(TAG_CONTACT, contact));



            // sending modified data through http request
            // Notice that update product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_update_patient,
                    "POST", params);

            // check json success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully updated
                    Intent i = getIntent();
                    // send result code 100 to notify about product update
                    setResult(100, i);
                    finish();
                } else {
                    // failed to update product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }


        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product uupdated
            pDialog.dismiss();
        }
    }

    /*****************************************************************
     * Background Async Task to Delete Product
     * */
    /*class DeleteProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
    /*
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditPatientActivity.this);
            pDialog.setMessage("Deleting Patient...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Deleting product
         * */
    /*  protected String doInBackground(String... args) {

            // Check for success tag
            int success;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("uid", uid));

                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                        url_delete_patient, "POST", params);

                // check your log for json response
                Log.d("Delete Patient", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // product successfully deleted
                    // notify previous activity by sending code 100
                    Intent i = getIntent();
                    // send result code 100 to notify about product deletion
                    setResult(100, i);
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();

        }




     public void updateDate(){
         inputdate.setText(formate.format(calendar.getTime()));
     }
     //setdate
     public void setDate(){

         new DatePickerDialog(EditPatientActivity.this,d,calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
     }
    //date form
        DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener(){

            @Override
            public void onDateSet(DatePicker View, int year, int monthOfYear, int dayOfMonth){

                calendar.set(Calendar.YEAR,year);
                calendar.set(Calendar.MONTH,monthOfYear);
                calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
                updateDate();


            }


        };

        @Override
        public void onClick(View v){
            setDate();
        }
}
Was it helpful?

Solution

If You have Context Menu like below:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;

    menu.setHeaderTitle("title");
    menu.setHeaderIcon(R.drawable.alarm1_icon);
    menu.add(0, 0, 0, "test");
}

Then you can get id or particular data from HashMap or Array like

  @Override
public boolean onContextItemSelected(MenuItem item) {

       AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        int index = info.position;

    if (item.getTitle() == "test") {
        Toast.makeText(getApplicationContext(), patientsList.get(index).tostring(),
                Toast.LENGTH_LONG).show();
        return true;
    }
          return false;
}

You can get Particular index from your Context Menu like below:

 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
 int index = info.position;

Using this index you can get data from ArrayList or HashMap at particular position.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top