Android error in passing id of selected item in listview using ContextMenu

为君一笑 提交于 2019-12-13 06:27:44

问题


I have a listview and long pressing will show contextmenu update, delete and send prescrip. Now when i click update it will go to the EditPatientActivity. Populate all data from MySql database to the form. My Problem is when i click the update menu it crashed the application. I don't know why. Please help me. I don't know if the problem is in passing the uid or something is missing from the EditPatientActivity.

edit_patient.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/white_bg" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="10dip" >

        <!-- Error message -->

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Patient Update"
            android:textAppearance="?android:attr/textAppearanceLarge" />


        <TextView
            android:id="@+id/register_error"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:textColor="#e30000"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/fname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="First Name" />

        <EditText
            android:id="@+id/lname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Last Name" />

        <EditText
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="36dp"
            android:ems="10"
            android:hint="Username" />

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="26dp"
            android:ems="10"
            android:hint="Password"
            android:inputType="textPassword" />

        <EditText
            android:id="@+id/contacts"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/regPassword"
            android:layout_alignRight="@+id/regPassword"
            android:layout_below="@+id/regPassword"
            android:ems="10"
            android:hint="Contacts" >

            <requestFocus android:layout_width="wrap_content" />

        </EditText>

        <EditText
            android:id="@+id/address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editText1"
            android:layout_alignRight="@+id/editText1"
            android:layout_below="@+id/editText1"
            android:ems="10"
            android:hint="Address" />

        <Spinner
            android:id="@+id/gender"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/datetext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Date"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Button
            android:id="@+id/pickdate"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Birthday" />

        <RelativeLayout
            android:layout_width="295dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.06" >

            <Button
                android:id="@+id/add"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="84dp"
                android:text="+" />

            <Button
                android:id="@+id/sub"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginRight="14dp"
                android:layout_toLeftOf="@+id/number"
                android:text="-" />

            <TextView
                android:id="@+id/number"
                android:layout_width="40dp"
                android:layout_height="38dp"
                android:layout_alignParentTop="true"
                android:layout_alignRight="@+id/add"
                android:layout_marginRight="18dp"
                android:ems="10"
                android:hint="age"
                android:textAppearance="?android:attr/textAppearanceMedium" />

        </RelativeLayout>

        <ImageView
            android:id="@+id/imgUpdate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:layout_marginRight="28dp"
            android:layout_weight="0.16"
            android:src="@drawable/update" />

    </LinearLayout>

</ScrollView>

EditPatientActivity

package com.example.healthhelpv2;
//import android.widget.DatePicker;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import library.JSONParser2;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//import com.mkyong.android.R;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
//import android.widget.RadioButton;
//import android.widget.Spinner;
//import android.widget.NumberPicker;
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();
            }
        });

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


        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);
                            inputdate = (TextView) findViewById(R.id.datetext);//bday
                            inputgender = (Spinner) findViewById(R.id.gender);
                            inputage = (TextView) findViewById(R.id.number);
                            //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();
        }
}

LOGCAT

02-08 15:33:06.042: E/AndroidRuntime(276): FATAL EXCEPTION: main
02-08 15:33:06.042: E/AndroidRuntime(276): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.healthhelpv2/com.example.healthhelpv2.EditPatientActivity}: java.lang.NullPointerException
02-08 15:33:06.042: E/AndroidRuntime(276):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-08 15:33:06.042: E/AndroidRuntime(276):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-08 15:33:06.042: E/AndroidRuntime(276):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-08 15:33:06.042: E/AndroidRuntime(276):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-08 15:33:06.042: E/AndroidRuntime(276):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-08 15:33:06.042: E/AndroidRuntime(276):  at android.os.Looper.loop(Looper.java:123)
02-08 15:33:06.042: E/AndroidRuntime(276):  at android.app.ActivityThread.main(ActivityThread.java:4627)
02-08 15:33:06.042: E/AndroidRuntime(276):  at java.lang.reflect.Method.invokeNative(Native Method)
02-08 15:33:06.042: E/AndroidRuntime(276):  at java.lang.reflect.Method.invoke(Method.java:521)
02-08 15:33:06.042: E/AndroidRuntime(276):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-08 15:33:06.042: E/AndroidRuntime(276):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-08 15:33:06.042: E/AndroidRuntime(276):  at dalvik.system.NativeStart.main(Native Method)
02-08 15:33:06.042: E/AndroidRuntime(276): Caused by: java.lang.NullPointerException
02-08 15:33:06.042: E/AndroidRuntime(276):  at com.example.healthhelpv2.EditPatientActivity.onCreate(EditPatientActivity.java:125)
02-08 15:33:06.042: E/AndroidRuntime(276):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-08 15:33:06.042: E/AndroidRuntime(276):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-08 15:33:06.042: E/AndroidRuntime(276):  ... 11 more

回答1:


From your comments line 105 is imgUpdate.setOnClickListener(new View.OnClickListener() { indicating imgUpdate is null.

So Change this

imgUpdate = (ImageView) findViewById(R.id.imgReg);

to

imgUpdate = (ImageView) findViewById(R.id.imgUpdate);

coz you have

<ImageView
        android:id="@+id/imgUpdate"  // id is imgUpdate 


来源:https://stackoverflow.com/questions/21642138/android-error-in-passing-id-of-selected-item-in-listview-using-contextmenu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!