2013-10-30 15 views
0

我必须在我的Android应用程序中使用SQLite数据库实现登录应用程序。首先,我创建了注册数据库,并在表中插入了值,并且我已经完成了这一点。并且当我首先运行我的应用程序时,我成功注册并在数据库中插入数据,然后我登录数据没有收到它显示错误NullPointerException这里是我的代码。如何在Android中从sqlite获取数据?

public class DataBaseHandller extends SQLiteOpenHelper 

{ 

    public DataBaseHandller(Context context) 
    { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     // TODO Auto-generated constructor stub 
    } 

    // All Static variables 
    // Database Version 
    private static final int DATABASE_VERSION = 1; 

    // Database Name 
    private static final String DATABASE_NAME = "LeadManagment"; 

    // table's name 
    private static final String TABLE_REGISTER = "registration"; 
// Register Table Columns names 
    private static final String KEY_ID = "id"; 
    private static final String KEY_NAME = "name"; 
    private static String KEY_EMAIL = "email"; 
    private static final String KEY_PIN = "pin"; 

@Override 
    public void onCreate(SQLiteDatabase db) 
    { 
     String CREATE_REGISTER_TABLE = "CREATE TABLE " + TABLE_REGISTER + "(" 
     + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," 
     + KEY_EMAIL + " TEXT," + KEY_PIN + " TEXT" + ")"; 
     db.execSQL(CREATE_REGISTER_TABLE); 
} 


@Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // Drop older table if existed 
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER); 


    // Create tables again 
    onCreate(db); 
    } 


/** 
    * All CRUD(Create, Read, Update, Delete) Operations 
    */ 

    // Adding new contact Or Insert Field In TableS 
    public void Add_Contact(Register_BeanClass register_Bean) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    ContentValues insert_ContentValues = new ContentValues(); 
    insert_ContentValues.put(KEY_NAME, register_Bean.get_name()); 
    insert_ContentValues.put(KEY_EMAIL, register_Bean.get_email()); 
    insert_ContentValues.put(KEY_PIN, register_Bean.get_pin()); 
    // Inserting Row 
    db.insert(TABLE_REGISTER, null, insert_ContentValues); 
    db.close(); // Closing database connection 
    } 

    //Get Single Antry 
    public String getSinlgeEntry(String userName) 
    { 
     SQLiteDatabase db = this.getReadableDatabase(); 
     Cursor cursor=db.query(TABLE_REGISTER, null, KEY_EMAIL +="?", new String[]{userName}, null, null, null); 
     if(cursor.getCount()<1) // UserName Not Exist 
     { 
      cursor.close(); 
      return "NOT EXIST"; 
     } 
     cursor.moveToFirst(); 
     String password= cursor.getString(cursor.getColumnIndex(KEY_PIN)); 
     cursor.close(); 
     return password;     
    } 



    // Getting All Contacts 
    public ArrayList<Register_BeanClass> Get_Contacts() 
    { 

     try 
     { 

     register_list.clear(); 

     // Select All Query 
     String selectQuery = "SELECT * FROM " + TABLE_REGISTER; 

     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     // looping through all rows and adding to list 
     if (cursor.moveToFirst()) 
     { 
     do 
      { 

      Register_BeanClass contact = new Register_BeanClass(); 

      contact.setId(Integer.parseInt(cursor.getString(0))); 
      contact.set_name(cursor.getString(1)); 
      contact.set_email(cursor.getString(2)); 
      contact.set_pin(cursor.getString(3)); 

      register_list.add(contact); 


     } while (cursor.moveToNext()); 

    } 

     // return contact list 
     cursor.close(); 
     db.close(); 
     return register_list; 
    } 

    catch (Exception e) 
    { 
     // TODO: handle exception 
     Log.e("all_contact", "" + e); 
    } 

    return register_list; 
    } 


    // Updating single contact 
    public int Update_RegisterField(Register_BeanClass update_Register_BeanClass) { 
    SQLiteDatabase db = this.getWritableDatabase(); 

    ContentValues updateContentvalues = new ContentValues(); 
    updateContentvalues.put(KEY_NAME, update_Register_BeanClass.get_name()); 
    updateContentvalues.put(KEY_EMAIL, update_Register_BeanClass.get_email()); 
    updateContentvalues.put(KEY_PIN, update_Register_BeanClass.get_pin()); 

    // updating row 
    return db.update(TABLE_REGISTER, updateContentvalues, KEY_ID + " = ?", 
     new String[] { String.valueOf(update_Register_BeanClass.getId()) }); 
    } 


    // Deleting single contact 
    public void Delete_Contact(int id) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    db.delete(TABLE_REGISTER, KEY_ID + " = ?", 
     new String[] { String.valueOf(id) }); 
    db.close(); 
    } 



    // Getting contacts Count 
    public int Get_Total_Contacts() { 
    String countQuery = "SELECT * FROM " + TABLE_REGISTER; 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor cursor = db.rawQuery(countQuery, null); 
    cursor.close(); 

    // return count 
    return cursor.getCount(); 
    } 

} 



    public class Registration_Activity1 extends Activity 
    { 
     TextView eText_TotalRecord; 
     EditText editTextUserName,editTextEmailId , editTextPin,editTextConfirmPin; 
     Button btnCreateAccount; 
     Button btnViewDetails; 

     DataBaseHandller dbHandller=new DataBaseHandller(this); 


     public void onCreate(Bundle savedInstanceState) 
     { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.registration_activity1); 


      editTextUserName = (EditText) findViewById(R.id.editText_regName); 
      editTextEmailId = (EditText) findViewById(R.id.editText_regEmail); 
      editTextPin = (EditText) findViewById(R.id.editText_regApp_Pin); 
      editTextConfirmPin = (EditText) findViewById(R.id.editText_regConfirm_App_Pin); 

      eText_TotalRecord=(TextView)findViewById(R.id.etext_totalRecord); 


      btnCreateAccount=(Button)findViewById(R.id.reg_btnSubmit); 
      btnCreateAccount.setOnClickListener(new OnClickListener() { 

       @SuppressWarnings("unused") 
       @Override 
       public void onClick(View arg0) { 
        // TODO Auto-generated method stub 

        String userName=editTextUserName.getText().toString(); 
        String userEmail=editTextEmailId.getText().toString(); 
        String userPin=editTextPin.getText().toString(); 
        String userConfirmPin=editTextConfirmPin.getText().toString(); 


        // check if any of the fields are vaccant 
        if(userName.equals("")||userEmail.equals("")||userPin.equals("")||userConfirmPin.equals("")) 
        { 
          Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show(); 
          return; 
        } 
        // check if both password matches 
        if(!userPin.equals(userConfirmPin)) 
        { 
         Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show(); 
         return; 
        } 
        else 
        { 
         // Save the Data in Database 
         dbHandller.Add_Contact(new Register_BeanClass(0, userName,userEmail,userPin)); 

         Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show(); 
        } 
       } 
      }); 


btnLogin=(Button) findViewById(R.id.btn_Login); 
     btnLogin.setOnClickListener(new OnClickListener() 
     { 

      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 

       str_EmailId=editText_Email.getText().toString().trim(); 
       str_AppPin=editText_App_Pin.getText().toString().trim(); 

       // fetch the Password form database for respective user name 
       String storedApplication=db.getSinlgeEntry(str_AppPin); 


       if(str_AppPin.equals(storedApplication)) 
       { 
        Toast.makeText(Application_Pin_Activity2.this,"Access Allow", Toast.LENGTH_LONG).show(); 
       } 

       else 
       { 
        Toast.makeText(Application_Pin_Activity2.this, "Sorry ! Wrong Pin", Toast.LENGTH_LONG).show(); 
       } 


      } 
     }); 

} 
+0

