public class LoginInterface extends AppCompatActivity implements View.OnClickListener{
Button bLogin;
EditText etUsername, etPassword;
TextView tvRegisterLink;
String username;
boolean ifReturn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_interface);
etPassword = (EditText) findViewById(R.id.etPassword);
etUsername = (EditText) findViewById(R.id.etUsername);
bLogin = (Button) findViewById(R.id.blogin);
bLogin.setTransformationMethod(null);
tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
bLogin.setOnClickListener(this);
tvRegisterLink.setOnClickListener(this);
}
public void saveInfo(View view){
SharedPreferences sharedPref = getSharedPreferences("user_info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("email", etUsername.getText().toString());
editor.putString("password", etPassword.getText().toString());
editor.apply();
}
public void getInfo(View view){
SharedPreferences sharedPref = getSharedPreferences("user_info", Context.MODE_PRIVATE);
String email = sharedPref.getString("email", "");
String password = sharedPref.getString("password", "");
if (!email.isEmpty() && !password.isEmpty()){
// Intent i = new Intent(this, Profile.class);
// Bundle bundle = new Bundle();
// bundle.putString("username", username);
// i.putExtras(bundle);
// startActivity(i);
}
}
public void alert(String message){
new AlertDialog.Builder(this)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
// a method that takes the text that user entered and compare them with the correct user account and password stored on userinfo.txt file.
public void volley() {
final ProgressDialog proDia = new ProgressDialog(this);
proDia.setTitle("Processing");
proDia.setMessage("Please wait...");
proDia.show();
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
RequestQueue mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
// Add request to queue
String url = "http://percyteng.com/get_users_details.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
username = new JSONObject(response).getString("user");
proDia.dismiss();
ifReturn = true;
// JSONArray jsonResponse = new JSONObject(response).getJSONArray("user");
// for (int i = 0; i< jsonResponse.length(); i++){
// JSONObject eachuser = jsonResponse.getJSONObject(i);
// String useremail = eachuser.getString("useremail");
// String password = eachuser.getString("password");
// alert(useremail + "," + password);
// }
// username = jsonResponse.getString("username");
} catch (JSONException e) {
alert("Incorrect user information.");
proDia.dismiss();
ifReturn = false;
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("useremail", etUsername.getText().toString());
params.put("password", etPassword.getText().toString());
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
if (ifReturn) {
alert("bitch");
Intent i = new Intent(this, Profile.class);
Bundle bundle = new Bundle();
bundle.putString("username", username);
i.putExtras(bundle);
startActivity(i);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tvRegisterLink:
startActivity(new Intent(this, Register.class));
break;
case R.id.blogin:
String ed_Name = etUsername.getText().toString().trim();
String ed_Password = etPassword.getText().toString().trim();
if (ed_Name.isEmpty()){
alert("Wrong input,please enter your user name.");
}
else if (ed_Password.isEmpty()){
alert("Wrong input, please enter your password.");
}
else{
volley();
// etPassword.setText("");
// etUsername.setText("");
}
break;
}
}
}
这是我的 android studio 中的代码,运行得很好。我的问题是在我的登录界面中,第一次点击登录按钮时,它不会执行任何操作,但我很确定服务器已经收到登录消息,因为第二次点击登录按钮时,它会启动响应我第一次点击按钮的 Activity 。当我尝试使用另一个帐户登录时,它第一次尝试时会使用以前的帐户登录。换句话说,我的登录 Activity 在一次尝试后发生了变化。这很难解释。所以我的第二次点击基本上响应了第一个 startActivity() 。
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
$response = array();
if (isset($_POST['useremail']) && isset($_POST['password'])) {
$useremail = $_POST['useremail'];
$password = $_POST['password'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
try{
// connecting to db
$con = new DB_CONNECT();
$db = $con->connect();
// mysql inserting a new row
$result = $db->prepare("SELECT username FROM user WHERE useremail = :useremail AND password = :password");
// binding parameters for mysql insertion
$result->bindParam(":useremail", $useremail);
$result->bindParam(":password", $password);
// mysql inserting a new row with prepared and binded statements
$result->execute();
// check if row inserted or not
if ($result) {
// check for empty result
if ($result->rowCount() > 0) {
$result = $result->fetch();
// $user = array();
// $user["useremail"] = $result["useremail"];
// $user["password"] = $result["password"];
// // success
$response["success"] = 1;
$response["message"] = "Successfully found the user";
// user node
$response["user"] = $result["username"];
// array_push($response["user"], $user);
// echoing JSON response
echo json_encode($response);
}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
} catch (PDOException $e){
print "Sorry, a database error occurred. Please try again later.\n";
print $e->getMessage();
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
这是 php 代码,如果你们需要看一下。再次,服务器连接成功,一切正常,所有数据都可以在android和mysql之间传输。这只是奇怪的响应延迟。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation = "vertical"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:weightSum="1"
android:layout_marginTop="50dp"
android:baselineAligned="false">
<ImageButton
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_gravity="center_horizontal"
android:layout_height="80dp"
android:layout_marginBottom="20dp"
android:background="@drawable/queensflag"
android:id="@+id/imageButton2" />
<TextView
android:layout_centerHorizontal="true"
android:layout_below="@+id/imageButton2"
android:id="@+id/tvUsername"
android:text="Email"
android:textSize="15dp"
android:layout_width = "wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal"
android:layout_height = "wrap_content"/>
<EditText
android:layout_centerHorizontal="true"
android:layout_below="@+id/tvUsername"
android:layout_width="300dp"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/etUsername" />
<TextView
android:layout_centerHorizontal="true"
android:layout_below="@+id/etUsername"
android:layout_gravity="center_horizontal"
android:textSize="15dp"
android:id="@+id/tvPassword"
android:layout_width = "wrap_content"
android:layout_marginTop="10dp"
android:text="Password"
android:layout_height = "wrap_content"/>
<EditText
android:layout_centerHorizontal="true"
android:layout_below="@+id/tvPassword"
android:layout_width="300dp"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/etPassword" />
<Button
android:layout_centerHorizontal="true"
android:layout_below="@+id/etPassword"
android:layout_width="300dp"
android:layout_marginTop="40dp"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="Login"
android:id="@+id/blogin"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_centerHorizontal="true"
android:layout_below="@id/blogin"
android:id="@+id/tvRegisterLink"
android:layout_width = "wrap_content"
android:layout_marginTop="30dp"
android:textSize="15dp"
android:layout_gravity="center_horizontal"
android:text="Register"
android:layout_height = "wrap_content"/>
</RelativeLayout>
这里是 xml 代码,如果你们需要看一下。但老实说,它只是一个普通的登录 xml。
最佳答案
简单地说,在 volley() 方法中,您执行以下步骤:
- 声明 StringRequest(使用您的 Response 监听器)。
- 发送 StringRequest。
- 检查是否返回。
由于 Volley 是异步的,你发送 StringRequest(2.) 并立即检查 ifReturn 变量(3.),当然第一次会是 false,因为没有时间获取响应并调用 Response 监听器(1.) 设置 ifReturn 为 true。
您应该在 Response.Listener 的 onResponse() 方法中启动 Activity 。您不再需要管理 ifReturn 。 Volley仅在收到请求的响应并且成功时才调用onResponse()方法。如果出现错误,将调用 onResponseError。
关于php - 我必须点击登录按钮两次才能登录我的 Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34449253/