使用文本菜单列表视图中选择传递项的ID Android的错误 [英] Android error in passing id of selected item in listview using ContextMenu

查看:221
本文介绍了使用文本菜单列表视图中选择传递项的ID Android的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表视图和长pressing将显示文本菜单更新,删除和发送prescrip。现在,当我点击更新,会去EditPatientActivity。从MySQL数据库中的所有数据填充到窗体。我的问题是,当我点击它崩溃的应用程序菜单。我不知道为什么。请帮帮我。我不知道问题出在传递UID或东西是从EditPatientActivity丢失。

edit_patient.xml

 <?XML版本=1.0编码=UTF-8&GT?;
<滚动型的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    机器人:背景=@绘制/ white_bg>    <的LinearLayout
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =FILL_PARENT
        机器人:方向=垂直
        机器人:填充=10dip>        <! - 错误信息 - >        <的TextView
            机器人:ID =@ + ID / textView1
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:文字=病人更新
            机器人:textAppearance =:/>中的Andr​​oid ATTR / textAppearanceLarge?
        <的TextView
            机器人:ID =@ + ID / register_error
            机器人:layout_width =FILL_PARENT
            机器人:layout_height =WRAP_CONTENT
            机器人:填充=10dip
            机器人:文字颜色=#e30000
            机器人:文字样式=大胆/>        <的EditText
            机器人:ID =@ + ID / FNAME
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:EMS =10
            机器人:提示=名/>        <的EditText
            机器人:ID =@ + ID / LNAME
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:EMS =10
            机器人:提示=姓/>        <的EditText
            机器人:ID =@ + ID /用户名
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_marginTop =36dp
            机器人:EMS =10
            机器人:提示=用户名/>        <的EditText
            机器人:ID =@ + ID /密码
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_marginTop =26dp
            机器人:EMS =10
            机器人:提示=密码
            安卓的inputType =textPassword/>        <的EditText
            机器人:ID =@ + ID /联系人
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_alignLeft =@ + ID / regPassword
            机器人:layout_alignRight =@ + ID / regPassword
            机器人:layout_below =@ + ID / regPassword
            机器人:EMS =10
            机器人:提示=联系人>            < requestFocus的机器人:layout_width =WRAP_CONTENT/>        < /&的EditText GT;        <的EditText
            机器人:ID =@ + ID /地址
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_alignLeft =@ + ID / editText1
            机器人:layout_alignRight =@ + ID / editText1
            机器人:layout_below =@ + ID / editText1
            机器人:EMS =10
            机器人:提示=地址/>        <微调
            机器人:ID =@ + ID /性别
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT/>        <的TextView
            机器人:ID =@ + ID / datetext
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:文字=日期
            机器人:textAppearance =机器人:ATTR / textAppearanceMedium/>        <按钮
            机器人:ID =@ + ID / pickdate
            风格=机器人:ATTR / buttonStyleSmall
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:文字=生日/>        < RelativeLayout的
            机器人:layout_width =295dp
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_weight =0.06>            <按钮
                机器人:ID =@ + ID /加
                风格=机器人:ATTR / buttonStyleSmall
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:layout_alignParentBottom =真
                机器人:layout_alignParentLeft =真
                机器人:layout_marginLeft =84dp
                机器人:文字=+/>            <按钮
                机器人:ID =@ + ID /子
                风格=机器人:ATTR / buttonStyleSmall
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:layout_alignParentBottom =真
                机器人:layout_marginRight =14dp
                机器人:layout_toLeftOf =@ + ID /号码
                机器人:文本= - />            <的TextView
                机器人:ID =@ + ID /号码
                机器人:layout_width =40dp
                机器人:layout_height =38dp
                机器人:layout_alignParentTop =真
                机器人:layout_alignRight =@ + ID /加
                机器人:layout_marginRight =18dp
                机器人:EMS =10
                机器人:提示=年龄
                机器人:textAppearance =机器人:ATTR / textAppearanceMedium/>        < / RelativeLayout的>        < ImageView的
            机器人:ID =@ + ID / imgUpdate
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_marginBottom =20dp
            机器人:layout_marginRight =28dp
            机器人:layout_weight =0.16
            机器人:SRC =@绘制/更新/>    < / LinearLayout中>< /滚动型>

EditPatientActivity

 包com.example.healthhelpv2;
