Null pointer exception when inserting in db
<p>I have a problem that when we want to Insert a data into a database table it returns a NullPointer Exception as "Failure delivering result resultInfo".
I don't know why it comes how will it removed?</p>

<p>Please suggest me the solution to this problem.</p>

<p><strong>Error Srtack:</strong></p>

<pre><code>08-05 16:18:39.816: ERROR/AndroidRuntime(5045): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=com.google.zxing.client.android.SCAN flg=0x80000 (has extras) }} to activity {com.shopzilla.android.common/com.shopzilla.android.common.MainActivity}: java.lang.NullPointerException
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3515)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3557)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at android.app.ActivityThread.access$2800(ActivityThread.java:125)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2063)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at android.os.Looper.loop(Looper.java:123)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at java.lang.reflect.Method.invokeNative(Native Method)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at java.lang.reflect.Method.invoke(Method.java:521)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at dalvik.system.NativeStart.main(Native Method)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045): Caused by: java.lang.NullPointerException
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at com.shopzilla.android.common.MainActivity.onActivityResult(MainActivity.java:210)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at android.app.Activity.dispatchActivityResult(Activity.java:3890)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3511)
08-05 16:18:39.816: ERROR/AndroidRuntime(5045):     ... 11 more
</code></pre>

<p><strong>Code:</strong></p>

<pre><code>package com.shopzilla.android.common;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.LinearGradient;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.flurry.android.FlurryAgent;
import com.shopzilla.android.client.dto.ProductSearchRequest;
import com.shopzilla.android.client.model.BaseInventoryItem;
import com.shopzilla.android.client.model.CatalogResponse;
import com.shopzilla.android.product.ProductComparisonActivity;
import com.shopzilla.android.search.SearchResultActivity;
import java.util.ArrayList;
import java.util.Locale;

