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

显示SQLite数据库android studio中的用户名

邓子濯
2023-03-14

我试着使用这种方法:Android-登录textView后显示sqlite数据库中的用户名

但我得到一个错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.inzynierka.DatabaseHelper.getUsername()' on a null object reference
        at com.example.inzynierka.UserPanelActivity.onCreate(UserPanelActivity.java:65)

我想要的是在成功登录后在UserPanelActivity中显示当前昵称。

用户面板活动:

package com.example.inzynierka;

import androidx.appcompat.app.AppCompatActivity;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class UserPanelActivity extends AppCompatActivity {
    private Button settings_btn, progress_btn, dailychallenge_btn, premium_btn, logout_btn;
    public TextView NickNameText;
    DatabaseHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_panel);

        settings_btn = findViewById(R.id.settings_user_panel_button);
        settings_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Settings();
            }
        });

        progress_btn = findViewById(R.id.progress_button);
        progress_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyProgress();
            }
        });

        dailychallenge_btn = findViewById(R.id.challenge_button);
        dailychallenge_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DailyChallenge();
            }
        });

        premium_btn = findViewById(R.id.premium_button);
        premium_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Premium();
            }
        });

        logout_btn = findViewById(R.id.logout_button);
        logout_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BackToMenu();
                finish();
            }
        });
        NickNameText =  findViewById(R.id.nickname);

        NickNameText.setText(db.getUsername());
    }

    private void BackToMenu() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    private void Premium() {
        Intent intent = new Intent(this,PremiumActivity.class);
        startActivity(intent);
    }

    private void DailyChallenge() {
        Intent intent = new Intent(this,DailyChallengeActivity.class);
        startActivity(intent);
    }

    private void MyProgress() {
        Intent intent = new Intent(this,MyProgressActivity.class);
        startActivity(intent);
    }

    private void Settings() {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }

}

DataBaseHelper:

package com.example.inzynierka;

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.widget.TextView;

import androidx.annotation.Nullable;

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME="register.db";
    public static final String TABLE_NAME="registeruser";
    public static final String COL_1 ="ID";
    public static final String COL_2 ="username";
    public static final String COL_3 ="mail_address";
    public static final String COL_4 ="password";

    public DatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME,null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE registeruser (ID INTEGER PRIMARY KEY AUTOINCREMENT,username TEXT, mail_address TEXT, password TEXT)");
    }

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

    public long addUser(String user, String password, String mail_address) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("username", user);
        contentValues.put("password", password);
        contentValues.put("mail_address", mail_address);
        long res = db.insert("registeruser", null, contentValues);
        db.close();
        return res;
    }

        public boolean checkUser(String username, String password)
        {
            String[] columns = {COL_1};
            SQLiteDatabase db = getReadableDatabase();
            String selection = COL_2 + "=?" + " and " + COL_4 + "=?";
            String[] selectionArgs = {username, password};
            Cursor cursor = db.query(TABLE_NAME, columns,selection,selectionArgs,null,null,null);
            int count = cursor.getCount();
            cursor.close();
            db.close();

            if(count>0)
                return true;
            else
                return false;
        }

    public String getUsername() throws SQLException {
        String username = "";
        Cursor cursor = this.getReadableDatabase().query(
                TABLE_NAME, new String[] { COL_2 },
                null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                username = cursor.getString(1);
            } while (cursor.moveToNext());
        }
        cursor.close();

        return username;
    }
    }

UserPanel.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/lightblue"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".UserPanelActivity">


    <ImageView
        android:id="@+id/avatar"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:contentDescription="@string/avatar_description"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/kulfon"
        tools:srcCompat="@drawable/kulfon" />

    <TextView
        android:id="@+id/nickname"
        android:layout_width="120dp"
        android:layout_height="25dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:text="@string/username"
        app:layout_constraintBottom_toBottomOf="@+id/avatar"
        app:layout_constraintStart_toEndOf="@+id/avatar" />

    <TextView
        android:id="@+id/rank"
        android:layout_width="80dp"
        android:layout_height="25dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:text="@string/rank"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/avatar" />

    <Button
        android:id="@+id/progress_button"
        android:layout_width="136dp"
        android:layout_height="70dp"
        android:layout_marginTop="160dp"
        android:text="@string/progress"
        app:layout_constraintEnd_toStartOf="@+id/challenge_button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/challenge_button"
        android:layout_width="136dp"
        android:layout_height="70dp"
        android:layout_marginStart="136dp"
        android:layout_marginLeft="136dp"
        android:layout_marginTop="160dp"
        android:text="@string/challenge"
        app:layout_constraintEnd_toStartOf="@+id/settings_user_panel_button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/settings_user_panel_button"
        android:layout_width="136dp"
        android:layout_height="70dp"
        android:layout_marginStart="272dp"
        android:layout_marginLeft="272dp"
        android:layout_marginTop="160dp"
        android:text="@string/settings_user_panel"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/premium_button"
        android:layout_width="136dp"
        android:layout_height="70dp"
        android:layout_marginTop="10dp"
        android:text="@string/premium"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.49"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/start_freetraining_button" />

    <Button
        android:id="@+id/start_freetraining_button"
        android:layout_width="0dp"
        android:layout_height="120dp"
        android:layout_marginStart="50dp"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="60dp"
        android:layout_marginEnd="50dp"
        android:layout_marginRight="50dp"
        android:text="@string/freetraining_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/challenge_button" />

    <Button
        android:id="@+id/logout_button"
        android:layout_width="85dp"
        android:layout_height="35dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="@string/logout_btn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