//进口android.widget.DatePicker;
进口java.text.DateFormat中;
进口的java.util.ArrayList;
进口的java.util.Calendar;
进口的java.util.List;进口library.JSONParser2;
进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;//进口com.mkyong.android.R;进口android.app.Activity;
进口android.app.DatePickerDialog;
进口android.app.ProgressDialog;
进口android.content.Intent;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.widget.ArrayAdapter;
进口android.widget.Button;
进口android.widget.DatePicker;
进口android.widget.EditText;
进口android.widget.ImageView;
进口android.widget.Spinner;
进口android.widget.TextView;
//进口android.widget.RadioButton;
//进口android.widget.Spinner;
//进口android.widget.NumberPicker;
公共类EditPatientActivity扩展活动实现View.OnClickListener {    的EditText inputfname,inputlname,inputbirthday,inputcontact,inputaddress;
    的EditText txtCreatedAt,inputusername,控件inputPassword;
    TextView的inputdate,inputage;
    微调inputgender;
    ImageView的imgUpdate;
    钮子,加,pickdate;
    INT计数器= 0;
    日期格式甲酸= DateFormat.getDateInstance();
    台历挂历= Calendar.getInstance();
    串UID;
    //进度对话框
    私人ProgressDialog pDialog;    // JSON解析器类
    JSONParser2 jsonParser =新JSONParser2();    //单品链接
    私有静态最后弦乐url_patient_detials =htt​​p://10.0.2.2/android_connect/get_patient_details.php;    // URL来更新产品
    私有静态最后弦乐url_update_patient =htt​​p://10.0.2.2/android_connect/updatepatient.php;    // URL删除产品
    //私有静态最后弦乐url_delete_patient =htt​​p://10.0.2.2/android_connect/delete_patient.php;    // JSON节点名称
    私有静态最后弦乐TAG_SUCCESS =成功;
    私有静态最后弦乐TAG_PATIENT =病人;
    私有静态最后弦乐TAG_UID =UID;
    私有静态最后弦乐TAG_FNAME =FNAME;
    私有静态最后弦乐TAG_USERNAME =用户名;
    私有静态最后弦乐TAG_PASSWORD =密码;
    私有静态最后弦乐TAG_LNAME =LNAME;
    私有静态最后弦乐TAG_ADDRESS =地址;
    私有静态最后弦乐TAG_GENDER =性别;
    //私有静态最后弦乐TAG_GENDER2 =女;
    私有静态最后弦乐TAG_CONTACT =联系;
    私有静态最后弦乐TAG_AGE =年龄;
    私有静态最后弦乐TAG_BIRTHDAY =生日;
    公共无效onBack pressed(){
        super.onBack pressed();
        //userFunctions.logoutUser(getApplicationContext());
        意向意图=新意图(这一点,EditMenuActivity.class);
        startActivity(意向);
    }
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.edit_patient);        //保存按钮
        // btnsave =(按钮)findViewById(R.id.btnsave);
        // btndelete =(按钮)findViewById(R.id.btndelete);        //获取来自意图产品的详细信息
        意向I = getIntent();        //从意图获取产品ID(PID)
        UID = i.getStringExtra(TAG_UID);        //获取在后台线程完整的产品细节
        新GetProductDetails()执行();
        imgUpdate =(ImageView的)findViewById(R.id.imgUpdate);
        //保存按钮单击事件
        imgUpdate.setOnClickListener(新View.OnClickListener(){            @覆盖
            公共无效的onClick(查看为arg0){
                //启动后台任务来更新产品
                新SaveProductDetails()执行();
            }
        });        //性别
        pickdate =(按钮)findViewById(R.id.pickdate);
        pickdate.setOnClickListener(本);
        updateDate();
        // inputdate =(的TextView)findViewById(R.id.datetext);
        ArrayAdapter适配器= ArrayAdapter.createFromResource(
                  对此,R.array.gender_array,android.R.layout.simple_spinner_item);
                  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                  inputgender.setAdapter(适配器);        //年龄表
        添加=(按钮)findViewById(R.id.add);
        分=(按钮)findViewById(R.id.sub);          add.setOnClickListener(新View.OnClickListener(){                公共无效的onClick(视图v){
                反++;
                inputage.setText(+计数器);
                }
            });            sub.setOnClickListener(新View.OnClickListener(){                公共无效的onClick(视图v){
                计数器 - ;
                inputage.setText(+计数器);
                }
            });
    / * //删除按钮单击事件
        btndelete.setOnClickListener(新View.OnClickListener(){            @覆盖
            公共无效的onClick(查看为arg0){
                //在后台线程删除产品
                新DeleteProduct()执行();
            }
        });
     * /
    }    / **
     *背景异步任务以获得完整的产品细节
     * * /
    类GetProductDetails扩展的AsyncTask<字符串,字符串,字符串> {        / **
         *启动后台线程显示进度对话框之前
         * * /
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(EditPatientActivity.this);
            pDialog.setMessage(加载病人的详细信息,请稍候...);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(真);
            pDialog.show();
        }        / **
         *获取产品的详细信息在后台线程
         * * /
        保护字符串doInBackground(字符串... PARAMS){            //从后台线程更新界面
            runOnUiThread(新的Runnable(){
                公共无效的run(){
                    //检查成功标记
                    诠释成功;
                    尝试{
                        //大厦参数
                        清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
                        params.add(新BasicNameValuePair(UID,UID));                        //通过HTTP请求获得产品的详细信息
                        //注意产品的详细信息URL会使用GET请求
                        JSONObject的JSON = jsonParser.makeHtt prequest(
                                url_patient_detials,GET,则params);                        //检查你的日志,JSON响应
                        Log.d(单个患者详细信息,json.toString());                        // JSON的成功标签
                        成功= json.getInt(TAG_SUCCESS);
                        如果(成功== 1){
                            //成功接收产品的详细信息
                            JSONArray productObj = JSON
                                    .getJSONArray(TAG_PATIENT); // JSON数组                            //从JSON数组的第一个产品对象
                            的JSONObject产物= productObj.getJSONObject(0);                            //与本产品的PID发现
                            //编辑文本
                            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 =(微调)findViewById(R.id.gender);
                            inputage =(的TextView)findViewById(R.id.number);
                            // rdmale =(单选)findViewById(R.id.rdmale);
                            // rdfemale =(单选)findViewById(R.id.rdfemale);
                            //在显示的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));
                            如果(product.getString(TAG_GENDER).equals(男))
                                 inputgender.setSelection(0); //如果男性为0的位置
                            其他
                                 inputgender.setSelection(1); //如果女性在1位
                            inputage.setText(product.getString(TAG_AGE));
                            inputdate.setText(product.getString(TAG_BIRTHDAY));
                        }其他{
                            //产品具有pid未找到
                        }
                    }赶上(JSONException E){
                        e.printStackTrace();
                    }
                }
            });            返回null;
        }
        / **
         *在完成后台任务之后辞退进度对话框
         * ** /
        保护无效onPostExecute(字符串FILE_URL){
            //关闭该对话框一旦得了所有细节
            pDialog.dismiss();
        }
    }    / **
     *背景异步任务保存产品详细信息
     * * /
    类SaveProductDetails扩展的AsyncTask<字符串,字符串,字符串> {        / **
         *启动后台线程显示进度对话框之前
         * * /
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(EditPatientActivity.this);
            pDialog.setMessage(保存病人......);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(真);
            pDialog.show();
        }        / **
         *节能产品
         * * /
        保护字符串doInBackground(字符串参数... args){            //获得从EditTexts更新数据
            字符串username = inputusername.getText()的toString()。
            。字符串密码= inputpassword.getText()的toString();
            。字符串FNAME = inputfname.getText()的toString();
            。字符串LNAME = inputlname.getText()的toString();
            弦接触= inputcontact.getText()的toString()。
            串年龄= inputage.getText()的toString()。
            。字符串地址= inputaddress.getText()的toString();
            //字符串生日= inputbirthday.getText()的toString();
            。字符串性别= inputgender.getSelectedItem()的toString();
            。字符串BDAY = inputdate.getText()的toString();            //大厦参数
            清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
            //params.add(new BasicNameValuePair(TAG_PID,PID));
            params.add(新BasicNameValuePair(TAG_USERNAME,用户名));
            params.add(新BasicNameValuePair(TAG_PASSWORD,密码));
            params.add(新BasicNameValuePair(TAG_FNAME,FNAME));
            params.add(新BasicNameValuePair(TAG_LNAME,LNAME));
            params.add(新BasicNameValuePair(TAG_ADDRESS,地址));
            params.add(新BasicNameValuePair(TAG_BIRTHDAY,BDAY));
            params.add(新BasicNameValuePair(TAG_AGE,年龄));
            params.add(新BasicNameValuePair(TAG_GENDER,性别));
            params.add(新BasicNameValuePair(TAG_CONTACT,联系));            //通过发送HTTP请求修改的数据
            //注意,更新的产品网址接受POST方法
            JSONObject的JSON = jsonParser.makeHtt prequest(url_update_patient,
                    POST,则params);            //检查JSON的成功标签
            尝试{
                INT成功= json.getInt(TAG_SUCCESS);                如果(成功== 1){
                    //成功更新
                    意向I = getIntent();
                    //发送结果code 100,通知有关产品更新
                    的setResult(100,i)的;
                    完();
                }其他{
                    //无法更新产品
                }
            }赶上(JSONException E){
                e.printStackTrace();
            }            返回null;
        }
        / **
         *在完成后台任务之后辞退进度对话框
         * ** /
        保护无效onPostExecute(字符串FILE_URL){
            //关闭该对话框一旦产品uupdated
            pDialog.dismiss();
        }
    }    / ******************* ****************
     *背景异步任务删​​除产品
     * * /
    / *类DeleteProduct扩展的AsyncTask<字符串,字符串,字符串> {        / **
         *启动后台线程显示进度对话框之前
         * * /
    / *
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(EditPatientActivity.this);
            pDialog.setMessage(删除耐心等待...);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(真);
            pDialog.show();
        }        / **
         *删除产品
         * * /
    / *受保护的字符串doInBackground(字符串参数... args){            //检查成功标记
            诠释成功;
            尝试{
                //大厦参数
                清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
                params.add(新BasicNameValuePair(UID,UID));                //通过HTTP请求获得产品的详细信息
                JSONObject的JSON = jsonParser.makeHtt prequest(
                        url_delete_patient,POST,则params);                //检查你的日志,JSON响应
                Log.d(删除病人,json.toString());                // JSON的成功标签
                成功= json.getInt(TAG_SUCCESS);
                如果(成功== 1){
                    //产品成功删除
                    //通过发送code 100通知previous活动
                    意向I = getIntent();
                    //发送结果code 100,通知有关产品缺失
                    的setResult(100,i)的;
                    完();
                }
            }赶上(JSONException E){
                e.printStackTrace();
            }            返回null;
        }        / **
         *在完成后台任务之后辞退进度对话框
         * ** /
        保护无效onPostExecute(字符串FILE_URL){
            //关闭该对话框一旦产品被删除
            pDialog.dismiss();        }
     公共无效updateDate(){
         inputdate.setText(formate.format(calendar.getTime()));
     }
     //的setdate
     公共无效的setDate(){         新DatePickerDialog(EditPatientActivity.this,d,calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
     }
    //日期表
        DatePickerDialog.OnDateSetListener D =新DatePickerDialog.OnDateSetListener(){            @覆盖
            公共无效onDateSet(查看的DatePicker,年整型,诠释monthOfYear,诠释请将dayOfMonth){                calendar.set(Calendar.YEAR,年);
                calendar.set(的Calendar.MONTH,monthOfYear);
                calendar.set(Calendar.DAY_OF_MONTH,请将dayOfMonth);
                updateDate();
            }
        };        @覆盖
        公共无效的onClick(视图v){
            的setDate();
        }
}

