当前位置: 首页 > 知识库问答 >
问题:

无法使用Android Studio 2.1从SQLite数据库获取值

孙承弼
2023-03-14

我试图使用SQLite建立一个数据库来存储用户名和密码,但每当我在模拟器上注册一个帐户时,它就会出错。此外,如果我只是尝试登录而没有注册,它将出错。这只是我的第二篇帖子,所以如果我在发帖时有什么可以做得更好的,请告诉我!

public class DbHelper extends SQLiteOpenHelper {
private static String DbName = "SimpleDatabase";
private static int DbVersion = 1;

//Table Names
private static final String TABLE_USER = "User";

//Column Names
private static final String USER_NAME = "UserName";
private static final String PASSWORD = "Password";

//Create statements
// Todo table create statement
private static final String CREATE_TABLE_USER = "CREATE TABLE " 
        + TABLE_USER + "(" + USER_NAME + "TEXT PRIMARY KEY," 
        + PASSWORD + "TEXT)" ;

public DbHelper(Context context) {
    super(context, DbName, null, DbVersion);
}


@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE_USER);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXIST "+TABLE_USER);
    onCreate(db);
}

public Boolean InsertUser(String userName,String password){
    SQLiteDatabase db = this.getWritableDatabase();

    String query = "SELECT * FROM "+TABLE_USER+" WHERE "+USER_NAME+" == '"+userName+"';";
    Cursor c = db.rawQuery(query,null);
    if(c != null && c.moveToFirst()) {
        c.close();
        return false ;

    }else{
        ContentValues values = new ContentValues();
        values.put(USER_NAME, userName);
        values.put(PASSWORD, password);

        db.insert(TABLE_USER, null, values);
        return true;
    }
}

public Boolean loginUser(String userName,String password){

    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT * FROM "+TABLE_USER+" WHERE "+USER_NAME+" == '"+userName+"' AND "+PASSWORD+" == '"+password+"';";
    Cursor c = db.rawQuery(query,null);
    if(c != null && c.moveToFirst()) {
        c.close();
        return true;
    }
    return false;
}

}

下面是DbHelper附带的登录类

public class Login extends Fragment {

TextInputLayout usernamelayout, passwordLayout;
EditText userName,password;
Button login, goToRegister;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.content_login,container,false);
}

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    usernamelayout = (TextInputLayout)view.findViewById(R.id.user_name_layout);
    passwordLayout = (TextInputLayout)view.findViewById(R.id.password_layout);
    userName = (EditText)view.findViewById(R.id.user_name);
    password = (EditText)view.findViewById(R.id.password);
    login = (Button)view.findViewById(R.id.login_button);
    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String userText = userName.getText().toString().trim();
            String passwordText = password.getText().toString().trim();
            if (userText.isEmpty()) {
                usernamelayout.setErrorEnabled(true);
                usernamelayout.setError("Please Enter User Name");

            } else if (passwordText.isEmpty()) {
                passwordLayout.setErrorEnabled(true);
                passwordLayout.setError("Please Enter Password");
            } else {
                DbHelper helper = new DbHelper(getActivity());
                if (helper.loginUser(userText, passwordText)) {
                    startActivity(new Intent(getActivity(), MainActivity.class));
                } else {
                    Toast.makeText(getActivity(), "User Name or Password is incorrect", Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
    goToRegister = (Button)view.findViewById(R.id.go_to_register_button);
    goToRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Register fragment = new Register();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                setSharedElementReturnTransition(TransitionInflater.from(getActivity()).inflateTransition(R.transition.change_image_trans));
                setExitTransition(TransitionInflater.from(getActivity()).inflateTransition(android.R.transition.fade) );
                fragment.setSharedElementEnterTransition(TransitionInflater.from(getActivity()).inflateTransition(R.transition.change_image_trans));
                fragment.setEnterTransition(TransitionInflater.from(getActivity()).inflateTransition(android.R.transition.fade));

            }

            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.addSharedElement(view.findViewById(R.id.logo),"LOGO");
            transaction.replace(R.id.main_container, fragment);
            transaction.commit();
        }
    });
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getActivity().setTitle("Uhvents Login");
}

}

这里是REGISTER类。

public class Register extends Fragment {

TextInputLayout usernamelayout, passwordLayout;
EditText userName,password;
Button register, goToLogin;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.content_register,container,false);
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    usernamelayout = (TextInputLayout) view.findViewById(R.id.user_name_layout);
    passwordLayout = (TextInputLayout) view.findViewById(R.id.password_layout);
    userName = (EditText) view.findViewById(R.id.user_name);
    password = (EditText) view.findViewById(R.id.password);

    register = (Button) view.findViewById(R.id.register_button);
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String userText = userName.getText().toString().trim();
            String passwordText = password.getText().toString().trim();
            if(userText.isEmpty()) {
                usernamelayout.setErrorEnabled(true);
                usernamelayout.setError("Please Enter User Name");

            }
            else if (passwordText.isEmpty()){
                passwordLayout.setErrorEnabled(true);
                passwordLayout.setError("Please Enter Password");

            }
            else {

                DbHelper helper = new DbHelper(getActivity());
                if (helper.InsertUser(userText,passwordText)){
                    Toast.makeText(getActivity(), "Registration Success", Toast.LENGTH_SHORT).show();
                    if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
                    {
                        goToLogin.performClick();
                    }
                }else {
                    Toast.makeText(getActivity(), "User Name already in use.",Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
    goToLogin = (Button)view.findViewById(R.id.go_to_login);
    goToLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Login fragment = new Login();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                    setSharedElementReturnTransition(TransitionInflater.from(getActivity()).inflateTransition(R.transition.change_image_trans));
                    setExitTransition(TransitionInflater.from(getActivity()).inflateTransition(android.R.transition.fade) );
                    fragment.setSharedElementEnterTransition(TransitionInflater.from(getActivity()).inflateTransition(R.transition.change_image_trans));
                    fragment.setEnterTransition(TransitionInflater.from(getActivity()).inflateTransition(android.R.transition.fade));

            }

            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.addSharedElement(view.findViewById(R.id.logo),"LOGO");
            transaction.replace(R.id.main_container, fragment);
            transaction.commit();
        }

});
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getActivity().setTitle("Register for Uhvents");
}

}

这是我运行上面描述的场景时得到的错误日志。

致命异常:主进程:com。适应。教程4,PID:4807Android系统。数据库sqlite。SQLiteException:没有这样的列:UserName(代码1):,编译时:在android上,从UserName=='alex'和Password=='1234'的用户中选择*。数据库sqlite。SQLiteConnection。android上的nativePrepareStatement(本机方法)。数据库sqlite。SQLiteConnection。android上的acquirePreparedStatement(SQLiteConnection.java:887)。数据库sqlite。SQLiteConnection。在android上准备(SQLiteConnection.java:498)。数据库sqlite。SQLiteSession。在android上准备(SQLiteSession.java:588)。数据库sqlite。Sqlite程序。(SQLiteProgram.java:58)在android上。数据库sqlite。SQLiteQuery。(SQLiteQuery.java:37)在android上。数据库sqlite。SQLiteDirectCursorDriver。android上的查询(SQLiteDirectCursorDriver.java:44)。数据库sqlite。SQLITE数据库。android上的rawQueryWithFactory(SQLiteDatabase.java:1316)。数据库sqlite。SQLITE数据库。com上的rawQuery(SQLiteDatabase.java:1255)。适应。教程4。数据库DbHelper。登录用户(DbHelper.java:68)位于com。适应。教程4。碎片。登录费1美元。android上的onClick(Login.java:63)。看法看法android上的performClick(View.java:5198)。看法查看$PerformClick。在android上运行(View.java:21147)。操作系统。汉德勒。android上的handleCallback(Handler.java:739)。操作系统。汉德勒。android上的dispatchMessage(Handler.java:95)。操作系统。活套。android上的loop(Looper.java:148)。应用程序。活动线程。java上的main(ActivityThread.java:5417)。朗,反思一下。方法在com上调用(本机方法)。Android内部的操作系统。ZygoteInit$MethodandArgscaler。在com上运行(zyteinit.java:726)。Android内部的操作系统。合子岩。main(ZygoteInit.java:616)

共有2个答案

慕凌龙
2023-03-14

异常堆栈跟踪包含在SQLite数据库的用户表中找不到的列名UserName:

Android数据库sqlite。SQLiteException:没有这样的列:用户名(代码1):,编译时:从用户名='alex'和密码='1234'的用户中选择*

