Android - Display username from sqlite database after login in textView

我与影子孤独终老i 提交于 2021-02-08 06:20:32

问题


I am new in developing android app, I want to display the username after successfully login in the navigation drawer. My question is how to fetch only the username from sqlite database and display it in textView. See the picture

This is my codes so far, my DatabaseHelper

public class DatabaseHelper extends SQLiteOpenHelper{

public static final String DATABASE_NAME = "Users.db";
public static final String TABLE_NAME = "users_table";
private static final int DATABASE_VERSION = 1;

private static final String KEY_ID = "id";
private static final String KEY_NAME = "username";
private static final String KEY_PASS = "password";

SQLiteDatabase db;

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE "+TABLE_NAME+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT);");
    db.execSQL("INSERT INTO " + TABLE_NAME + " VALUES (null, 'admin', '12345');");

}

public String searchPass(String uname){
    db = this.getReadableDatabase();
    String query = "SELECT username, password FROM "+TABLE_NAME;
    Cursor cursor = db.rawQuery(query, null);
    String a, b;
    b = "not found";
    if(cursor.moveToFirst()){
        do{
            a = cursor.getString(0);
            if(a.equals(uname)){
                b = cursor.getString(1);
                break;
            }
        }while(cursor.moveToNext());
    }
    return b;
}

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

and here is where i want to display my username

public class MenuHome extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

public static final String PREFS_NAME = "LoginPrefs";
DatabaseHelper helper = new DatabaseHelper(this);

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //set the fragment initially
    HomeFragment fragment = new HomeFragment();
    setTitle(R.string.ttl_home);
    FragmentTransaction fragmentTransaction =
            getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment);
    fragmentTransaction.commit();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

/*@Override             //Right Options Menu
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_home, menu);
    return true;
}*/

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return false;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_home) {
        HomeFragment fragment = new HomeFragment();
        setTitle(R.string.ttl_home);
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

    } else if (id == R.id.nav_inv) {
        InventoryFragment fragment = new InventoryFragment();
        setTitle(R.string.ttl_inventory);
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

    } else if (id == R.id.nav_prod) {
        ProductFragment fragment = new ProductFragment();
        setTitle(R.string.ttl_products);
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

    } else if (id == R.id.nav_clients) {
        ClientsFragment fragment = new ClientsFragment();
        setTitle(R.string.ttl_clients);
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

    } else if (id == R.id.nav_stat) {
        StatsFragment fragment = new StatsFragment();
        setTitle(R.string.ttl_stat);
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

    } else if (id == R.id.nav_prof) {
        ProfileFragment fragment = new ProfileFragment();
        setTitle(R.string.ttl_prof);
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

    } else if (id == R.id.nav_about) {
        AboutFragment fragment = new AboutFragment();
        setTitle(R.string.ttl_about);
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

    } else if (id == R.id.nav_logout) {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.remove("logged");
        editor.commit();
        Intent intent = new Intent(MenuHome.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}  }

回答1:


I would save username to sharedpreferences, because app will have only one user, you don't need to save just one entry to your database. But if you insist on getting it from database, then add this function to your DatabaseHelper.

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

                  return username;
    }

and later you can use this code to get username in your drawer activity:

textView.setText(helper.getUsername());

P.S. you should really really refactor your code. And use SharedPreferences instead of SQLite for storing single values. SQLite is designed to store massive data containers, like cached list data and so on.



来源:https://stackoverflow.com/questions/34815337/android-display-username-from-sqlite-database-after-login-in-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!