Java 远程MySQL数据库的Android登录验证
以下是我的java代码:Java 远程MySQL数据库的Android登录验证,java,android,Java,Android,以下是我的java代码: btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ArrayList < NameValuePair > postParameters = new ArrayList < NameValuePair > (); postParameters.add(new BasicNameVal
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ArrayList < NameValuePair > postParameters = new ArrayList < NameValuePair > ();
postParameters.add(new BasicNameValuePair("username", txtUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password", txtPassword.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://www.sampleweb.com/imba.php", postParameters);
String res = response.toString();
// res = res.trim();
res = res.replaceAll("\\s+", "");
//error.setText(res);
if (res.equals("1")) {
txtError.setText("Correct Username or Password");
//Intent i = new Intent(CDroidMonitoringActivity.this, MenuClass.class);
//startActivity(i);
} else {
txtError.setText("Sorry!! Incorrect Username or Password");
}
} catch (Exception e) {
txtUsername.setText(e.toString());
}
}
});
btnLogin.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
ArrayListpostParameters=新的ArrayList();
添加(新的BasicNameValuePair(“用户名”,txtUsername.getText().toString());
添加(新的BasicNameValuePair(“密码”,txtPassword.getText().toString());
//字符串valid=“1”;
字符串响应=null;
试一试{
响应=CustomHttpClient.executeHttpPost(“http://www.sampleweb.com/imba.php“,后参数);
String res=response.toString();
//res=res.trim();
res=res.replaceAll(“\\s+”,”);
//错误.setText(res);
如果(相对等于(“1”)){
setText(“正确的用户名或密码”);
//意图i=新意图(CDroidMonitoringActivity.this,MenuClass.class);
//星触觉(i);
}否则{
setText(“对不起!!用户名或密码不正确”);
}
}捕获(例外e){
setText(例如toString());
}
}
});
我认为我的res.equals中有一个错误,因为它一直在说“无效的用户名或密码”,即使我输入了正确的用户名或密码。但是当我将res.equals更改为res.contains时,它会一直说“正确的用户名或密码”,即使我输入了正确的用户名和密码。我真的需要你的帮助。所有人都精通android开发。希望你能在这方面帮助我。而且,当我更改txterro.setText(res)只是为了检查它是否返回1和0时,它不会返回 这需要在php文件中完成,而不是在Android代码中:
<?php
define('DB_USER', "root"); //username used to connect to the database.
define('DB_PASSWORD', ""); //password used to connect to the database.
define('DB_DATABASE', "dbname"); //database name
define('DB_SERVER', "127.0.0.1"); //database server address
?>
使用JSON解析器,您需要解析服务器上的数据。您需要使用类似于以下内容的内容:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
//Method to connect to the database
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
//The following works just as in normal GET and POST methods
try {
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
公共JSONParser(){
}
//方法连接到数据库
公共JSONObject makeHttpRequest(字符串url、字符串方法、列表参数){
//下面的工作方式与正常的GET和POST方法相同
试一试{
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
//请求方法是GET
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
}
在第二个类中,您需要按如下方式定义连接参数:
public class UserFunctions {
private JSONParser jsonParser;
private static String loginURL = "http://www.sampleweb.com/login.php";
private static String registerURL = "http://www.sampleweb.com/register.php";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* @param email
* @param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* @param name
* @param email
* @param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
公共类用户函数{
私有JSONParser JSONParser;
专用静态字符串loginURL=”http://www.sampleweb.com/login.php";
专用静态字符串注册表URL=”http://www.sampleweb.com/register.php";
私有静态字符串login_tag=“login”;
专用静态字符串寄存器\u tag=“寄存器”;
//建造师
公共用户函数(){
jsonParser=新的jsonParser();
}
/**
*函数发出登录请求
*@param电子邮件
*@param密码
* */
公共JSONObject登录用户(字符串电子邮件、字符串密码){
//建筑参数
List params=new ArrayList();
添加(新的BasicNameValuePair(“标签”,登录标签));
参数添加(新的BasicNameValuePair(“电子邮件”),电子邮件);
添加(新的BasicNameValuePair(“密码”,password));
JSONObject json=jsonParser.getJSONFromUrl(loginURL,params);
//返回json
//Log.e(“JSON”,JSON.toString());
返回json;
}
/**
*函数发出登录请求
*@param name
*@param电子邮件
*@param密码
* */
公共JSONObject注册表服务器(字符串名称、字符串电子邮件、字符串密码){
//建筑参数
List params=new ArrayList();
参数添加(新的BasicNameValuePair(“标记”,寄存器_标记));
参数添加(新的BasicNameValuePair(“名称”),名称);
参数添加(新的BasicNameValuePair(“电子邮件”),电子邮件);
添加(新的BasicNameValuePair(“密码”,password));
//获取JSON对象
JSONObject json=jsonParser.getJSONFr