登录活动:

package com.example.inzynierka;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.CallbackManager;

public class SignInActivity extends AppCompatActivity {
    private TextView register_text;
    public static CallbackManager callbackManager;
    DatabaseHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        db = new DatabaseHelper(this);
        callbackManager = CallbackManager.Factory.create();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);

        final EditText usernameEditText = findViewById(R.id.username);
        final EditText passwordEditText = findViewById(R.id.password);
        final Button loginButton = findViewById(R.id.login);
        final ProgressBar loadingProgressBar = findViewById(R.id.loading);
        usernameEditText.requestFocus();
        register_text = findViewById(R.id.register_text);
        String user = usernameEditText.getText().toString();
        register_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent registerIntent = new Intent(SignInActivity.this, RegisterActivity.class);
                startActivity(registerIntent);
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String user = usernameEditText.getText().toString().trim();
                String pwd = passwordEditText.getText().toString().trim();
                Boolean res = db.checkUser(user,pwd);
                if(res == true)
                {
                    Intent intent = new Intent(SignInActivity.this,UserPanelActivity.class);
                    //intent.putExtra("username",user);
                    startActivity(intent);
                    Toast.makeText(SignInActivity.this,"Welcome " + user + "!", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(SignInActivity.this,"There is a problem with singing in!", Toast.LENGTH_SHORT).show();
                    usernameEditText.setText("");
                    passwordEditText.setText("");
                    usernameEditText.requestFocus();
                }

            }
        });
    }
}

谢谢你的帮助!:)

共有1个答案

杨慎之
2023-03-14

您没有在onCreate中初始化您的Database aseHelper db。如果没有初始化,您将尝试使用它。这就是为什么您会得到NullPointerException

DatabaseHelper db = new DatabaseHelper(this);
NickNameText.setText(db.getUsername());

关于您的第二个查询:成功登录后,通过意图将用户名传递给UserPanelactive

Intent intent = new Intent(SignInActivity.this,UserPanelActivity.class);
intent.putExtra("username",user);
startActivity(intent);

然后,UserPanelActivityonCreate获取此用户名并将其设置为昵称文本。无需在此访问db。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_panel);

    String usrename = getIntent().getStringExtra("username");

    NickNameText =  findViewById(R.id.nickname);
    NickNameText.setText(usrename);

    ...
}

 类似资料:
  • 我想在我的应用程序中显示来自sqlite数据库的图像。我的要求是显示文本视图及其相关图像。我将我的数据库文件保存在资产文件夹中。但实际上我的图像存储在服务器的“allimages”文件夹中。 我的数据库列(我保留的assets文件夹中的db)如下所示: S.无描述 1 div style=“文本对齐:对齐;” 2 div style="文本对齐:对齐;" 现在我的问题是在我的数据库中,图像路径存储

  • 喂! 我一直在做一个web项目,用户可以注册和登录。我也想添加一个配置文件,他们提供的一些信息可以在“配置文件”页面上显示。 我已经使用firebase auth(与电子邮件和密码)和rt数据库存储额外的信息,如‘姓名','生物’等。 我已经尝试过这里其他问题的解决方案,但似乎没有一个对我有效。 下面是我的数据库的外观: 下面是配置文件页面的一些代码: 当我测试代码时,我在控制台上得到了这个错误:

  • 我怀疑原因可能是在ViewHolder中连接字符串,根据我所读到的(检查底部的引用),这应该使用带有占位符的资源字符串来完成,例如 应替换为 其中包括。 https://developer.android.com/guide/topics/resources/string-resource#formattingandstyling https://developer.android.com/ref

  • 因此,我最近开始学习Android编程,并一直在学习本教程,学习如何在SQLite数据库中插入、更新、删除和查看数据。现在,我还想在这个SQLite数据库中添加一个搜索功能,在这个数据库中,我可以搜索一个名称(我使用的列是name、contact和DOB),如果搜索到的名称与数据库中现有的名称匹配,则在应用程序中显示数据库中的一行/条目。我想这可以以类似于查看/更新数据库的方式来完成,所以我试着用

  • 问题内容: 我正在使用jdbc编写程序,该程序将成为数据库的接口(类似于CRUD应用程序)。我假设我必须编写一个类(例如),该类将对数据库执行所有操作(以及可能会简化为这些操作的某些其他逻辑)。用户界面由一组表和一些按钮组成。要使用Jtable,我需要实现一个类(例如),它是AbstractTableModel的子类。因此,此类将向用户显示我的数据。我需要为数据库架构中的所有表实现这种模型。我不想

  • 这是我的数据库代码,我想从我的数据库中检索名称,并将其显示在listview中,在下面发布的另一个java文件中显示为profilelist.jar。但是我不能这样做,请告诉我这段代码是否正确? profileList.java 我在a.vaccination.datahandler.getTitle(datahandler.java:115)和a.vaccination.profilelist.