你就可以用光标计数资料... –

+0

日志猫将有助于 – Nezam

+1

我认为这个问题是在' Get_Total_Contacts()'。关闭'Cursor',然后尝试返回已经关闭的cursor.getCount(),导致'NullPointerException'。编辑:它似乎尚未使用,所以这是不太可能的原因,但可能会稍后,如果没有改变... –

回答

0

我建议你在这个类之外进行查询。

DataBaseHandller dbHelper= new DataBaseHandller (this, "DB_NAME", null, 1); 
SQLiteDatabase db = dbHelper.getWritableDatabase(); 

...

而当你粘贴有相同的代码。

1

我建议使用不同的clases用于不同的目的。为了简单起见,我认为你在这里张贴全班。

你应该有一个类助手来创建/升级你的数据库。它是这样的:

public class MainDatabaseHelper extends SQLiteOpenHelper { 

    private static MainDatabaseHelper mInstance = null; 

    private static final String DATABASE_NAME = "persistence.db"; 
    private static final int DATABASE_VERSION = 1; 

    public static MainDatabaseHelper getInstance(Context context) { 

     if (mInstance == null) { 
      mInstance = new MainDatabaseHelper(context.getApplicationContext()); 
     } 
     return mInstance; 
    } 

    private MainDatabaseHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     System.out.println("main database helper created, private constructor"); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase database) { 
     DB_BarTable.onCreate(database); 
     DB_FooTable.onCreate(database); 

    } 

    @Override 
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { 
     DB_FooTable.onUpgrade(database, oldVersion, newVersion); 
     DB_Bar_LINETable.onUpgrade(database, oldVersion, newVersion); 

    } 
} 

