简体   繁体   中英

Android application closes when clicking a button

I am developing an android application that takes user information entered in an edit text as an argument in an sql argument. An example of this is if I were to type in "Business A" and click one of my buttons that says "By Name" it would search the database using the Name column and display the results. The other button is "By Type" which would essentially do the same thing but only by the type of business. My code runs without errors on an emulator and displays my background image, the buttons, and the text. Upon clicking it'll close the application. I am new to android programming and any help or advice would be greatly appreciated. I have put my code and logcat below for others to view.

Main activity where the database is created:

public class MainActivity 
{
    EditText dEdit;
    public static final String KEY_ROWID = "_id";
    public static final String KEY_BUSINESS = "business";
    public static final String KEY_ADDRESS = "address";
    public static final String KEY_PHONE = "phone";
    public static final String KEY_HOURS = "hours";
    public static final String KEY_WEB = "website";
    public static final String KEY_TYPE = "type";


    private static final String TAG = "MainActivity";

    private static final String DATABASE_NAME = "LocalDB";
    private static final String DATABASE_TABLE = "Business";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE =
        "create table Business (_id integer primary key autoincrement, "
        + "business text not null, address text not null, phone text not null,hours text not null,website text not null,type text not null" 
        + ")";

    private final Context context; 

    private DatabaseHelper DBHelper;
    private SQLiteDatabase mDB;

