2016-06-02 3 views
0

Я новичок в Android и SQLite. Я пытаюсь создать несколько таблиц в моей базе данных, где во-первых, я сохраняю данные электронной почты в базе данных, а затем через эту сохраненную электронную почту, я могу получить электронное письмо с сервера. Когда я пытаюсь сохранить эти данные электронной почты во второй таблице базы данных, он выбрасывает исключение нулевого указателя. Это происходит из-за заявления Sqlitedatabase db = this.writeabledatabase; alwasy становится нулевым, что означает, что база данных не может получить путь. Это мой код:Несколько таблиц базы данных в SQLite

package com.elevenvalues.baig.db2listviewupdatedeleteinsert; 
import android.content.ContentValues; 
import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 

import java.sql.SQLException; 


public class DbHelper extends SQLiteOpenHelper { 


// table name 
public static final String EMAIL_INSERT_TABLE = "EmailInsertDetail"; 
public static final String EMAIL_LOG = "EmailLog"; 
// Database Version 
private static final int DATABASE_VERSION = 1; 

// Database Name 
public static String DATABASE_NAME = "My database"; 

public static final String KEY_USERNAME = "username"; 
public static final String KEY_EMAIL = "email"; 
public static final String KEY_PASSWORD = "password"; 
public static final String KEY_SERVER = "server"; 
public static final String KEY_PORT = "port"; 
public static final String KEY_SECURITY_TYPE = "securityType"; 
public static final String KEY_ACTIVE_TIME = "activeTime"; 
public static final String KEY_ID = "id"; 

public static final String KEY_ROWID = "id"; 
public static final String KEY_FROM = "froom"; 
public static final String KEY_TO = "too"; 
public static final String KEY_MESSAGE_BODY = "messagebody"; 


SQLiteDatabase db; 
private boolean isUpdate; 
String id; 



public DbHelper(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 


} 

@Override 
public void onCreate(SQLiteDatabase db) { 


    String CREATE_TABLE = "CREATE TABLE " + EMAIL_INSERT_TABLE + " (" + KEY_ID + " INTEGER PRIMARY KEY, " 
      + KEY_USERNAME + " TEXT, " + KEY_EMAIL + " TEXT," + KEY_PASSWORD + " TEXT," + KEY_SERVER + " TEXT," + 
      KEY_PORT + " TEXT," + KEY_SECURITY_TYPE + " TEXT," + KEY_ACTIVE_TIME + " TEXT);"; 


    String CREATE_SERVER_DATABASE = "CREATE TABLE " + EMAIL_LOG + " (" + KEY_ROWID + " INTEGER PRIMARY KEY, " 
      + KEY_TO + " TEXT, " + KEY_FROM + " TEXT," + KEY_MESSAGE_BODY + " TEXT);"; 



    db.execSQL(CREATE_SERVER_DATABASE); 
    db.execSQL(CREATE_TABLE); 

} 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    db.execSQL("DROP TABLE IF EXISTS " + EMAIL_INSERT_TABLE); 

    db.execSQL("DROP TABLE IF EXISTS " + EMAIL_LOG); 

    // create new tables 
    onCreate(db); 

} 

    void EmailReadDataInsert(String from, String too, String messageBody) { 


    db=this.getWritableDatabase(); 
    ContentValues cv = new ContentValues(); 
    cv.put(DbHelper.KEY_FROM, from); 
    cv.put(DbHelper.KEY_TO, too); 
    cv.put(DbHelper.KEY_MESSAGE_BODY, messageBody); 
    // Inserting Row 
    db.insert(EMAIL_LOG, null, cv); 

    } 


    /** 
    * save data into SQLite 
    */ 
    public void AddEmailData(String username,String email,String password,String server,String port,String securityType, 
    String activeTime) { 
    db = this.getWritableDatabase(); 
    ContentValues values = new ContentValues(); 

    values.put(DbHelper.KEY_USERNAME, username); 
    values.put(DbHelper.KEY_EMAIL, email); 
    values.put(DbHelper.KEY_PASSWORD, password); 
    values.put(DbHelper.KEY_SERVER, server); 
    values.put(DbHelper.KEY_PORT, port); 
    values.put(DbHelper.KEY_SECURITY_TYPE, securityType); 
    values.put(DbHelper.KEY_ACTIVE_TIME, activeTime); 

    if (isUpdate) { 
     //update database with new data 
     db.update(DbHelper.EMAIL_INSERT_TABLE, values, DbHelper.KEY_ID + "=" + id, null); 
    } else { 
     //insert data into database 
     db.insert(DbHelper.EMAIL_INSERT_TABLE, null, values); 
    } 
    //close database 
    db.close(); 

    } 


    //---opens the database--- 
    public DbHelper open() throws SQLException 
    { 
    db = this.getWritableDatabase(); 
    return this; 
    } 


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

} 

