好的,我已经完成了上述任务,但我对此并不满意。它看起来非常复杂。
我需要一些其他方法来解决这个问题,因为我在Android开发方面的经验非常少,而且无法找到其他任何方式。
在这里我是如何做到的。我将向您展示访问数据库的简单登录系统。
以下是登录活动。
package com.example.andorid.ersnexus.userlogin;
import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
mport android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.andorid.ersnexus.R;
import
com.example.andorid.ersnexus.userprofile.homeactivity.
UserProfileHomeActivity;
import com.example.andorid.ersnexus.usersignup.UserSignUpActivity;
import com.example.andorid.ersnexus.util.SharedPreferencesData;
import com.example.andorid.ersnexus.webservices.BackgroundDbConnector;
//This is the main activity of the app.
//It is the user login screen where users logs in or sign up's.
public class UserLoginActivity extends AppCompatActivity {
private EditText mUserName;
private EditText mUserPassword;
private Button mLoginButton;
private Button mSignUpButton;
//private UserBaseHelper mHelper;
private String userName;
private String pass;
//private String password;
//private String mErno;
public static Activity mActivity;
public static Boolean mActive;
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
mActivity = this;
Boolean status = SharedPreferencesData.getStoredLoginStatus(UserLoginActivity.this);
if(status){
Intent i = new Intent(UserLoginActivity.this, UserProfileHomeActivity.class);
startActivity(i);
}
//mHelper = new UserBaseHelper(this);
//user UserName editText in activity_user_login
mUserName = (EditText) findViewById(R.id.login_user_name);
//PASSWORD editText
mUserPassword = (EditText) findViewById(R.id.login_user_pass);
//SignUp button
mSignUpButton = (Button) findViewById(R.id.sign_up_button);
mSignUpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v) {
Intent i = new Intent(UserLoginActivity.this, UserSignUpActivity.class);
startActivity(i);
}
});
//Login Button
mLoginButton = (Button) findViewById(R.id.login_button);
mLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v) {
if(isNetworkAvailableAndConnected()) {
/*try {
if(!InetAddress.getByName("192.168.2.3").isReachable(5000)){
throw new Exception("Host does not exist::");
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(UserLoginActivity.this,
"Server Is Down",Toast.LENGTH_SHORT).show();
}*/
String type = "login";
userName = mUserName.getText().toString();
pass = mUserPassword.getText().toString();
//password = mHelper.fetchUserPass(userName);
//mErno = mHelper.fetchErNo(userName);
//String fullName = mHelper.fetchFullName(userName);
***BackgroundDbConnector backgroundDbConnector = new
BackgroundDbConnector(UserLoginActivity.this);
backgroundDbConnector.execute(type, userName, pass);***
SharedPreferencesData.setStoredUsername(UserLoginActivity.this, userName);
}else {
Toast.makeText(UserLoginActivity.this,
"No Internet Connection",Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onStart() {
super.onStart();
mActive = true;
}
@Override
public void onStop() {
super.onStop();
mActive = false;
}
private boolean isNetworkAvailableAndConnected () {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
return isNetworkAvailable &&
cm.getActiveNetworkInfo().isConnected();
}
}
Post请求通过backgroundTask发送
BackgroundDbConnector backgroundDbConnector = new
BackgroundDbConnector(UserLoginActivity.this);
backgroundDbConnector.execute(type, userName, pass);
然后在backGround AsyncTask中发生以下事情:
try {
//Fetch the username and password from the background method call.
String username = params[1];
String password = params[2];
mHttpURLConnection = URLManager.
getConnection(URLManager.LOGIN_URL);
//Creating the outputStream
OutputStream outputStream = mHttpURLConnection.getOutputStream();
//Writing in the outputStream.
BufferedWriter bufferedWriter = new BufferedWriter(new
OutputStreamWriter(outputStream, "UTF-8"));
//This is for connecting the variables in the app and in the php file.
String postData = URLEncoder.encode("username", "UTF-8") + "=" +//$_POST["username"]
URLEncoder.encode(username, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" +//$_POST["password"]
URLEncoder.encode(password, "UTF-8");
//Feeding the data.
bufferedWriter.write(postData);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//Creating an inputStream to fetch the results.
InputStream inputStream = mHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"));
//Getting the results
String result = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
mHttpURLConnection.disconnect();
//Returning the results
return result;
}
最后php文件如下:
<?php
require "conn.php";
$user_name = $_POST["username"];
$user_pass = $_POST["password"];
$mysql_qry = "SELECT * FROM student_data WHERE username='$user_name' AND
password='$user_pass';";
$result = mysqli_query($conn, $mysql_qry);
$row_cnt = mysqli_num_rows($result);
if($row_cnt > 0){
$row = mysqli_fetch_assoc($result);
$erno = $row["enrollmentnumber"];
echo $erno;
}
else{
echo "Wrong Username or Password";
}
?>
所以大多数数据库连接都以这种方式完成,我需要一些其他的方法来完成这个
我有一种直觉,你可以看到backGround任务需要以其他方式处理,但我没有得到...
那些在Android方面有良好经验的人,请引导我走正确的道路。
感谢那些花时间阅读我的代码的开发人员。
这是我对该项目的链接。如果你愿意,请看看并测试,我会喜欢关于我的代码的意见。
答案 0 :(得分:0)
嗯,我找到了另一种选择,实施它非常可爱。
try {
//Fetch the username and password from the background method call.
String username = params[1];
String password = params[2];
mHttpURLConnection = URLManager.
getConnection(URLManager.LOGIN_URL);
//Creating the outputStream
OutputStream outputStream = mHttpURLConnection.getOutputStream();
//Writing in the outputStream.
BufferedWriter bufferedWriter = new BufferedWriter(new
OutputStreamWriter(outputStream, "UTF-8"));
//This is for connecting the variables in the app and in the php file.
String postData = URLEncoder.encode("username", "UTF-8") + "=" +//$_POST["username"]
URLEncoder.encode(username, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" +//$_POST["password"]
URLEncoder.encode(password, "UTF-8");
//Feeding the data.
bufferedWriter.write(postData);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//Creating an inputStream to fetch the results.
InputStream inputStream = mHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"));
//Getting the results
String result = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
mHttpURLConnection.disconnect();
//Returning the results
return result;
}
使用Volley将以上所有代码替换为以下代码。 以下是新代码
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLManager.
LOGIN_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response != null &&
!response.equals("Wrong Username or Password")) {
SharedPreferencesData.setStoredLoginStatus(mContext, true);
SharedPreferencesData.setStoredErno(mContext, response);
mContext.startActivity(new Intent(mContext,
UserProfileHomeActivity.class));
} else {
Toast.makeText(mContext, "Wrong Username or Password!",
Toast.LENGTH_SHORT)
.show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(UserLoginActivity.this, error.toString(),
Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(KEY_USERNAME, userName);
params.put(KEY_PASSWORD, pass);
return params;
}
};
SharedPreferencesData.setStoredUsername(UserLoginActivity.this, userName);
RequestQueue requestQueue = Volley.newRequestQueue(UserLoginActivity.this);
requestQueue.add(stringRequest);