    public MainActivity(Context ctx) 
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private  class DatabaseHelper extends SQLiteOpenHelper 
    {
        DatabaseHelper(Context context) 
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) 
        {
            try{
            mDB=db;
            mDB.execSQL(DATABASE_CREATE);
            } catch(SQLException e){
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, 
        int newVersion) 
        {   
            try{
                mDB=db;
            Log.w(TAG, "Upgrading database from version " + oldVersion 
                    + " to "
                    + newVersion + ", which will destroy all old data");
            mDB.execSQL("DROP TABLE IF EXISTS Business");
            onCreate(mDB);
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }    

    //---opens the database---
    public MainActivity open() throws SQLException 
    {
        mDB = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---    
    public void close() 
    {
        DBHelper.close();
    }

    //---insert a title into the database---
    public long insertTitle(String business, String address, String phone, String hours, String website, String type) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_BUSINESS, business);
        initialValues.put(KEY_ADDRESS, address);
        initialValues.put(KEY_PHONE, phone);
        initialValues.put(KEY_HOURS, hours);
        initialValues.put(KEY_WEB, hours);
        initialValues.put(KEY_TYPE, type);
        return mDB.insert(DATABASE_TABLE, null, initialValues);
    }

    //---deletes a particular title---
    public boolean deleteTitle(long rowId) 
    {
        return mDB.delete(DATABASE_TABLE, KEY_ROWID + 
                "=" + rowId, null) > 0;
    }

    //---retrieves all the titles---
    public Cursor getAllTitles() 
    {
        return mDB.query(DATABASE_TABLE, new String[] {
                KEY_ROWID, 
                KEY_BUSINESS,
                KEY_ADDRESS,
                KEY_PHONE,
                KEY_HOURS,
                KEY_WEB,
              KEY_TYPE}, 
                null, 
              null, 
                null, 
                null, 
                null);
    }

    //---retrieves a particular title---
    public Cursor getTitle(long rowId) throws SQLException 
    {
        Cursor mCursor =
                mDB.query(true, DATABASE_TABLE, new String[] {
                        KEY_ROWID,
                        KEY_BUSINESS, 
                        KEY_ADDRESS,
                        KEY_PHONE,
                        KEY_HOURS,
                        KEY_WEB,
                        KEY_TYPE
                        }, 
                        KEY_ROWID + "=" + rowId, 
                        null,
                        null, 
                        null, 
                        null, 
                        null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    //---updates a title---
    public boolean updateTitle(long rowId, String business, 
    String address, String phone, String hours, String website, String type) 
    {
        ContentValues args = new ContentValues();
        args.put(KEY_BUSINESS, business);
        args.put(KEY_ADDRESS, address);
        args.put(KEY_PHONE, phone);
        args.put(KEY_HOURS,hours);
        args.put(KEY_WEB,website);
        args.put(KEY_TYPE, type);
        return mDB.update(DATABASE_TABLE, args, 
                         KEY_ROWID + "=" + rowId, null) > 0;
    }



}

Where the data should hopefully be displayed:

public class DBUse extends Activity {
    EditText dEdit;
    MainActivity data;
    public static final String KEY_ROWID = "_id";
    public static final String KEY_BUSINESS = "business";
    public static final String KEY_ADDRESS = "address";
    public static final String KEY_PHONE = "phone";
    public static final String KEY_HOURS = "hours";
    public static final String KEY_WEB = "website";
    public static final String KEY_TYPE = "type";




    @Override
    public void onCreate(Bundle savedInstanceState) {

        // TODO Auto-generated method stub


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MainActivity data = new MainActivity(this);

        Button buttonName =(Button)findViewById(R.id.buttonName);
        buttonName.setOnClickListener(startName);

        Button buttonType =(Button)findViewById(R.id.buttonType);
        buttonType.setOnClickListener(startType);

        dEdit =(EditText)findViewById(R.id.textView1);

        data.open();


        Cursor c = data.getAllTitles();
        if(c.moveToFirst())
        {
            do{DisplayTitle(c);
        }while (c.moveToNext());
    }   
        data.open();
        Cursor b = data.getAllTitles();

        if (b.moveToFirst())
            DisplayTitle(b);
        else
            Toast.makeText(this,"No business found",Toast.LENGTH_LONG).show();
        data.close();

    data.close();


    }



//displays the data

    public void DisplayTitle(Cursor c) {
        Toast.makeText(this,
        "Name: " + c.getString(1)+"\n"+
        "Address:" + c.getString(2)+"\n"+
        "Phone:" + c.getString(3)+"\n"+
        "Hours:" + c.getString(4)+"\n"+
        "Website"+ c.getShort(5)+
        "Type" + c.getShort(6),
        Toast.LENGTH_LONG).show();


    }

    //Informs the user what is being searched
    private OnClickListener startName=new OnClickListener(){

        public void onClick (View v){

            Cursor cur=data.rawQuery("SELECT business,address,phone,hours,website,type FROM Business where name like %"+dEdit.getText().toString()+"%", null);
            String result="";

            //int iRow=cur.getColumnIndex(KEY_ROWID);
            //int   iName=cur.getColumnIndex(KEY_BUSINESS);
            //int iAddress=cur.getColumnIndex(KEY_ADDRESS);
            //int   iPhone=cur.getColumnIndex(KEY_PHONE);
            //int   iHours=cur.getColumnIndex(KEY_HOURS);
            //int iWebsite=cur.getColumnIndex(KEY_WEB);
            //int iType=cur.getColumnIndex(KEY_TYPE);
            Toast.makeText(DBUse.this, "Searching by Name", Toast.LENGTH_LONG).show();
        //  log.d("result",DBUse.getString(0));
            //for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()){
                //result=result +cur.getString(iRow) + " "
                    //  +cur.getString(iName) + " "
                    //  +cur.getString(iAddress) + " "
                    //  +cur.getString(iPhone) + " "
                    //  +cur.getString(iHours) + " "
                    //  +cur.getString(iWebsite) + " "
                //      +cur.getString(iType) + " " + "\n";

            //}
            return;
        }




        //Informs the user what is being searched
    private OnClickListener startType=new OnClickListener(){
        public void onClick (View v){
            Cursor cur=data.rawQuery("SELECT business,address,phone,hours,website,type FROM Business where type like %"+dEdit.getText().toString()+"%", null);
            String result="";
            //int iRow=cur.getColumnIndex(KEY_ROWID);
            //int   iName=cur.getColumnIndex(KEY_BUSINESS);
            //int iAddress=cur.getColumnIndex(KEY_ADDRESS);
            //int   iPhone=cur.getColumnIndex(KEY_PHONE);
            //int   iHours=cur.getColumnIndex(KEY_HOURS);
            //int iWebsite=cur.getColumnIndex(KEY_WEB);
            //int iType=cur.getColumnIndex(KEY_TYPE);
            Toast.makeText(DBUse.this, "Searching by Name", Toast.LENGTH_LONG).show();
        //  log.d("result",DBUse.getString(0));
            //for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()){
                //result=result +cur.getString(iRow) + " "
                    //  +cur.getString(iName) + " "
                        //+cur.getString(iAddress) + " "
                        //+cur.getString(iPhone) + " "
                        //+cur.getString(iHours) + " "
                        //+cur.getString(iWebsite) + " "
                        //+cur.getString(iType) + " " + "\n";


            //}
            return;
        }


        };
    };
}

Lastly where all the data is coming from.

package com.example.database;
import java.io.IOException;
import java.io.InputStream;
import static android.provider.BaseColumns._ID;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;
import java.io.OutputStream;
import android.database.sqlite.SQLiteDatabase;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class DBActivity extends Activity {
    MainActivity eventsData;
    EditText output;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MainActivity db= new MainActivity(this);

        output = (EditText) findViewById(R.id.textView1);



        //type.setOnClickListener(
        //      new OnClickListener(){
        //          public void onClick(View view){
        //              Log.v("Entry",dEdit.getText().toString());
            //      }
        ///     });


        //try{String destPath="/data/data" +getPackageName()+ "/databases/BloomBusiness";
        //  File f = new File(destPath);
        //  if(!f.exists()){
        //      CopyDB(getBaseContext().getAssets().open("db"), new FileOutputStream(destPath));
        //  }
        //  
        //  
        //}catch(FileNotFoundException e){
        //  e.printStackTrace();
        //}catch(IOException e){
        //  e.printStackTrace();
        //}

        db.open();

        //inserting all data
        long id; 
        id =db.insertTitle("BloomingFoods","419 E. Kirkwood Ave. Bloomington, IN", "812-336-5300", "M-Sat:8AM-9PM Sun:9AM-8PM","http://www.bloomingfoods.coop","Grocery");


        id=db.insertTitle("BloomingFoods","316 W. 6th Street Bloomington, IN", "812-333-5300", "M-Sat:7AM-10PM Sun:9AM-9PM","http://www.bloomingfoods.coop","Grocery");
        id=db.insertTitle("BloomingFoods","3220 E. 3rd Street Bloomington, IN", "812-336-5300", "M-Sun:8AM-10PM","http://www.bloomingfoods.coop","Grocery");
        id=db.insertTitle("The Uptown Cafe","102 E. Kirkwood Ave. Bloomington, IN", "812-339-0900", "M-Sat:8AM-9PM Sun:9AM-8PM", "http://www.the-uptown.com/","Cajun-Creole");
        id=db.insertTitle("Crazy Horse","214 W. Kirkwood Ave. Bloomington, IN", "812-336-8877", "M-Sat:11AM-2AM Sun:Noon-Midnight", "http://www.crazyhorseindiana.com/","Restaurant & Live Music");
        id=db.insertTitle("FARMbloomington","108 E. Kirkwood Ave. Bloomington, IN", "812-323-0002", "Tue.-Thurs.:8AM-10PM F:8AM-1AM Sat: 10AM-3AM Sun: 10AM-10PM","http://www.farm-bloomington.com","Grocery");
        id=db.insertTitle("Laughing Planet","322 E. Kirkwood Ave. Bloomington, IN", "812-323-2233", "M-Sun:11AM-9PM","http://www.facebook.com/laughingplanetbtown","Burritos & Salads");
        id=db.insertTitle("Soma Coffeehouse","322 E. Kirkwood Bloomington, IN", "812-331-2770", "M-Sat:7AM-11PM Sun:8AM-11PM","http://www.iheartsoma.com","Coffee House");
        id=db.insertTitle("Upland Brewing Company","350 W. 11th St. Bloomington, IN", "812-336-2337", "M-Thurs:11AM-Midnight F-Sat:11AM-1AM Sun: Noon-Midnight","http://www.uplandbeer.com","Brewery & Restaraunt");
        id=db.insertTitle("Nick's English Hut","423 E. Kirkwood Bloomington, IN", "812-332-4040", "M-Sat:11AM-2AM Sun: Noon-Midnight","http://www.nicksenglishhut.com","Bar & Restaraunt");
        id=db.insertTitle("The Village Deli","409 E. Kirkwood Ave. Bloomington, IN", "812-336-2303", "M-F:7AM-8PM Sat-Sun 8AM-8PM","http://www.villagedeli.biz","Breakfast,Lunch,Dinner");
        id=db.insertTitle("Rachael's Cafe","300 E. 3rd St. Bloomington, IN", "812-330-1882", "M-F:8AM-9PM Sat-Sun 9AM-9PM","http://www.rachaelscafe.com","Coffee House & Live Music");
        id=db.insertTitle("Happy Pig","1604 W. 7th St. Bloomington, IN", "None", "W:Sample Gates Noon-3PM Thurs:Sample Gates Noon-3PM F:Atlas Bar 11:30PM-3:30AM Sat:Courthouse Square 11:30PM-3:30AM","http://www.happypigbloomington.com","BBQ Streetfood");
        id=db.insertTitle("Lennie's Restaurant and Brewpub","1795 E. 10th St. Bloomington, IN", "812-323-2112", "Sun-Th:11AM-11PM F-Sat 11AM-Midnight","http://www.lenniesgourmetpizza.com","Bar & Restaurant");
        id=db.insertTitle("Pizza X","1791 E. 10th St. Bloomington, IN", "812-339-7737", "Sun-Tues:11AM-2AM Wed-Thur: 11AM-3AM F-Sat:11AM-4AM","http://www.pizzaxbloomington.com","Pizza");
        id=db.insertTitle("Pizza X","1610 W. 3rd St. Bloomington, IN", "812-332-2522", "Sun-Wed:4PM-Midnight Thur: 4PM-3AM F-Sat:4PM-4AM","http://www.pizzaxbloomington.com","Pizza");
        id=db.insertTitle("Pizza X","877 S. College Mall Rd. Bloomington, IN", "812-355-5000", "Sun-Wed:4PM-Midnight Thur: 4PM-3AM F-Sat:4PM-4AM","http://www.pizzaxbloomington.com","Pizza");
        id=db.insertTitle("Pizza X","2443 S. Walnut St. Pk. Bloomington, IN", "812-332-8500", "Sun-Wed:4PM-Midnight Thur: 4PM-3AM F-Sat:4PM-4AM","http://www.pizzaxbloomington.com","Pizza");
        id=db.insertTitle("The Atlas Bar","209 S. College Ave.  Bloomington, IN", "812-334-4435", "M-F:5PM-3AM Sat-Sun:7PM-3AM","http://www.atlasballroom.com","Bar");
        id=db.insertTitle("The Bishop","123 S. Walnut St.  Bloomington, IN", "812-333-4700", "Mon-Sat:7PM-3AM","http://www.thebishopbar.com","Bar & Live Music");
        id=db.insertTitle("Oliver Winery","8024 N. State Road 37 Bloomington, IN", "812-876-5800", "Mon-Sat:10AM-6PM Sun: 12PM-6PM Tours:F-Sat Noon-4:30PM Sun:1PM-4:30PM","http://www.oliverwinery.com","Winery");
        id=db.insertTitle("Revolution Bike and Bean","401 E. 10th St. Bloomington, IN", "812-336-0241", "Mon-Fri:10AM-6PM Sat: 10AM-5PM","http://www.revolutionbikeandbean.com","Coffee House & Bike Repair Shop");
        id=db.insertTitle("Mother Hubbard's Cupboard","1010 S. Walnut Bloomington, IN", "812-355-6843", "Mon-Fri:4PM-6PM","http://www.mhcfoodpantry.org","Food Pantry Service & Non-Profit");
        id=db.insertTitle("Patricia's Wellness Arts Cafe and Quilter's Comfort Teas","725 W. Kirkwood Ave. Bloomington, IN", "812-331-0886", "Mon-Sat:11AM-5PM First Friday: 11AM-8PM","http://www.hartrock.net/cafe.htm","Tea House & Holistic and Naturopathic & Reiki & Counseling");
        id=db.insertTitle("One World Catering and Events","2234 W. Industrial Pk. Dr. Bloomington, IN", "812-334-3663", "","http://www.oneworldcateringandevents.com","Catering");
        id=db.insertTitle("Nelson's Furniture Restoration","6573 S. Old State Road 37 Bloomington, IN", "812-824-7769", "M-F:10AM-6PM","http://www.nelsonrestoration.com","Furniture Restoration");
        id=db.insertTitle("NR Hiller Design, Inc","3450 S. Garrison Chapel. Rd. Bloomington, IN", "812-825-5872", "Hours By Appointment","http://www.nrhillerdesign.com","Furniture Design & Furniture Building & Cabinet-Making & Furniture");
        id=db.insertTitle("Showers Inn Bed and Breakfast","430 N. Washington St. Bloomington, IN", "812-334-9000", "Hours By Appointment","http://www.showersinn.com","Bed and Breakfast");
        id=db.insertTitle("Monroe County History Center","202 E. 6th St.  Bloomington, IN", "812-332-2517", "Tues-Sat:10AM-4PM","http://www.monroehistory.org","Museum");
        id=db.insertTitle("WFHB","108 W. 4th St. Bloomington, IN", "812-323-0320", "Hours By Appointment","http://www.wfhb.org","Radio Station & Non-Profit");
        id=db.insertTitle("Brinegar Eye Care","4001 E. 3rd St. Suite 8 Bloomington, IN", "812-339-7995", "Mon-F:9AM-5PM","http://www.brinegareyecare.com","Optometrist");
        id=db.insertTitle("Sole Sensations","414 S. College Ave. Bloomington, IN", "812-331-1962", "Mon:10AM-6PM Tues:10AM-8PM Wed:10AM-6PM Thurs:10AM-8PM Sat:10AM-5PM","http://www.solesensations.com/Soul-Inspirations.html","Orthotics & Shoes");
        id=db.insertTitle("Bloomignton Area Birth Services (BABS)","2458 S. Walnut St. Bloomington, IN", "812-337-8121", "Mon-Fri:10AM-5PM Sat:10AM-2PM" ,"http://www.bloomingtonbirth.org","Holistic and Naturopathic & Non-Profit & Gifts & Toys & Books & Maternity/Nursing Wear & Prenatal and Postnatal Yoga & Childbirth Classes & Breastfeeding Classes and Consultation");
        id=db.insertTitle("Karen Knight, LMHC Counseling Services","115 N. College Ave Suite 214 Bloomington, IN", "812-361-3601", "Mon-Fri:9AM-8PM By Appointment" ,"http://www.karenknight.net","Mental Health & Counseling");
        id=db.insertTitle("Mister Buck's Genuinely Good Pet Food Compnay","319 S. Mitchell Bloomington, IN", "812-384-3853", "24hr Internet Access" ,"http://www.mrbuckspetfood.com","Pet Care");
        id=db.insertTitle("Center for Sustainable Living","323 S. Walnut St. Bloomington, IN", "812-332-8796", "24hr Internet Access" ,"http://www.simplycsl.org","Non-Profit");
        id=db.insertTitle("Friends of Art Bookshop","1201 E. 7th St. (Fine Arts Building, Indiana University) Bloomington, IN", "812-855-7498","M-Thurs:9AM-6PM Sat-Sun:1PM-5PM" ,"http://www.fa.indiana.edu/foart/","Non-Profit & Books & Art Books & Textbooks");
        id=db.insertTitle("Cardinal Stage Company","900 S. Walnut St. Bloomington, IN", "812-323-3020", "24hr Internet Access" ,"http://www.cardinalstage.org","Non-Profit & Theater");
        id=db.insertTitle("Bloomington Playwrights Project","107 W. 9th St. Bloomington, IN", "812-334-1188", "Mon-Fri:9AM-5PM" ,"http://www.newplays.org","Non-Profit");
        id=db.insertTitle("Boxcar Books","408 E. 6th St. Bloomington, IN", "812-339-8710", "Mon-Fri: 11AM-9PM Sat:10AM-9PM Sun:10AM-5PM" ,"http://www.boxcarbooks.org","Non-Profit & Books & Textbooks");
        id=db.insertTitle("Community Foundation of Bloomington and Monroe County,Inc.","101 W. Kirkwood Ave. Suite 321 Bloomington, IN", "812-333-9016", "Mon-Fri:8:30AM-5PM" ,"http://www.cfbmc.org","Non-Profit");
        id=db.insertTitle("Windfall Dancers","1101 N. Dunn St. Bloomington, IN", "812-334-0506", "24hr Internet Access" ,"http://www.windfalldancers.org","Non-Profit & Modern Dance & Dance");
        id=db.insertTitle("The Updraft Supplementary Scholarship Project, Inc. (USSP)","403 E. 6th St. Bloomington, IN", "812-961-3553 Toll Free:877-451-8535", "Mon-Fri:9AM-5PM" ,"http://www.usspkids.org","Non-Profit");
        id=db.insertTitle("Story Insights","P.O. Box 2264. Bloomington, IN 47402", "812-340-0479", "24hrs" ,"http://storyinsights.com","Non-Profit & Story Development & Project Management & Web Design");
        id=db.insertTitle("Middle Way House","P.O. Box 95 Bloomington, IN 47402", "Administration:812-333-7404 Crisis Line:812-336-9063", "24hr Internet Access" ,"http://www.middlewayhouse.org","Non-Profit");
        id=db.insertTitle("Baugh Enterprises, Inc","1611 S Rogers St. Bloomington, IN", "812-334-8189", "Mon-Fri:8:30AM-5PM" ,"http://www.baughenterprises.com","Printing Service & Printwork Design");
        id=db.insertTitle("White Rabbit","118 W. 6th St. Bloomington, IN", "812-339-5020 Fax:812-339-7847", "Mon-Fri:8:30AM-5PM" ,"http://www.whiterabbitcopyservice.com","Printing Service");
        id=db.insertTitle("Mr. Copy","501 E. 10th St. Bloomington, IN", "812-334-2679", "Mon-Fri:9AM-6PM Sat: Noon-5PM" ,"http://www.copysales.com","Printing Service & Graphic Design");
        id=db.insertTitle("Rosenplot Design","P.O Box 1083 Bloomington, IN 47402", "812-822-2077 Fax:812-822-2077", "Mon-Fri:8:30AM-5PM" ,"http://www.rosenplotdesign.com","Graphic Design");
        id=db.insertTitle("Patrick Siney Art Direction and Design","1303 S. Stull Ave. Bloomington, IN", "812-334-0019", "Mon-Fri:8:30AM-5PM" ,"http://www.patricksiney.com","Graphic Design & Web Design");
        id=db.insertTitle("Bloomington Cooking School","115 N. College Ave. Suite 014 Bloomington, IN ", "812-333-7100", "Mon-Fri:8:30AM-5PM" ,"http://www.bloomingtoncookingschool.com","Cooking Class");


    }

    //private void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException {
    //  // TODO Auto-generated method stub
    //  byte[] buffer=new byte[1024];
    //  int length;
    //  while((length=inputStream.read(buffer))>0){
    //      outputStream.write(buffer,0,length);
    //  }
    //  inputStream.close();
    //  outputStream.close();
    //}

}

after a few edits I am now getting errors that are shown in the logcat

    04-26 07:12:49.949: I/Process(18874): Sending signal. PID: 18874 SIG: 9
    04-26 07:12:54.070: D/dalvikvm(19443): GC_FOR_ALLOC freed 61K, 2% free 10842K/11011K, paused 50ms, total 52ms
    04-26 07:12:54.070: I/dalvikvm-heap(19443): Grow heap (frag case) to 11.203MB for 614416-byte allocation
    04-26 07:12:54.220: D/dalvikvm(19443): GC_CONCURRENT freed 1K, 2% free 11440K/11655K, paused 82ms+17ms, total 148ms
    04-26 07:12:54.280: D/dalvikvm(19443): GC_FOR_ALLOC freed 0K, 2% free 11440K/11655K, paused 33ms, total 33ms
    04-26 07:12:54.300: I/dalvikvm-heap(19443): Grow heap (frag case) to 12.245MB for 1093136-byte allocation
    04-26 07:12:54.440: D/dalvikvm(19443): GC_CONCURRENT freed 0K, 2% free 12508K/12743K, paused 74ms+15ms, total 141ms
    04-26 07:12:55.160: D/gralloc_goldfish(19443): Emulator without GPU emulation detected.
    04-26 07:13:00.769: D/AndroidRuntime(19443): Shutting down VM
    04-26 07:13:00.769: W/dalvikvm(19443): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
04-26 09:12:27.900: E/AndroidRuntime(3962): FATAL EXCEPTION: main
04-26 09:12:27.900: E/AndroidRuntime(3962): java.lang.NullPointerException
04-26 09:12:27.900: E/AndroidRuntime(3962):     at com.example.database.DBUse$2.onClick(DBUse.java:123)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at android.view.View.performClick(View.java:4084)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at android.view.View$PerformClick.run(View.java:16966)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at android.os.Handler.handleCallback(Handler.java:615)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at android.os.Looper.loop(Looper.java:137)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at android.app.ActivityThread.main(ActivityThread.java:4745)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at java.lang.reflect.Method.invokeNative(Native Method)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at java.lang.reflect.Method.invoke(Method.java:511)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-26 09:12:27.900: E/AndroidRuntime(3962):     at dalvik.system.NativeStart.main(Native Method)

This is where my issue is now it says that rawQuery is undefined by MainActivity does this mean I need to use the variable SQLiteDatabase? code below :

Cursor cur=data.rawQuery("SELECT business,address,phone,hours,website,type FROM Business where type like %"+dEdit.getText().toString()+"%", null);

looks like db is null in the function onClick(). Also, why are you using the same variable name twice, one for SQLiteDatabase and another for MainActivity.

When checking your logcat you have this :

04-26 09:12:27.900: E/AndroidRuntime(3962): FATAL EXCEPTION: main
04-26 09:12:27.900: E/AndroidRuntime(3962): java.lang.NullPointerException
04-26 09:12:27.900: E/AndroidRuntime(3962):     at com.example.database.DBUse$2.onClick(DBUse.java:123)

Go on line 123 in DBUse, and debug on it. what is happening is that on this line you have an instance calling a method (for example db.rawQuery ) and that instance is null. in this example db.

If you still can't find the problem, post what is on line 123 in your question

if this is your line

Cursor cur=db.rawQuery("SELECT        business,address,phone,hours,website,type FROM          Business where type    like %"+dEdit.getText().toString()+"%", null);

then what shouldn't be null is db or dEdit or dEdit.getText()

I didn't see where in your code db is initialised. I think this is the problem

Steps for the solution :

  • rename private SQLiteDatabase db; to private SQLiteDatabase mDB; (so you can differentiate it from the other variables)

  • change OnCreate of DataHelper to this

      @Override public void onCreate(SQLiteDatabase db) { try{ mDb = db; mDb.execSQL(DATABASE_CREATE); } catch(SQLException e){ e.printStackTrace(); } } 

(do same thing for upgrade)

and Everywhere else use mDb instead of db.

(also change the name of MainActivity db , it's confusing)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM