我有一个LoginActivity.java
package com.example.teachify;
/**
* Created by Sayan on 8/24/13.
*/
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;
import android.database.Cursor;
import android.widget.EditText;
public class LoginActivity extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
Button btnCancel;
UserDetails udt;
private DataBaseManager dataBase;
String strDetails;
DatabaseHandler db = new DatabaseHandler(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
//creates and open the database so we can use it
dataBase = DataBaseManager.instance();
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
txtUserName=(EditText)this.findViewById(R.id.txtUserName);
txtPassword=(EditText)this.findViewById(R.id.txtPassword);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
i.putExtra("extra", txtUserName.getText().toString());
startActivityForResult(i,0);
}
});
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Cursor cursor=null;
try {
cursor = dataBase.select("SELECT UserName,Password FROM User WHERE UserName='" + txtUserName.getText().toString() + "'");
}
catch( SQLException e) {
strDetails="";
if (cursor == null){
cursor.close();
}
else {
cursor.moveToFirst();
strDetails=cursor.getString(0);
cursor.close();
}
if((txtUserName.getText().toString()).equals(strDetails)){
Toast.makeText(LoginActivity.this, "Login Successful",Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginActivity.this, e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
});
}
}
DataBaseManager.java
package com.example.teachify;
/**
* Created by Sayan on 9/5/13.
*/
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DataBaseManager extends SQLiteOpenHelper {
// The Android's default system path of your application database.
//data/data/ and /databases remain the same always. The one that must be changed is com.example which represents
//the MAIN package of your project
private static String DB_PATH = "/data/data/com.example.teachify/databases/";
//the name of your database
private static String DB_NAME = "user";
private static SQLiteDatabase mDataBase;
private static DataBaseManager sInstance = null;
// database version
private static final int DATABASE_VERSION = 1;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*/
private DataBaseManager() {
super(ApplicationContextProvider.getContext(), DB_NAME, null, DATABASE_VERSION);
try {
createDataBase();
openDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Singleton for DataBase
*
* @return singleton instance
*/
public static DataBaseManager instance() {
if (sInstance == null) {
sInstance = new DataBaseManager();
}
return sInstance;
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
*
* @throws java.io.IOException io exception
*/
private void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method an empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error(e.toString());
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database doesn't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
*
* @throws java.io.IOException io exception
*/
public void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = ApplicationContextProvider.getContext().getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
private void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
mDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
/**
* Select method
*
* @param query select query
* @return - Cursor with the results
* @throws android.database.SQLException sql exception
*/
public Cursor select(String query) throws SQLException {
return mDataBase.rawQuery(query, null);
}
/**
* Insert method
*
* @param table - name of the table
* @param values values to insert
* @throws android.database.SQLException sql exception
*/
public void insert(String table, ContentValues values) throws SQLException {
mDataBase.insert(table, null, values);
}
/**
* Delete method
*
* @param table - table name
* @param where WHERE clause, if pass null, all the rows will be deleted
* @throws android.database.SQLException sql exception
*/
public void delete(String table, String where) throws SQLException {
mDataBase.delete(table, where, null);
}
/**
* Update method
*
* @param table - table name
* @param values - values to update
* @param where - WHERE clause, if pass null, all rows will be updated
*/
public void update(String table, ContentValues values, String where) {
mDataBase.update(table, values, where, null);
}
/**
* Let you make a raw query
*
* @param command - the sql comand you want to run
*/
public void sqlCommand(String command) {
mDataBase.execSQL(command);
}
@Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
但是当我在模拟器中执行此操作时:AVD_for_Nexus_by_Google 我收到了错误 没有这样的表
我做了一张桌子。任何人都可以帮助我......
答案 0 :(得分:1)
我遇到了同样的问题。我通过使用下面的方法而不是使用getWritableDatabase()来获取Databse实例
来解决它public SQLiteDatabase opendatabase(){
try{
String mypath = DB_PATH + DB_NAME;
database = SQLiteDatabase.openDatabase(mypath, null,SQLiteDatabase.OPEN_READWRITE);
}catch(SQLiteException sle){
System.out.println("Exception while opning database : "+sle);
}
return database;
}
因为getWritableDatabase()方法给出了空实例,因为它指向不同的数据库位置实际上我们的数据库没有从资产文件夹中复制。
答案 1 :(得分:0)
SQLiteOpenHelper
将自动创建一个空数据库。
checkDataBase
函数仅检查数据库文件是否存在,但是如果它包含所需的表则不检查。
使用SQLiteOpenHelper
时,您应该在onCreate
函数中创建数据库。