0

我正在尝试制作一个简单的联系人列表应用程序,当我按下按钮创建联系人时,它会显示一个表单,在该表单中添加详细信息后,我必须在其中添加人员的联系人详细信息,然后我必须按保存按钮来保存这些字段进入我的数据库,但是当我按下保存按钮时,我遇到了错误

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { (has extras) }} 
to activity {com.webpreneur_contactlist/com.webpreneur_contactlist.WebpreneurActivity}: 
java.lang.IllegalStateException: database not open

这是我的代码:

     public class WebpreneurActivity extends ListActivity {

        private static final int CONTACT_CREATE = 0;
        private static final int CONTACT_EDIT = 1;

        //select the second one, Android view menu
        private static final int INSERT_ID = Menu.FIRST;
        private static final int DELETE_ID = Menu.FIRST + 1;

        private DBHandler dbHelper;
        private Cursor c;
        ImageButton imageButton;
    long rowid;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            Log.d("database1" ,"0");
            Log.d("Your Location4", "ok4:");
            super.onCreate(savedInstanceState);
            Log.d("database1" ,"1");
            setContentView(R.layout.activity_webpreneur);
            Log.d("database1" ,"2");
            dbHelper = new DBHandler(this);
            Log.d("database1" ,"3");
            dbHelper.open();
            //addListenerOnButton();
        //dbHelper.addContact();
        dbHelper.close();
        imageButton = (ImageButton) findViewById(R.id.imageButton1);
        Log.d("database1" ,"button");
        imageButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Log.d("database1" ,"b4");
                Intent i = new Intent(getApplicationContext(),      ContactEdit.class);
                startActivityForResult(i, CONTACT_CREATE);

                Log.d("database1" ,"button3");
                //fillData();
            }

        });

    }


    @SuppressWarnings("deprecation")
    public void fillData() {
        Log.d("Your Location4", "ok6:");
        c = dbHelper.fetchAllRows();
        Log.d("Your Location4", "ok8:");
        startManagingCursor(c);
        Log.d("Your Location4", "ok2:");
        ListAdapter adapter = new SimpleCursorAdapter(this,
                R.layout.contact_row, c, new String[] { DBHandler.Key_Name,
                        DBHandler.Key_Phone }, new int[] { R.id.name,
                        R.id.phonenumber });
        setListAdapter(adapter);
    }





        /*private void createContact() {
            Intent i = new Intent(this, ContactEdit.class);
            startActivityForResult(i, CONTACT_CREATE);
        }*/
        protected void onListItemClick(ListView l, View v, int position, long id) {
            super.onListItemClick(l, v, position, id);

            Intent i = new Intent(this, ContactEdit.class);
            i.putExtra(DBHandler.Key_ID, c.getLong(c.getColumnIndex(DBHandler.Key_ID)));
            i.putExtra(DBHandler.Key_Name, c.getString(c.getColumnIndex(DBHandler.Key_Name)));
            i.putExtra(DBHandler.Key_Address, c.getString(c.getColumnIndex(DBHandler.Key_Address)));
            i.putExtra(DBHandler.Key_Phone, c.getString(c.getColumnIndex(DBHandler.Key_Phone)));
            i.putExtra(DBHandler.Key_Website, c.getString(c.getColumnIndex(DBHandler.Key_Home)));
            startActivityForResult(i, CONTACT_EDIT);
    }
        protected void onActivityResult(int requestCode, int resultCode,
                Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (resultCode == RESULT_OK) {
                String name = data.getStringExtra(DBHandler.Key_Name);
                String address = data.getStringExtra(DBHandler.Key_Address);
                String mobile = data.getStringExtra(DBHandler.Key_Phone);
                String home = data.getStringExtra(DBHandler.Key_Home);
                switch (requestCode) {
                case CONTACT_CREATE:
                    Log.d("Your Location4", "jj:");
                    dbHelper.createRow(name, address, mobile, home);
                    Log.d("Your Location4", "ok90:");
                    fillData();
                    break;
                case CONTACT_EDIT:

                     String id = data.getStringExtra(DBHandler.Key_ID);


                     long rowId=Long.parseLong(id);

                    if (rowId != (Long)null){
                        dbHelper.updateRow(rowId, name, address, mobile, home);
                    }
                    fillData();
                    break;
                }
            }
        }
    }
    /////////////////////////////////////////////////

    public class ContactEdit extends Activity {

        protected EditText nameText;
        private EditText addressText;
        private EditText mobileText;
        private EditText homeText;
        public long rowId;
          Button submitButton;
          @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.d("database1" ,"button4");
            setContentView(R.layout.contact_edit);
            Log.d("database1" ,"button5");
            nameText = (EditText) findViewById(R.id.textName);
            addressText = (EditText) findViewById(R.id.textAddress);
            mobileText  = (EditText) findViewById(R.id.textMobile);
            homeText    = (EditText) findViewById(R.id.textHome);
            Button submitButton = (Button) findViewById(R.id.BtnSave);
            //long rowId = (Long) null;
            Intent extras = getIntent();
            Log.d("database1" ,"button5");

            if (extras != null){
                //get all the values for the corresponding keys
                String name = extras.getStringExtra(DBHandler.Key_Name);
                String address = extras.getStringExtra(DBHandler.Key_Address);
                String mobile = extras.getStringExtra(DBHandler.Key_Phone);
                String home = extras.getStringExtra(DBHandler.Key_Home);
            //  String id = extras.getStringExtra(DBHandler.Key_ID);
                //Log.d("database1" ,"button6");

            //   rowId=Long.parseLong(id.trim());
                // if (rowId != (Long)null)
                // {
                    // Log.d("foract","gact");
                 //}
                 //else {
                    // Log.d("foract","gactttt");
                 //}

                if (name !=null){
                    nameText.setText(name);
                }
                if (address != null){
                    addressText.setText(address);
                }
                if (mobile != null){
                    mobileText.setText(mobile);
                }
                if (home != null){
                    homeText.setText(home);
                }

            }


          submitButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v){
            //Intent bundle = new Bundle();
            Intent intent=new Intent();

            intent.putExtra(DBHandler.Key_Name, nameText.getText().toString());
            intent.putExtra(DBHandler.Key_Address, addressText.getText().toString());
            intent.putExtra(DBHandler.Key_Phone, mobileText.getText().toString());
            intent.putExtra(DBHandler.Key_Home, homeText.getText().toString());

              //  intent.putExtra(DBHandler.Key_ID, rowId);
         //   Log.d(DBHandler.Key_ID, rowId);
            setResult(RESULT_OK,intent);
            Log.e("what","result set");
            finish();
        }

        public void onClick(DialogInterface arg0, int arg1) {
            // TODO Auto-generated method stub

        }
    });
    }}
    //////////////////////////////////
    DBHANDLER CLASS///////////////////

    public class DBHandler extends SQLiteOpenHelper{

        private static final int DB_Version = 1;

        private static final String DB_Name = "Places";

        protected static final String Places_Table = "Places";

        String name, Address, Website,ID;
        //WebpreneurActivity Contact;
     public static final String Key_ID = "ID";
     public static final String Key_Name = "Name";
     public static final String Key_Phone = "Phone";
     public  static final String Key_Address = "Address";
     public static final String Key_Website = "Website";
     public  static final String Key_Home = "HOME";
     public static final String PROJECTION[] = {
        Key_ID,
        Key_Name,
        Key_Address,
        Key_Phone,
        Key_Home
    };

        String CREATE_PLACES_TABLE = "create table if not exists Places_Table (id integer primary key ,"+
                "name VARCHAR not null, phone VARCHAR not null, address VARCAHR not null, website VARCHAR not null,Home VARCHAR not null)";

        Context context;
        SQLiteDatabase db;

        public DBHandler(Context context) {

            super(context, DB_Name, null, DB_Version);
            Log.d("database1" ,"4");
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try{
                Log.d("DB", "DB creationnewwwww");
                    db.execSQL("CREATE TABLE  " + Places_Table + " (" +
                            Key_ID + " INT PRIMARY KEY NOT NULL,"+
                            Key_Name + " TEXT NOT NULL," +
                            Key_Phone + " TEXT NOT NULL," +
                            Key_Address + " TEXT NOT NULL," +
                            Key_Website + " TEXT," +
                            Key_Home + " TEXT)");
                    Log.d("DB", "DB creationnewwwwwwwwwwwwwwwwwwwwwwwwwww");
            }
            catch(SQLiteException e){
                Log.d("DB", "DB creation excptionhhhhhhhhhhhhhhh");
                e.printStackTrace();
            }

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

            db.execSQL("Drop Table If Exists" + Places_Table);
            onCreate(db);
        }

         /* void addContact() {
                SQLiteDatabase db = this.getWritableDatabase();

                ContentValues values = new ContentValues();
                values.put(Key_Name,Name); // Contact Name
                values.put(KEY_COST,cost); // Contact Phone
                values.put(Key_Address, contact.Address); //Contact phone no

                // Inserting Row
                db.insert(Places_Table, null, values);
                db.close(); // Closing database connection
            }*/

        public DBHandler open()
        {Log.d("DB", "DB creation 9");
         db = this.getWritableDatabase();
            //onCreate(db);
        Log.d("DB", "DB creation 9");
        return this;
        }
        public void close()
        {
            db.close();

        }

        //Adding Places 
        void addPlaces( int id, String name,String phone, String address,String url){

            Log.d("DB", "DB creation 1");
            //SinglePlaceActivity single = new SinglePlaceActivity();   Log.d("DB", "DB creation 2");
            ContentValues contentValues = new ContentValues();
            Log.d("DB", "DB creation 3");
            contentValues.put(Key_ID, id);
            Log.d("DB", "DB creation 4");
            contentValues.put(Key_Name, name);
            contentValues.put(Key_Phone, phone);
            contentValues.put(Key_Address, address);
            contentValues.put(Key_Website, url);
            Log.d("DB", "DB creation 4");
            db.insert(Places_Table, null, contentValues);
            Log.d("DB", "DB creation 5555");
            //db.close();
        }

        public String getdata() {
            // TODO Auto-generated method stub
            String [] columns =new String[]{Key_ID ,Key_Name,Key_Address,Key_Website};
            Cursor c =db.query(DB_Name, columns, null, null, null, null, null);
            String Result=""; 
            int iRow=c.getColumnIndex(Key_ID);
            int iName=c.getColumnIndex(Key_Name);
            int iAddress=c.getColumnIndex(Key_Address);
            int iWebsite=c.getColumnIndex(Key_Website);
            for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
                Result=Result+c.getString(iRow)+"    "+c.getString(iName)+ "  "+c.getString(iAddress)+ "   "+c.getString(iWebsite)+ "\n";
            }

            return Result;
        }   


        public void createRow(String name, String address, String Phone, String home)
        {
            ContentValues initialValues = new ContentValues();
            initialValues.put(Key_Name, name);
            initialValues.put(Key_Address, address);
            initialValues.put(Key_Phone, Phone);
            initialValues.put(Key_Home, home);
                    //pass the initialValues to the database to insert the row
            Log.d(Key_Home, home);
            db.insert(Places_Table, null, initialValues);
            Log.d("Your Location4", "okna:");
        }

            public void deleteRow(long rowId){
            db.delete(Places_Table, Key_ID+"="+rowId,null);
        }

            public boolean updateRow (long rowId, String name, String address, String Phone, String home){
            ContentValues args = new ContentValues();
            args.put(Key_Name, name);
            args.put(Key_Address, address);
            args.put(Key_Phone, Phone);
            args.put(Key_Home, home);
            return db.update(Places_Table, args, Key_ID +"="+ rowId, null)>0;
        }
            public Cursor fetchRow(long rowId) throws SQLException{
                Cursor result = db.query( Places_Table, null, 
                        Key_ID + "=" + rowId, null, null, null,null);
                if ((result.equals(rowId)) || !result.isFirst()) {
                    throw new SQLException("No note matching ID: " + rowId);
                }
                return result;
            }

            public Cursor fetchAllRows(){
                Log.d("Your Location4", "ok99:");
                return db.query(Places_Table, PROJECTION, 
                        null, null, null, null, null);

            }
    }
4

1 回答 1

0

只需执行以下操作。可能对你有用:

第一的 :

声明你的

  private static String DB_NAME="Database_Name";  
  private final Context context;  
  private String DB_PATH="";  
  private static int DB_VERSION=1;
  SQLiteDatabase db;

作为

private static SQLiteDatabase db;   

你的构造函数就像:

public DBHandler(Context context){
      super(context, DB_NAME, null,DB_VERSION);  
      this.context = context;  
      DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";  
  }

然后在访问 it.as 之前打开您的数据库:

public void open() throws SQLException{      
    //Open the database
    String myPath = DB_PATH + DB_NAME;
    db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);  
}

并在完成访问数据后将其关闭为:

@Override
public synchronized void close() { 
   if(db != null)
        db.close(); 
    super.close(); 
}

可能这会对你有所帮助。

于 2014-01-27T11:44:36.177 回答