Hot questions for Using Android EditText in nullpointerexception

Top Java Programmings / Android EditText / nullpointerexception

Question:

I tried a number of things but my Application keeps Crashing.

I tried debugging it is returned this error when I run the application.

java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

package com.zybooks.pigdice;


import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    final Context context = this;
    //private EditText playerName;
    private String name;
    private int target_score_display;
    //public TextView player_name;
    private  EditText targetScore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //player_name = findViewById(R.id.player_name);
        targetScore = dialog.findViewById(R.id.enter_target_score);
        //playerName = findViewById(R.id.enter_player_name);



        Button start_game = findViewById(R.id.start_game);
        start_game.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // custom dialog
                final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.dialogbox);
                dialog.setTitle("Title...");
                Button dialogButton = dialog.findViewById(R.id.start_game_dialog);
                // if button is clicked, close the custom dialog
                dialogButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        try{
                            String value = targetScore.getText().toString();
                            target_score_display = Integer.parseInt(targetScore.getText().toString());
                            Intent intent = new Intent(getApplicationContext(),Gameplay.class);
                            intent.putExtra("TARGET_SCORE",target_score_display);
                            Bundle bundle = new Bundle();
                            bundle.putString("TARGET_SCORE",value);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        } catch(NumberFormatException nfe) {
                            System.out.println("Could not parse " + nfe);
                        }
                    }
                });
                dialog.show();
            }
        });
    }
}

Trying to pass input taken in the dialog box to the next Activity. Have been struggling with this for over 3 hours.


Answer:

You can only call dialog.findViewById after the dialog is created (inside the onClick). It has no content when the Activity is created, so you can't find its views. For example, dialogButton is gotten correctly

So when you try to get the text from the non existing view, it will throw the exception

Question:

I want to get a double value from a EditText where you can only instert numberDecimal and numberSigned.

I thought:

EditText editText1 = (EditText)findViewById(R.id.edittext1)

double double1 = Double.parseDouble(editText1.getText().toString());

But logcat says that this double = "" and the app crashes

Logcat:

08-29 20:52:24.148  22688-22688/test.com.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity  
ComponentInfo{test.com.app/test.com.app.Main}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
        at android.app.ActivityThread.access$700(ActivityThread.java:159)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:5419)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at java.lang.StringToReal.parseDouble(StringToReal.java:244)
        at java.lang.Double.parseDouble(Double.java:295)
        at test.com.app.Graph.yWerte(Graph.java:188)
        at test.com.app.Graph.getDataFromReceiver(Graph.java:184)
        at test.com.app.Main.onCreate(Main.java:30)
        at android.app.Activity.performCreate(Activity.java:5372)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)       
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
        at android.app.ActivityThread.access$700(ActivityThread.java:159)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:5419)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
        at dalvik.system.NativeStart.main(Native Method)

Answer:

editText1.getText() is null. Try this:

CharSequence cs = editText1.getText();
double double1 = cs == null ? -1.0 : Double.parseDouble(cs.toString());

If you want to avoid also the NumberFormatException in case you typed a non-parsable double, you can write:

double double1 = -1.0; // invalid!
try {
    double1 = Double.parseDouble(editText1.getText().toString());
} catch(RuntimeException ignored) {
    // NPE or parsing failed, double1 == -1.0
}

Catching (and also ignoring) RuntimeExceptions is not good practice in general, but it is ok in this example due to the particular API.

Edit: updated after the stack trace has been posted

Edit 2: updated to correct also the parsing problem

Question:

Currently i am having a

java.lang.NullPointerException error for android.widget.EditText.addTextChangedListener

What i am trying to do is letting the user, key in a text/string into a "EditText" field. Once the code detect a change in the "EditText" field, it will get text/string from the "EditText" field and automatic display it out into a field name "tv".

i have search online for a solution but none work for me

below is what i have tried

what i found so far online suggested putting a final in front of the EditText which does not work for me

 final EditText filename1 = (EditText)findViewById(container.findViewById(R.id.editText1);

Below is the code which the LogCat feedback the error

  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
                    EditText filename1 = (EditText) container.findViewById(R.id.editText1);

                    filename1.addTextChangedListener(new TextWatcher(){
                    public void afterTextChanged(Editable s){

                    }
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }
                    public void onTextChanged(CharSequence s, int start, int count, int after) {

                        SeeThroughTextView tv = new SeeThroughTextView(getActivity());                      
                        tv.setLayoutParams(new FrameLayout.LayoutParams(1000, 1000));
                        tv.setText(s);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 60);
                        tv.setBackgroundResource(R.drawable.view_bg);                       
                    }
                });     
                return filename1;       
         }
  }

Full Java Code:

public class MainActivity extends ActionBarActivity
{

    int counter;

    Button button1, button2, button3, button4;
    ImageView image;
    EditText filename1, filename2;
    FrameLayout digit;

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Fabric.with(this, new Crashlytics());

        setContentView(R.layout.activity_main);


        button1 = (Button) findViewById(R.id.button1);      
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        button4 = (Button) findViewById(R.id.button4);

        image = (ImageView) findViewById(R.id.imageView1);
        filename1 = (EditText) findViewById(R.id.editText1);
        filename2 = (EditText) findViewById(R.id.editText2);




        NumberPicker np1 = (NumberPicker) findViewById(R.id.np1);
        NumberPicker np2 = (NumberPicker) findViewById(R.id.np2);
        np1.setMaxValue(9);
        np1.setMinValue(0);
        np1.setWrapSelectorWheel(true);
        np1.setOnValueChangedListener( new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {

            }
        });

        np2.setMaxValue(9);
        np2.setMinValue(0);
        np2.setWrapSelectorWheel(true);
        np2.setOnValueChangedListener( new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {

            }
        });


        if (savedInstanceState == null)
        {

            getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
        }
    }


    public static class PlaceholderFragment extends Fragment
    {


        public PlaceholderFragment()
        {
        }




        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {

                    View layout = inflater.inflate(R.layout.activity_main, container, false);
                    EditText filename1 = (EditText)layout.findViewById(R.id.editText1);

                    filename1.addTextChangedListener(new TextWatcher(){
                    public void afterTextChanged(Editable s){

                    }
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }
                    public void onTextChanged(CharSequence s, int start, int count, int after) {



                        SeeThroughTextView tv = new SeeThroughTextView(getActivity());
                        tv.setLayoutParams(new FrameLayout.LayoutParams(1000, 1000));
                        tv.setText(s);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 60);
                        tv.setBackgroundResource(R.drawable.view_bg);


                    }
                });

                return layout;
        }
    }

    final static class SeeThroughTextView extends TextView
    {
        Bitmap mMaskBitmap;
        Canvas mMaskCanvas;
        Paint mPaint;

        Drawable mBackground;
        Bitmap mBackgroundBitmap;
        Canvas mBackgroundCanvas;
        private boolean mSetBoundsOnSizeAvailable = false;

        public SeeThroughTextView(Context context)
        {
            super(context);

            mPaint = new Paint();
            mPaint.setXfermode(new PorterDuffXfermode(Mode.DST_OUT));
            super.setTextColor(Color.BLACK);
            super.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }

        @Override
        @Deprecated
        public void setBackgroundDrawable(Drawable bg)
        {
            mBackground = bg;
            int w = bg.getIntrinsicWidth();
            int h = bg.getIntrinsicHeight();


            if (w == -1 || h == -1)
            {
                w = getWidth();
                h = getHeight();
            }


            if (w == 0 || h == 0)
            {
                mSetBoundsOnSizeAvailable = true;
                return;
            }

            mBackground.setBounds(100, 100, w, h);
            invalidate();
        }

        @Override
        public void setBackgroundColor(int color)
        {
            setBackgroundDrawable(new ColorDrawable(color));
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh)
        {
            super.onSizeChanged(w, h, oldw, oldh);
            mBackgroundBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            mBackgroundCanvas = new Canvas(mBackgroundBitmap);
            mMaskBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            mMaskCanvas = new Canvas(mMaskBitmap);

            if (mSetBoundsOnSizeAvailable)
            {

                mBackground.setBounds(0, 0, w, h);
                mSetBoundsOnSizeAvailable = false;
            }
        }

        @Override
        protected void onDraw(Canvas canvas)
        {

            mBackground.draw(mBackgroundCanvas);
            mMaskCanvas.drawColor(Color.BLACK, PorterDuff.Mode.CLEAR);
            super.onDraw(mMaskCanvas);
            mBackgroundCanvas.drawBitmap(mMaskBitmap,100, 100, mPaint);
            canvas.drawBitmap(mBackgroundBitmap, 0.f, 0.f, null);
        }
    }
}

