我有登录的iusse:当我点击“登录”时,我只看到“退出”按钮而没有关于人的名字。
为什么?
我向您展示关于我的db的截图:
关于获取用户的代码:
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(2));
user.put("cognome", cursor.getString(3));
user.put("email", cursor.getString(4));
user.put("email2", cursor.getString(5));
user.put("numero_appartamento", cursor.getString(6));
user.put("nome_edificio", cursor.getString(7));
user.put("zona_metropolitana", cursor.getString(8));
user.put("uid", cursor.getString(9));
user.put("created_at", cursor.getString(10));
}
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
MAIN ACTIVITY.java:
public class MainActivity extends Activity {
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.numero_telefonico);
btnLogout = (Button) findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from SQLite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
//String email = user.get("email");
String email = user.get("email");
// Displaying the user details on the screen
System.out.println(name+email);
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logoutUser();
}
});
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
PS:System.out.println在consolle
中打印null和nullSQLITE HENDLER:
public class SQLiteHandler extends SQLiteOpenHelper {
private static final String TAG = SQLiteHandler.class.getSimpleName();
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_api";
// Login table name
private static final String TABLE_USER = "user";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_COGNOME = "cognome";
private static final String KEY_EMAIL = "email";
private static final String KEY_EMAIL2 = "email2";
private static final String KEY_NUMERO_APPARTAMENTO = "numero_appartamento";
private static final String KEY_NOME_EDIFICIO = "nome_edificio";
private static final String KEY_ZONA_METROPOLITANA = "zona_metropolitana";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public SQLiteHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_COGNOME+ " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_EMAIL2 + " TEXT,"
+ KEY_NUMERO_APPARTAMENTO + " TEXT,"
+ KEY_NOME_EDIFICIO + " TEXT,"
+ KEY_ZONA_METROPOLITANA + " TEXT,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
Log.d(TAG, "Database tables created");
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name,String cognome, String email, String email2,String numero_appartamento,String nome_edificio,String zona_metropolitana, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_COGNOME, cognome); // Cognome
values.put(KEY_EMAIL, email);// Email
values.put(KEY_EMAIL2, email2);
values.put(KEY_NUMERO_APPARTAMENTO, numero_appartamento);
values.put(KEY_NOME_EDIFICIO, nome_edificio);
values.put(KEY_ZONA_METROPOLITANA, zona_metropolitana);
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
long id = db.insert(TABLE_USER, null, values);
db.close(); // Closing database connection
Log.d(TAG, "New user inserted into sqlite: " + id);
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("cognome", cursor.getString(2));
user.put("email", cursor.getString(3));
user.put("email2", cursor.getString(4));
user.put("numero_appartamento", cursor.getString(5));
user.put("nome_edificio", cursor.getString(6));
user.put("zona_metropolitana", cursor.getString(7));
user.put("uid", cursor.getString(8));
user.put("created_at", cursor.getString(9));
}
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
/**
* Re crate database Delete all tables and create them again
* */
public void deleteUsers() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_USER, null, null);
db.close();
Log.d(TAG, "Deleted all user info from sqlite");
}
}
登录活动:
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText enputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
enputEmail = (EditText) findViewById(R.id.numero_telefonico);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = enputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String cognome = user.getString("cognome");
String email = user.getString("email");
String email2 = user.getString("email2");
String numero_appartamento = user.getString("numero_appartamento");
String nome_edificio = user.getString("nome_edificio");
String zona_metropolitana = user.getString("zona_metropolitana");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name,cognome, email,email2,numero_appartamento, nome_edificio,zona_metropolitana,uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
System.out.println(params);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
答案 0 :(得分:2)
在调用if-statement
后删除cursor.moveToFirst
,而不是检查moveToFirst
是否返回true
(这意味着光标非空)。您的代码应如下所示:
if( cursor.moveToFirst()){
user.put("name", cursor.getString(2));
user.put("cognome", cursor.getString(3));
user.put("email", cursor.getString(4));
user.put("email2", cursor.getString(5));
user.put("numero_appartamento", cursor.getString(6));
user.put("nome_edificio", cursor.getString(7));
user.put("zona_metropolitana", cursor.getString(8));
user.put("uid", cursor.getString(9));
user.put("created_at", cursor.getString(10));
}
尝试一下,让我知道这是否有帮助。确认您至少拥有数据库中的数据,并且您不再获得空值。
答案 1 :(得分:0)
在// Move to first row
&amp;之间更改您的代码// return user
// Move to first row
if (cursor.moveToFirst()) {
do {
user.put("name", cursor.getString(2));
user.put("cognome", cursor.getString(3));
user.put("email", cursor.getString(4));
user.put("email2", cursor.getString(5));
user.put("numero_appartamento", cursor.getString(6));
user.put("nome_edificio", cursor.getString(7));
user.put("zona_metropolitana", cursor.getString(8));
user.put("uid", cursor.getString(9));
user.put("created_at", cursor.getString(10));
} while (cursor.moveToNext());
}
db.close();
// return user
到目前为止工作正常。 日Thnx
答案 2 :(得分:0)
在“登录活动”中,添加以下行
db.deleteUsers();
之前:
db.addUser();