之后,包裹每一个类中的一类,像这样:

public class DB_FooTable { 
    public static final String TABLE_NAME = "foo"; 
    public static final String COLUMN_ID = "id"; 
    public static final String COLUMN_NAME = "name"; 

    // TODO foreign keys 
    public static final String DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" 
      + COLUMN_IDHIDDEN + " integer primary key autoincrement," + COLUMN_ID + " integer," + COLUMN_NAME+ " text);"; 

    public static void onCreate(SQLiteDatabase database) { 
     database.execSQL(DATABASE_CREATE); 
     Log.i(Constants.TAG, "Creating database " + TABLE_NAME); 
    } 

    public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { 
     Log.w(Constants.TAG, "Upgrading database from version " + oldVersion + " to " + newVersion 
       + ", which will destroy all old data"); 
     database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); 
     onCreate(database); 
    } 

} 

最后,使用DAO(数据访问对象)来访问不同的哟数据层。 一个例子可以是这样:

public class FooDAO { 
    public static final int MAX_RESULTS = 30; 

    public Future<List<Foo>> getAll(final Context context, final int pagination) { 

     Callable<List<Foo>> c = new Callable<List<Foo>>() { 

      @Override 
      public List<Foo> call() { 

       MainDatabaseHelper dbHelper = MainDatabaseHelper.getInstance(context); 
       ArrayList<Foo> items = new ArrayList<Foo>(); 

       SQLiteDatabase db = dbHelper.getWritableDatabase(); 

       Cursor cursor = null; 

       // No parameters, load MAX_RESULTS first items 
       if (pagination < 1) { 
        cursor = db.query(DB_FooTable.TABLE_NAME, null, null, null, null, null, 
          null, String.valueOf(MAX_RESULTS)); 


       while (cursor.moveToNext()) { 
        Foo o = new Foo(); 
        o.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DB_FooTable.COLUMN_ID))); 
        o.setName(cursor.getString(cursor.getColumnIndexOrThrow(DB_FooTable.COLUMN_NAME))); 

        items.add(o); 
       } 
       return items; 
      }; 
     }; 
     ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor(); 
     return s.submit(c); 
    } 


    public void delete(final Context context, final long idToDelete) { 

     Log.i(Constants.TAG, "onDeleteItem single" + idToDelete); 
     Thread t = new Thread(new Runnable() { 

      @Override 
      public void run() { 
       long idDeleted = -1; 

       MainDatabaseHelper dbHelper = MainDatabaseHelper.getInstance(context); 
       SQLiteDatabase db = dbHelper.getWritableDatabase(); 
       idDeleted = db.delete(DB_FooTable.TABLE_NAME, DB_FooTable.COLUMN_ID + " = " + idToDelete, 
         null); 

       Log.i(Constants.TAG, "ITEM DELETED, id " + idDeleted); 
      } 
     }); 
     t.start(); 
    } 

    public Future<Long> insert(final Context context, final Foo p) { 

     Callable<Long> c = new Callable<Long>() { 

      @Override 
      public Long call() throws Exception { 
       long id = -1; 

       ContentValues cv = new ContentValues(); 
       cv.put(DB_FooTable.COLUMN_ID, p.getId()); 
       cv.put(DB_FooTable.COLUMN_NAME, p.getName()); 

       MainDatabaseHelper dbHelper = MainDatabaseHelper.getInstance(context); 
       SQLiteDatabase db = dbHelper.getWritableDatabase(); 
       id = db.insert(DB_FooTable.TABLE_NAME, "<empty>", cv); 

       return id; 
      }; 
     }; 
     ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor(); 
     return s.submit(c); 
    } 

} 

希望它可以帮助!

显然,你需要一个业务对象您封装的结果!(类Foo这里)

2
DBhelper dbhlpr; 
Context mContext; 
SQLiteDatabase db; 
ArrayList<String> results; 

    results = new ArrayList<String>(); 
    mContext = getApplicationContext(); 
    dbhlpr = new DBhelper(mContext); 
    db = dbhlpr.getWritableDatabase(); 

Cursor c = db.rawQuery("SELECT name, phone FROM friends",null); 
//Here name and phone are the field name and friends is the table name 

if (c != null) 
{ 

if (c.moveToFirst()) 

{ 

do 
    { 
    String name = c.getString(c.getColumnIndex("name")); 
    int phone = c.getInt(c.getColumnIndex("phone")); 
    results.add("name " + name + ",phone: " + phone); 
    //In results we are adding the data from database 
    Toast.makeText(Data.this, "Name...."+name+" Phone...."+phone, 10000).show(); 
    } while (c.moveToNext()); 
} 
} 
相关问题