Full XML File:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout

        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:orientation="vertical" >

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="400dp"
            android:layout_toLeftOf="@+id/scrollView1"
            android:background="@drawable/activity_bg"
            app:context="com.example.crossover.MainActivity"
            app:ignore="MergeRootFrame" >

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="28dp" />
        </FrameLayout>

        <ScrollView
            android:id="@+id/scrollView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_gravity="right" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="end"
                android:orientation="vertical" >

                <Button
                    android:id="@+id/button1"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_margin="10dp"
                    android:text="Button" />

                <Button
                    android:id="@+id/button2"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_margin="10dp"
                    android:text="Button" />

                <Button
                    android:id="@+id/button3"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_margin="10dp"
                    android:text="Button" />

                <Button
                    android:id="@+id/button4"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_margin="10dp"
                    android:text="Button" />

                <Button
                    android:id="@+id/button5"
                    style="?android:attr/buttonStyleSmall"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_margin="10dp"
                    android:text="Button" />

            </LinearLayout>
        </ScrollView>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <NumberPicker
            android:id="@+id/np1"
            android:layout_width="40dp"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/np2"
            android:descendantFocusability="blocksDescendants"
            android:width="50dip" />

        <NumberPicker
            android:id="@+id/np2"
            android:layout_width="40dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/button6"
            android:descendantFocusability="blocksDescendants"
            android:width="50dip" />

        <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="22dp"
            android:layout_toLeftOf="@+id/np1"
            android:ems="10"
            android:maxLength="9"
            android:singleLine="true" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/editText1"
            android:layout_toLeftOf="@+id/np1"
            android:ems="10"
            android:maxLength="3"
            android:singleLine="true" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/button6"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_margin="10dp"
            android:text="Button" />

    </RelativeLayout>

</LinearLayout>

Answer:

Inflate your xml layout inside your onCreateView(...) method and get the reference of your id's.

View view=inflater.inflate(R.layout.yourlayout, container,false);
EditText filename1 = (EditText) view.findViewById(R.id.editText1);

Question:

I want to calculate the average of grades, now I have the basics and the layout. When the EditText is left open it throws a NullPointerException, I know what it is but not how I can check/handle it with my code. Can someone explain me how to do this?

Any tips etc. are welcome!

final TextView averageView = findViewById(R.id.averageView); 
final String averageText = getString(R.string.average); 
final Button calculateButton = findViewById(R.id.calculateAverageButton); 
final Button addGradeButton = findViewById(R.id.addGradeButton)

