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工作室中的代码,完全正常。我的问题是在我的登录界面,我第一次点击登录按钮,它不会做任何事情,但我很确定服务器已经收到登录消息,因为我第二次点击登录按钮,它开始响应我的第一个按钮点击的活动。当我尝试使用其他帐户登录时,它会使用之前的帐户登录进行第一次尝试。换句话说,我的登录活动在一次尝试后发生了变化。这很难解释。所以我的第二次点击响应第一个startActivity()basicalliy。
<?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。
答案 0 :(得分:0)
简而言之,在您的volley()方法中,您执行以下步骤:
由于Volley是异步的,你发送StringRequest(2。)并立即检查ifReturn变量(3.),当然第一次它将是false,因为没有时间得到响应并调用Response listener (1.)将ifReturn设置为true。
您应该从Response.Listener中的onResponse()方法中启动活动。您不再需要管理ifReturn。当获得请求的响应并且成功时,Volley仅调用onResponse()方法。如果出现错误,将调用onResponseError。