public class MainActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    private LocationManager locationManager;
    private Location currentLocation;
    static ArrayList&lt;String&gt; recent = new ArrayList&lt;String&gt;();
    SQLiteDatabase db;
    static String keyword;
    EditText txt_search;
    public static Boolean zipcode = false;
    public static String zip = "";
    String lat;
    String longi;
    public static String status = "";
    Dialog dialog;
    public static int count = 0;
    ContentValues values;
    private static final String CREATE_RECENT_BARCODE_TABLE = "create table if not exists recentbarcode(prod TEXT,status TEXT,image TEXT);";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btn = (Button) findViewById(R.id.btn_Search);
        Button btn_scanbar = (Button) findViewById(R.id.btn_ScanBar);
        txt_search = (EditText) findViewById(R.id.txt_Search);

        //Create Favorites DataBase
        final SQLiteDatabase db = openOrCreateDatabase("recentsearches2.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
        db.setVersion(1);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);
        db.execSQL(CREATE_RECENT_BARCODE_TABLE);
        values = new ContentValues();

        if (count == 0) {
            showDialog(0);
        }
        //Open Search Result Activity
        btn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                recent.add(txt_search.getText().toString());
                keyword = txt_search.getText().toString();
                if (!keyword.equals("")) {
                    Intent intent = new Intent(MainActivity.this, SearchResultActivity.class);
                    intent.putExtra("keyword", txt_search.getText().toString());
                    startActivity(intent);
                } else {
                    Toast.makeText(MainActivity.this, "Please Enter a Search Text in a Search Box.", Toast.LENGTH_SHORT).show();
                }

            }
        });
        //Open Scan BarCode Activity
        btn_scanbar.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                try {
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    intent.setPackage("com.google.zxing.client.android");
                    intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
                    startActivityForResult(intent, 0);
                } catch (Exception e) {
                    AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
                    alertDialog.setTitle("BIZRATE");
                    alertDialog.setMessage("Download BarCode Scanner App!!");
                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent viewIntent =
                                    new Intent("android.intent.action.VIEW",
                                            Uri.parse("https://market.android.com/details?id=com.google.zxing.client.android"));
                            startActivity(viewIntent);

                            return;
                        }
                    });
                    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            return;
                    } });
                    alertDialog.show();
                }

            }
        });

        //Geo Coding

        this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // Subscribe to the location manager's updates on the current location
        this.locationManager.requestLocationUpdates("gps", (long) 30000, (float) 10.0, new LocationListener() {
            public void onLocationChanged(Location arg0) {
                handleLocationChanged(arg0);
            }

            public void onProviderDisabled(String arg0) {

            }

            public void onProviderEnabled(String arg0) {

            }

            public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

            }
        });

        txt_search.setOnEditorActionListener(new EditText.OnEditorActionListener() {

            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    recent.add(txt_search.getText().toString());
                    keyword = txt_search.getText().toString();
                    if (!keyword.equals("")) {
                        Intent intent = new Intent(MainActivity.this, SearchResultActivity.class);
                        intent.putExtra("keyword", txt_search.getText().toString());
                        startActivity(intent);
                    } else {
                        Toast.makeText(MainActivity.this, "Please Enter a Search Text in a Search Box.", Toast.LENGTH_SHORT).show();
                    }

                }
                return false;
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {

                String contents = intent.getStringExtra("SCAN_RESULT");
                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

                // perform the barcode search immediately after getting the scan
                ProductSearchRequest barcodeSearch = ProductSearchRequestFactory.createProductSearchRequest();
                barcodeSearch.setProductId(contents);
                barcodeSearch.setZipCode("90291");
                barcodeSearch.setResultsOffers(25);
                CatalogResponse barcodeResponse = CatalogServiceLocator.getCatalogAPIClient().performSearch(barcodeSearch);
                BaseInventoryItem item = null;

                // check to see if the searched scan returned an offer
                if(barcodeResponse.getOffers() != null &amp;&amp; !barcodeResponse.getOffers().isEmpty()){
                    item = barcodeResponse.getOffers().get(0);
                }
                // check to see if the searched scan returned a product
                if(barcodeResponse.getProducts() != null &amp;&amp; !barcodeResponse.getProducts().isEmpty()){
                    item = barcodeResponse.getProducts().get(0);
                }
                if(item != null) {
                    // Send the user directly to product comparison activity, with the item returned by the scan
                    Intent searchIntent = new Intent(MainActivity.this, ProductComparisonActivity.class);
                    searchIntent.putExtra("item", item);
                    startActivity(searchIntent);
                    /* values = new ContentValues();*/
                     values.put("prod",contents);
                     values.put("status","Product Found");
                     values.put("image",item.getImageUrl(60));

                } else {
                    Toast.makeText(MainActivity.this, "Product Not Found on Bizrate", Toast.LENGTH_SHORT).show();
                    /* values = new ContentValues();*/
                     values.put("prod",contents);
                     values.put("status","Product Not Found");
                     values.put("image","");
                     long id = db.insert("recentbarcode",null,values); //-----------&gt; Here is the Problem
                }
              /*  long id = db.insert("recentbarcode",null,values);
                db.close();*/
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(MainActivity.this, "Scan Cancelled.", Toast.LENGTH_SHORT).show();
            }
        }

    }

    private void handleLocationChanged(Location loc) {
        // Save the latest location
        this.currentLocation = loc;
        // Update the latitude &amp; longitude TextViews
        lat = Double.toString(loc.getLatitude());
        longi = Double.toString(loc.getLongitude());
    }

    private void handleReverseGeocodeClick() {
        if (this.currentLocation != null) {
            // Kickoff an asynchronous task to fire the reverse geocoding
            // request off to google
            ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
            task.applicationContext = this;
            task.execute();
        } else {
            // If we don't know our location yet, we can't do reverse
            // geocoding - display a please wait message
            showToast("Please wait until we have a location fix from the gps");
        }
    }

    public void showToast(CharSequence message) {
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(getApplicationContext(), message, duration);
        toast.show();
    }

    public class ReverseGeocodeLookupTask extends AsyncTask&lt;Void, Void, String&gt; {
        private ProgressDialog dialog;
        protected Context applicationContext;

        @Override
        protected void onPreExecute() {
            this.dialog = ProgressDialog.show(applicationContext, "Please wait...contacting the tubes.",
                    "Requesting reverse geocode lookup", true);
        }

        @Override
        protected String doInBackground(Void... params) {
            String localityName = "";

            if (currentLocation != null) {
                localityName = Geocoder.reverseGeocode(currentLocation);
            }

            return localityName;
        }

        @Override
        protected void onPostExecute(String result) {
            //this.dialog.cancel();
            zip = result;
            dialog.dismiss();

        }
    }

    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case 0:
                count = 1;
                dialog = new Dialog(this);
                //dialog.setTitle("");
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.geocode);
                dialog.show();

                Button btn_getGeo = (Button) dialog.findViewById(R.id.btn_Geo_Ok);
                Button btn_cancel = (Button) dialog.findViewById(R.id.btn_Geo_cancel);
                btn_getGeo.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View arg0) {

                        zipcode = true;
                        handleReverseGeocodeClick();
                        //dialog.dismiss();
                        removeDialog(0);
                    }
                });

                btn_cancel.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View arg0) {

                        removeDialog(0);
                    }
                });

                break;
        }
        return dialog;
    }

    //Flurry Implementation
    public void onStart() {
        super.onStart();
        FlurryAgent.onStartSession(this, "AJT5DWUVF6IAE78NQV69");
        // your code
    }

    public void onStop() {
        super.onStop();
        FlurryAgent.onEndSession(this);
        // your code
    }
}
</code></pre>
