Monday, 19 August 2013

NullPointerException in adnroid

Solution :-

Why NullPointerException occures in Android ?

Many Android developer faced NullPointerException more than one times in a day.

When you try to use Any nullable object then NPE is getting.Any object that not initialize or not give  correct refrences .Also View have not give correct refrences from xml.Sometimes make mistakes due to set wrong content to view.And also when you give any refrence of view from xml  layout see you setContentView().Before setContenview you cant get any refrence from xml.

Suppose i declare ListView and setAdapter.
ListView listview;
listview.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mStrings));

Now your listview is null and you try to setAdapter so nullPointerException is occur.

so you have to give refrence from the xml or create object of listview.

ListView listview=(ListView)findViewById(;


ListView listview = new ListView(this);

In Most case NPE is occured Android Custom Dialog(Alert Dialog),Custom Adapter ListView.see red color text ,thats wrong.

Custom Dilaog/AlertDialog.

Dialog dialog = new Dialog(MyActivityName.this);

EditText editText =(EditText)dialog.findViewById(;
TextView textView =(TextView)dialog.findViewById(;
ImageView imgView =( ImageView)dialog.findViewById(;

editText.setText("edittext"); textView.setText("textview");

Custom Adapter ListView

    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        ViewHolder holder;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) activity
            view = inflater.inflate(R.layout.row, null);
            holder = new ViewHolder();
        } else {
            holder = (ViewHolder) view.getTag();
        holder.title = (TextView) view.findViewById(;
        holder.description = (TextView) view.findViewById(;

     holder.title.setText("title"+ position);
     holder.description.setText("description"+ position);

    return view
} public class ViewHolder {
        public TextView title,description;

How To Solve NullPointerException::
When you get NPE ,First Check your Logcat Error.And find your app package and activity/class name.Then see in parentheses there are your activity/Class name and line no of code that have nullable View/Object.

Here i have NPE in and Line no. is 11.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
    at android.os.Handler.dispatchMessage(
    at android.os.Looper.loop(
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
    at java.lang.Class.newInstanceImpl(Native Method)
    at java.lang.Class.newInstance(
    ... 11 more