的logcat

  15 02-08:33:06.042:E / AndroidRuntime(276):致命异常:主要
02-08 15:33:06.042:E / AndroidRuntime(276):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.healthhelpv2 / com.example.healthhelpv2.EditPatientActivity}:显示java.lang.NullPointerException
02-08 15:33:06.042:E / AndroidRuntime(276):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-08 15:33:06.042:E / AndroidRuntime(276):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-08 15:33:06.042:E / AndroidRuntime(276):在android.app.ActivityThread.access $ 2300(ActivityThread.java:125)
02-08 15:33:06.042:E / AndroidRuntime(276):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:2033)
02-08 15:33:06.042:E / AndroidRuntime(276):在android.os.Handler.dispatchMessage(Handler.java:99)
02-08 15:33:06.042:E / AndroidRuntime(276):在android.os.Looper.loop(Looper.java:123)
02-08 15:33:06.042:E / AndroidRuntime(276):在android.app.ActivityThread.main(ActivityThread.java:4627)
02-08 15:33:06.042:E / AndroidRuntime(276):在java.lang.reflect.Method.invokeNative(本机方法)
02-08 15:33:06.042:E / AndroidRuntime(276):在java.lang.reflect.Method.invoke(Method.java:521)
02-08 15:33:06.042:E / AndroidRuntime(276):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:868)
02-08 15:33:06.042:E / AndroidRuntime(276):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-08 15:33:06.042:E / AndroidRuntime(276):在dalvik.system.NativeStart.main(本机方法)
02-08 15:33:06.042:E / AndroidRuntime(276):致:显示java.lang.NullPointerException
02-08 15:33:06.042:E / AndroidRuntime(276):在com.example.healthhelpv2.EditPatientActivity.onCreate(EditPatientActivity.java:125)
02-08 15:33:06.042:E / AndroidRuntime(276):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-08 15:33:06.042:E / AndroidRuntime(276):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-08 15:33:06.042:E / AndroidRuntime(276):11 ...更多


解决方案

从您的意见线105 imgUpdate.setOnClickListener(新View.OnClickListener(){说明 imgUpdate 为null。

所以更改此

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

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

因为你有

 < ImageView的
        机器人:ID =@ + ID / imgUpdate// id是imgUpdate

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

解决方案

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 

这篇关于使用文本菜单列表视图中选择传递项的ID Android的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