Проблема возникает в этом методе, где db становится нулевым:

void EmailReadDataInsert(String from, String too, String messageBody) { 


    db=this.getWritableDatabase(); 
    ContentValues cv = new ContentValues(); 
    cv.put(DbHelper.KEY_FROM, from); 
    cv.put(DbHelper.KEY_TO, too); 
    cv.put(DbHelper.KEY_MESSAGE_BODY, messageBody); 
    // Inserting Row 
    db.insert(EMAIL_LOG, null, cv); 

    } 

Как решить мою проблему? Какие-либо предложения?

+0

Попробуйте избавиться от линии: db.close(); –

ответ

0

Если вы пытаетесь создать несколько таблиц в базе данных, вам не обязательно всегда создавать новую базу данных. Ваш класс, который управляет записями в вашей базе данных, должен быть слегка изменен, чтобы обеспечить обе таблицы. Попытка добавить этот код вместо:

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 

public class Database { 
    static final String databaseName = "My database"; 
    static final int databaseVersion = 0; 
    static final String rowId = “id”; 
    static final String rowUsername = “username”; 
    static final String rowEmail = “email”; 
    static final String rowPassword = "password"; 
    static final String rowServer = “server”; 
    static final String rowPort = "port"; 
    static final String rowSecurityType = "securityType"; 
    static final String rowActiveTime = "activeTime"; 

    static final String emailTable = "EmailInsertDetail"; 
    static final String logTable = "EmailLog"; 

    static final String rowFrom = "from"; 
    static final String rowTo = "to"; 
    static final String rowMessage = "message"; 
    final Context context; 

    SqlLiteDatabase database; 
    DatabaseHelper helper; 

    public Database(Context context) { 
     this.context = context; 
     this.helper = new DatabaseHelper(context); 
    } 

    private static class DatabaseHelper extends SQLiteOpenHelper { 
     DatabaseHelper(Context context) { 
      super(context, databaseName, null, databaseVersion); 
     } 

     @Override 
     public void onCreate(SQLiteDatabase database) { 
      try { 
       database.execSQL("CREATE TABLE IF NOT EXISTS " + emailTable); 
       database.execSQL("CREATE TABLE IF NOT EXISTS " + logTable); 
      } catch (SQLException ex) { 
        ex.printStackTrace(); 
      } 
     } 

     @Override 
     public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { 
      Log.w("Database", “Upgrading database from version “ + oldVersion + “ to “ + newVersion + “, which will destroy all old data”); 
      db.execSQL(“DROP TABLE IF EXISTS " + emailTable + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT, password TEXT, server TEXT, port TEXT, securityType TEXT, activeTime TEXT)"); 
      db.execSQL("DROP TABLE IF EXISTS " + logTable + " (id INTEGER PRIMARY KEY AUTOINCREMENT, from TEXT, to TEXT, message TEXT)"); 
      onCreate(database); 
     } 
    } 

    public Database open() throws SQLException { 
     this.database = DatabaseHelper.getWritableDatabase(); 
     return this; 
    } 

    public void close() { 
     DatabaseHelper.close(); 
    } 

    public long insertEmail(String username, String email, String password, String server, String port, String securityType, String activeTime) { 
     ContentValues contentValues = new ContentValues(); 

     contentValues.put(rowUsername, username); 
     contentValues.put(rowEmail, email); 
     contentValues.put(rowPassword, password); 
     contentValues.put(rowServer, server); 
     contentValues.put(rowPort, port); 
     contentValues.put(rowSecurityType, securityType); 
     contentValues.put(rowActiveTime, activeTime); 

     return database.insert(emailTable, null, contentValues); 
    } 

    public long insertData(String from, String to, String message) { 
     ContentValues contentValues = new ContentValues(); 

     contentValues.put(rowFrom, from); 
     contentValues.put(rowTo, to); 
     contentValues.put(rowMessage, message); 

     return database.insert(logTable, null, contentValues); 
    } 

    public boolean updateEmail(long id, String username, String email, String password, String server, String port, String securityType, String activeTime) { 
     ContentValues contentValues = new ContentValues(); 

     contentValues.put(rowUsername, username); 
     contentValues.put(rowEmail, email); 
     contentValues.put(rowPassword, password); 
     contentValues.put(rowServer, server); 
     contentValues.put(rowPort, port); 
     contentValues.put(rowSecurityType, securityType); 
     contentValues.put(rowActiveTime, activeTime); 

     return database.update(emailTable, contentValues, rowId + "=" + id, null) > 0; 
    } 

    public boolean updateEmail(long id, String from, String to, String message) { 
     ContentValues contentValues = new ContentValues(); 

     contentValues.put(rowFrom, from); 
     contentValues.put(rowTo, to); 
     contentValues.put(rowMessage, message); 

     return database.update(logTable, contentValues, rowId + "=" + id, null) > 0; 
    } 

    public Cursor getAllEmails() { 
     return database.query(emailTable, new String[] {rowId, rowUsername, rowEmail, rowPassword, rowServer, rowPort, rowSecurityType, rowActiveTime}, null, null, null, null, null); 
    } 

    public Cursor getAllData() { 
     return database.query(logTable, new String[] {rowId, rowFrom, rowTo, rowMessage}, null, null, null, null, null); 
    } 

    public Cursor getEmail(long id) throws SQLException { 
     Cursor cursor = db.query(true, emailTable, new String[] {rowId, rowUsername, rowEmail, rowPassword, rowServer, rowPort, rowSecurityType, rowActiveTime}, rowId + “=” + id, null, null, null, null, null); 

     if (cursor != null) { 
      cursor.moveToFirst(); 
     } 
     return cursor; 
    } 

    public Cursor getData(long id) throws SQLException { 
     Cursor cursor = db.query(true, logTable, new String[] {rowId, rowFrom, rowTo, rowMessage}, rowId + “=” + id, null, null, null, null, null); 

     if (cursor != null) { 
      cursor.moveToFirst(); 
     } 
     return cursor; 
    } 
} 

В деятельности или классе, который вы хотите вставить или извлечь данные, тип:

Database database = new Database(context); 
database.open(); 

// To insert whatever data you want 
long insert = database.insertEmail(parametres go in here); 

// To update whatever data you want 
if (database.updateEmail(the parametres)) 
    // more code to be executed 

// To retrieve all items in a table 
Cursor cursor = database.getAllEmails(); 

if (cursor.moveToFirst()) { 
    do { 
     Toast.makeText(this, "Id: " + cursor.getInt(0) + " Email: " + cursor.getString(2), Toast.LENGTH_SHORT).show(); 
    } while (cursor.moveToNext(); 
} 

// To retrieve a certain item 
Cursor cursor = database.getEmail(the id); 
    Toast.makeText(this, "Id: " + cursor.getInt(0) + " From: " + cursor.getString(1), Toast.LENGTH_SHORT).show(); 
if (cursor.moveToFirst()) { 

} 

database.close(); 

Не забудьте заменить context либо this, getContext() или переменной Context. Не забудьте заменить операторы Toast собственным кодом. Если у вас все еще есть проблемы, обязательно обратитесь к this eBook, которые должны помочь вам или оставить комментарии ниже.

Смежные вопросы