要解决该问题,您的数据库助手类需要更改如下:

public class DbHelper extends SQLiteOpenHelper {

    private static final String DbName = "SimpleDatabase";
    private static final int DbVersion = 1;

    // Table Names
    private static final String TABLE_USER = "User";

    // Column Names
    private static final String USER_NAME = "UserName";
    private static final String PASSWORD = "Password";

    // Create statements
    // Todo table create statement
    private static final String CREATE_TABLE_USER = "CREATE TABLE " 
            + TABLE_USER + " (" + USER_NAME + " TEXT PRIMARY KEY,"   
            // >>>>>> Note extra space above before TEXT keyword
            + PASSWORD + " TEXT)" ;

    public DbHelper(Context context) {
        super(context, DbName, null, DbVersion);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_USER);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXIST "+TABLE_USER);
        onCreate(db);
    }

    public Boolean InsertUser(String userName,String password){
        SQLiteDatabase db = this.getWritableDatabase();

        String query = "SELECT * FROM "+TABLE_USER+" WHERE "+USER_NAME+" == '"+userName+"';";
        Cursor c = db.rawQuery(query,null);

        if (c != null && c.moveToFirst()) {
            c.close();
            return false ;
        } else {
            ContentValues values = new ContentValues();
            values.put(USER_NAME, userName);
            values.put(PASSWORD, password);

            db.insert(TABLE_USER, null, values);
            return true;
        }
    }

    public Boolean loginUser(String userName,String password){

        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_USER + 
        " WHERE "+USER_NAME+" ==    '"+userName+"' AND "
        + PASSWORD + " == '"+password+"';";

        Cursor c = db.rawQuery(query,null);

        if(c != null && c.moveToFirst()) {
                c.close();
                return true;
        }

        return false;
    }
}
朱丰
2023-03-14

您需要在连接中添加空间。

这部分没有空间

" + USER_NAME + "TEXT PRIMARY KEY,"

还有这个

+ PASSWORD + "TEXT)";

所以把它改成

private static final String CREATE_TABLE_USER = "CREATE TABLE " 
        + TABLE_USER + "(" + USER_NAME + " TEXT PRIMARY KEY," 
        + PASSWORD + " TEXT)";
 类似资料:
  • 问题内容: 如何在Android上的SQLite数据库中获取布尔字段的值? 我通常使用,等获取字段的值,但似乎没有方法。 问题答案: 它是:

  • 我想从数据库中检索名称。但我总是收到错误: 数据库Java语言 它不断返回错误 android.database.CursorIndexOutOfBoundsException:请求索引-1,大小为1,字符串名称=helper.getProductNameT(cur); 有人知道我的编码哪里出错了吗?

  • 我正在尝试获取我的用户名,并在应用程序打开时向他/她问好。但我无法根据某个用户的uid获取数据。当我运行应用程序时,祝酒词从未真正出现。 数据库结构 密码

  • 我是在Android应用程序中使用SQL的新手,并且我在更新使用listView创建的表时遇到了一些麻烦。我设法从listView中更新了一个元素,但它不是正确的元素,它总是列表中的第一个元素发生了变化。 我制作了一个只有一列的表(稍后我将添加更多的两列),下面是我如何构建它: TaskContract_Faltas.java TaskDbHelper_Faltas Faltas.java 我使用

  • 问题内容: 我最近将应用程序中的hiberbnate模式更新为5.4.4.Final。现在,在部署过程中我面临以下异常。 我使用以下persistence.xml。 经过进一步调查,我发现根本原因是:hibernate使用 SequenceInformation 接口进行序列元数据操作 但是,我的应用程序使用如下序列: 该 Long.MAX_VALUE 等于9223372036854775807,

  • 问题内容: 我有一个执行此功能的数据库助手: 它从中提取的表如下所示: 在我的主要活动中,我尝试这样做并得到一个空指针… 有人知道我的问题是什么吗?我在较早的时候将数据放入数据库: 尝试了一下,仍然没有,我想选择“课程”中的所有“名称”值。没头绪…失去希望。 问题答案: 应该是这个 说明: api中的方法已定义为 公共游标查询(字符串表,字符串[]列,字符串选择,字符串[] selectionAr