Android-登录textView后显示sqlite数据库中的用户名 [英] Android - Display username from sqlite database after login in textView

查看:121
本文介绍了Android-登录textView后显示sqlite数据库中的用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是开发Android应用程序的新手,我想在成功登录导航抽屉后显示用户名.我的问题是如何仅从sqlite数据库中获取用户名并将其显示在textView中.查看图片

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

到目前为止,这是我的代码,我的DatabaseHelper

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;
}  }

推荐答案

我会将用户名保存到sharedpreferences中,因为应用程序只有一个用户,因此您无需仅将一个条目保存到数据库中.但是,如果您坚持要从数据库中获取它,则可以将此函数添加到DatabaseHelper中.

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.您应该真正重构代码.并使用SharedPreferences而不是SQLite来存储单个值.SQLite旨在存储大量数据容器,例如缓存的列表数据等.

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.

这篇关于Android-登录textView后显示sqlite数据库中的用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