calaculateButton.setOnClickListener(new View.onClickListener() { 
    @SupressLint("SetTextI18n")                                                     
    public void onClick(View v) { 

        double grade[]  = {Double.parseDouble(((EditText) findViewById(R.id.grade1)).getText().toString()); 

        double weight[] = {Double.parseDouble(((EditText) findViewById(R.id.weight1)).getText().toString()); 

        double weightTotal = weight[0]; double sum = grade[0] * weight[0] 

        double average = sum / weightTotal 

        @SuppressLint("DefaultLocale") String averageResult = String.format(%.2f, average);

        averageView.setText(averageText + " " + averageResult);

Answer:

So you have to be careful calling "toString()" on a potential null object.

Especially if you plan to cast it to a double.

Note* Your code also creates an array of doubles from a single entry in the EditText so additional checking of the text format before casting it should be done as well to ensure it is a double. You can take the lazy way and wrap it in a try/catch to tell them it isn't formatted properly if you would like.

Handling Number format exceptions means you need to confirm that it is a double before you use it. You can use a nice utility or you can write a simple helper method. Guava has a helper method, Apache has helper methods or you can write a regex pattern matcher like here. The nice thing about regex is that you aren't relying on a try/catch to identify an issue.

How to check that a string is parseable to a double?

But for sake of thoroughness you could do something like:

private boolean isDouble(String value) {
    try {
        Double.parseDouble(value);
        return true;
    } catch (Exception ex) {
        return false;
    }
}

You have a few options for handling your null.

1) Check for null in a "if / else" statement.

double grade[];
if (myText.getText() != null && isDouble(myText.getText().toString()) {
    grade = {Double.parseDouble(myText.getText().toString())}
} else {
    //it's null, don't use it
}

2) check for null inline

if (isDouble(myText.getText().toString()) {
    double grade[] = myText.getText() == null ? {0.0, 0.0} : {Double.parseDouble(myText.getText().toString())}
}

3) Allow null as an option

double grade[] = myText.getText() == null ? null : {Double.parseDouble(myText.getText().toString())}

4) Cheat and use a Try/Catch (if you don't want to master handling this the best ways, and just want to make sure it doesn't crash and you can notify the user of a data formatting issue, you can simply wrap a Try/Catch around all your code and say "not formatted properly" each time, but that is not very descriptive and possibly not helpful enough, just fyi.

5) Or if you are willing to use Kotlin you can make great extension methods for each.

fun EditText.doubleArrayOrDefault(): ArrayList<Double> {
      return if (this.getText() != null && isDouble(myText.getText().toString())) {
            {Double.parseDouble(myText.getText().toString())}
      } else {
            {0.0, 0.0} // or whatever you want your default to be
      }
 }

6) Lastly, you could simply use DataBinding which would always be my personal preference. Update your gradle to enable DataBining and accept the inevitable that it's the greatest thing to happen since sliced break ;).

in the Activity you would have

var myObservabeText: ObservableField<String> = ObservableField("defaultTextIfAny")

in the onCreate you would set the variable

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    mBinding = DataBindingUtil.setContentView(this, R.layout.activity_my)
    mBinding.activity = this
}

in the XML you would update it to be

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:bind="http://schemas.android.com/apk/res-auto">

    <data>
        <variable name="activity" type="com.package.a35.activities.MyActivity" />
    </data>

     <EditText
        android:id="@+id/myText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@={activity.myObservableText}" />

Of course you can also add a JVMStatic to an adapter to handle binding to an array of double as well, if you want to write a nice adapter that is pretty straight forward as well.

Of course this is all pseudo and not typed in the actual IDE, but it will be very close, so hopefully this will help you with options.

Best of luck, hopefully one of these options fits your needs nicely.

Happy Coding.

Question:

I am trying to get values from a patient registration form into my database. But each time when I click on Submit button, application stops with following message: Unfortunately. Application has stopped.

Logcat details are:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

My code for the same is as follows:

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TimePicker;

public class indoor_patient extends Activity{

public EditText sr_no, patient_name, consultant_name, ref_dr, department,
        rel_name, rel_no, arr_date, arr_time;
Button submit;
ImageButton datepicker, timepicker;
Calendar cal;
int day, month, year;
int hour, min;

static final int TIME_DIALOG_ID = 1;

static final int DATE_DIALOG_ID = 0;

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.indoor_patient_tbl);

    sr_no = (EditText) findViewById(R.id.etSrNo);
    patient_name = (EditText) findViewById(R.id.etPatientName);
    consultant_name = (EditText) findViewById(R.id.etConsultantDr);
    ref_dr = (EditText) findViewById(R.id.etRefDr);
    department = (EditText) findViewById(R.id.etDepartment);
    rel_name = (EditText) findViewById(R.id.etRelativeName);
    rel_no = (EditText) findViewById(R.id.etRelContact);
    arr_date = (EditText) findViewById(R.id.etArrDate);
    arr_time = (EditText) findViewById(R.id.etArrTime);

    submit = (Button) findViewById(R.id.btnIndoorSubmit);

    cal = Calendar.getInstance();

    day = cal.get(Calendar.DAY_OF_MONTH);
    month = cal.get(Calendar.MONTH);
    year = cal.get(Calendar.YEAR);
    datepicker = (ImageButton) findViewById(R.id.imgBtnDate);

    datepicker.setOnClickListener(new View.OnClickListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onClick(View v) {

            showDialog(DATE_DIALOG_ID);
        }
    });


    hour = cal.get(Calendar.HOUR_OF_DAY);
    min = cal.get(Calendar.MINUTE);
    timepicker = (ImageButton) findViewById(R.id.imgBtnTime);

    timepicker.setOnClickListener(new View.OnClickListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onClick(View v) {
            showDialog(TIME_DIALOG_ID);
        }
    });

    submit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new dbwork().execute();
        }
    });
}

