Android调用已有sqlite数据库登录帐号

准备做一个使用已用的sqlite数据库登录帐号,,这就得自己创建一个数据库然后移动数据库,看了很多都是通过先创建数据库再打开数据库然后查询实现登录注册的功能,但是我们项目要求只登陆不注册,而且先创建数据库再打开数据库会把帐号密码都给看出来了,那也太不专业了,为了体现自己的专业水平,只好自己动手操作了。

首先遇到的问题就是怎么把sqlite studio(一款sqlite可视化软件,网上教程很多自己搜)创建的数据库移动到项目上来,首先得把创建的数据库移动到res/raw文件夹下,再创建一个MyDatabaseHelper类,在里面使用File类实现文件移动,详细过程如下代码所示:

public class MyDatabaseHelper {
    private final int BUFFER_SIZE = 400000;
    public static final String DB_NAME = "mydatabase.db"; //保存的数据库文件名
    public static final String PACKAGE_NAME = "com.example.expert6";//包名
    public static final String DB_PATH = "/data"
            + Environment.getDataDirectory().getAbsolutePath() + "/"
            + PACKAGE_NAME + "/databases";  //存放数据库的位置
    private SQLiteDatabase database;
    private Context context;
    MyDatabaseHelper(Context context){
        this.context = context;
    }

    public void openDatabase() {
        File dFile=new File(DB_PATH);//判断路径是否存在,不存在则创建路径
        if (!dFile.exists()) {
            dFile.mkdir();
        }
        this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
    }
    private SQLiteDatabase openDatabase(String dbfile) {
        try {
            if (!(new File(dbfile).exists())) {
                InputStream is = this.context.getResources().openRawResource(
                        R.raw.mydatabase); //欲导入的数据库
                FileOutputStream fos = new FileOutputStream(dbfile);
                byte[] buffer = new byte[BUFFER_SIZE];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
                    null);
            return db;
        }catch (FileNotFoundException e) {
            Log.e("Database", "File not found");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("Database", "IO exception");
            e.printStackTrace();
        }
        return null;
    }

    public String QuerySQL(String str1,String str2) {

        String result = "";
        try{
            Cursor cursor = database.rawQuery("select username from users  where passwd=? " +
                    "and  username=? ", new String[]{str2,str1 });
            if (cursor.moveToNext())
            {
                result= "1" ;
            }
            cursor.close();
            database.close();

        }
        catch (SQLException e)
        {
            e.printStackTrace();
            result += "查询数据异常!" + e.getMessage();
        }
        return result;
    }
    public void closeDatabase()
    {
        this.database.close();
    }
}

 这只是第一步,还得创建一个MainActivity类实现登录账号的功能。首先在OnCreate实例化 MyDatabaseHelper对象再  调用该类中的databaseHelper.openDatabase(),打开数据库,最后才是首先按钮的点击事件。主程序代码如下:

/**
 * 主Activity为控制类,用于控制界面的显示
 */
public class MainActivity extends Activity {
    private static final String TAG = "LifeCycleActivity";
    private Context context = this;
    private int param = 1;
    MyDatabaseHelper databaseHelper;
    private EditText username;  //接收用户输入的用户名
    private EditText passwd;    //接收用户输入的密码
    //Activity创建时被调用
    @Override
    public void onCreate(Bundle savedInstanceState) {
        databaseHelper=new MyDatabaseHelper(this);//实例化MyDatabaseHelper
        databaseHelper.openDatabase();//打开数据库
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        username = (EditText) findViewById(R.id.username);
        passwd = (EditText) findViewById(R.id.passwd);
        Button btn = (Button) findViewById(R.id.but_login);
        Button btn1 = (Button) findViewById(R.id.but_clear);
        SQLiteStudioService.instance().start(this);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username.setText("");
                passwd.setText("");
            }
        });
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MassegeActivity.class);
                //绑定数据
                String str1=username.getText().toString();//获取帐号
                String str2=passwd.getText().toString();//获取密码

                String ret = databaseHelper.QuerySQL(str1,str2);
                if(ret.equals("1")) {
                    startActivity(intent);
                    finish();
                    //下面跳转问卷界面
                }
                else {
                    Toast.makeText(MainActivity.this,"用户名或密码错误",
                            Toast.LENGTH_SHORT).show();//事件触发,显示登录失败
                }
            }
        });

    }

    protected void onDestroy() {
        // TODO Auto-generated method stub
        SQLiteStudioService.instance().stop();
        super.onDestroy();
    }

}

如果你直接在网上复制先创建数据库再打开然后在主程序调用MyDatabaseHelper的的QuerySQL方法会出现空对象的情况,主要原因是对象混乱,乱调用对象,根本就没有引用创建数据库的方法,只是实例化,也没有打开数据库当然就会出现空对象的情况,我就是一直在这卡壳,老是以为只要复制了代码就没事了,看来以后还得多分析啊

在这耗费了很多时间,今天记录下来提醒自己,希望对你们有帮助。

有需要源码的自行下载

源码

猜你喜欢

转载自blog.csdn.net/qq_45098495/article/details/107074461
今日推荐