@Override
protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
    switch (id) {
    case DATE_DIALOG_ID:
        return new DatePickerDialog(this, datePickerListener, year, month,
                day);
    case TIME_DIALOG_ID:    
        return new TimePickerDialog(this, timePickerListener, hour, min,
                false);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        arr_date.setText(selectedDay + "/" + (selectedMonth + 1) + "/"
                + selectedYear);
    }
};

private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        int hour;
        String am_pm;
        if (hourOfDay > 12) {
            hour = hourOfDay - 12;
            am_pm = "PM";
        } else {
            hour = hourOfDay;
            am_pm = "AM";
        }
        arr_time.setText(hour + ":" + min + " " + am_pm);
    }
};  
}

And my database connectivity file is as follows:

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;

public class dbwork extends AsyncTask<Void, String, String> {

indoor_patient ins=new indoor_patient();    
String webUrl = "http://10.0.3.2:8084/data_web/indoorPatient.jsp?sr_no="
        + ins.sr_no.getText().toString()
        + ""
        + ins.patient_name.getText().toString()
        + ""
        + ins.consultant_name.getText().toString()
        + ""
        + ins.ref_dr.getText().toString()
        + ""
        + ins.department.getText().toString()
        + ""
        + ins.rel_name.getText().toString()
        + ""
        + ins.rel_no.getText().toString()
        + ""
        + ins.arr_date.getText().toString()
        + ""
        + ins.arr_time.getText().toString() + "&submit=Submit";

@Override
protected String doInBackground(Void... params) {
    // TODO Auto-generated method stub
    StringBuffer strbuffer=new StringBuffer("");
    String line="";

    try {

       URL url=new URL(webUrl);

        HttpURLConnection hurl;
        hurl=(HttpURLConnection)url.openConnection();

        BufferedInputStream bis;
        bis=new BufferedInputStream(hurl.getInputStream());

        InputStream is;
        is=bis;//implicit casting  // from downward to upward

        InputStreamReader isr;
        isr=new InputStreamReader(is);

        BufferedReader br;
        br=new BufferedReader(isr);

        //reading html form
        while ((line = br.readLine()) != null) {

            strbuffer.append(line);
        }

        bis.close();
        is.close();
        isr.close();
        br.close();

        hurl.disconnect();
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return strbuffer.toString();
}

@Override
protected void onPostExecute(String result) {

    super.onPostExecute(result);
   }
}

Answer:

You can't just instantiate your Activity and access the TextView members on it. This doesn't make any sense:

indoor_patient ins=new indoor_patient();    
String webUrl = "http://10.0.3.2:8084/data_web/indoorPatient.jsp?sr_no="
        + ins.sr_no.getText().toString()

Instead you could figure out what your webUrl is in your onClick() method and pass in the complete URL as a parameter to the AsyncTask:

submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String webUrl = "http://10.0.3.2:8084/data_web/indoorPatient.jsp?sr_no="
                + ins.sr_no.getText().toString()
                + ""
                + ins.patient_name.getText().toString()
                + ""
                + ins.consultant_name.getText().toString()
                + ""
                + ins.ref_dr.getText().toString()
                + ""
                + ins.department.getText().toString()
                + ""
                + ins.rel_name.getText().toString()
                + ""
                + ins.rel_no.getText().toString()
                + ""
                + ins.arr_date.getText().toString()
                + ""
                + ins.arr_time.getText().toString() + "&submit=Submit";
        new dbwork().execute(webUrl);
    }
});

Then change your AsyncTask to something like this:

public class dbwork extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        String webUrl = params[0];
        // TODO Auto-generated method stub
        StringBuffer strbuffer=new StringBuffer("");
        // ...