Java 使用wamp服务器、phpmyadmin、eclipse和json进行Android登录和注册
我试图创建一个登录界面遵循本教程:-第1部分至第6部分 当我在Android emulator上运行应用程序时,它返回toast消息“Login Unsuccessful”(下面Main.java文件中声明的异常) main.java文件连接到我保存在目录wamp/www/index.php中的php文件-index.php,然后该文件与存储在wamp服务器(在我的本地机器上)上的“mobiledb”通信 已经在数据库中创建了一个用户,我尝试通过模拟器登录,该模拟器将验证登录详细信息,并给出toast消息“Success!” 如果有人能在这个问题上提供任何帮助,我们将不胜感激。谢谢 Main.javaJava 使用wamp服务器、phpmyadmin、eclipse和json进行Android登录和注册,java,eclipse,json,phpmyadmin,wampserver,Java,Eclipse,Json,Phpmyadmin,Wampserver,我试图创建一个登录界面遵循本教程:-第1部分至第6部分 当我在Android emulator上运行应用程序时,它返回toast消息“Login Unsuccessful”(下面Main.java文件中声明的异常) main.java文件连接到我保存在目录wamp/www/index.php中的php文件-index.php,然后该文件与存储在wamp服务器(在我的本地机器上)上的“mobiledb”通信 已经在数据库中创建了一个用户,我尝试通过模拟器登录,该模拟器将验证登录详细信息,并给出to
package com.kibriaali.logintutorial;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity implements OnClickListener{
EditText etUser, etPass;
Button bLogin;
//Create string variables that will have the input assigned to them
String username, password;
//Create a HTTPClient as the form container
HttpClient httpclient;
//Use HTTP POST method
HttpPost httppost;
//Create an array list for the input data to be sent
ArrayList<NameValuePair> nameValuePairs;
//Create a HTTP Response and HTTP Entity
HttpResponse response;
HttpEntity entity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialise();
}
private void initialise() {
// TODO Auto-generated method stub
etUser = (EditText) findViewById(R.id.etUser);
etPass = (EditText) findViewById(R.id.etPass);
bLogin = (Button) findViewById(R.id.bSubmit);
//Now to set an onClickListener
bLogin.setOnClickListener(this);
}
public void onClick(View v) {
// This is where we will be working now
//Create new default HTTPClient
httpclient = new DefaultHttpClient();
//Create new HTTP POST with URL to php file as parameter
httppost = new HttpPost("http://127.0.0.1/wamp/www/index.php"); //92.4.131.132 //127.0.0.1 //10.0.2.2
//Assign input text to strings
username = etUser.getText().toString();
password = etPass.getText().toString();
//Next block of code needs to be surrounded by try/catch block for it to work
try {
//Create new Array List
nameValuePairs = new ArrayList<NameValuePair>(2);
//place them in an array list
nameValuePairs.add(new BasicNameValuePair("user", "username"));
nameValuePairs.add(new BasicNameValuePair("pass", "password"));
//Add array list to http post
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//assign executed form container to response
response = httpclient.execute(httppost); //response from the PHP file
//check status code, need to check status code 200
if(response.getStatusLine().getStatusCode()== 200){
//assign response entity to http entity
entity = response.getEntity();
//check if entity is not null
if(entity != null){
//Create new input stream with received data assigned
InputStream instream = entity.getContent();
//Create new JSON Object. assign converted data as parameter.
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
//assign json responses to local strings
String retUser = jsonResponse.getString("user");//mySQL table field
String retPass = jsonResponse.getString("pass");
//Validate login
if(username.equals(retUser)&& password.equals(retPass)){ //Check whether 'retUser' and 'retPass' matches username/password
//Create a new shared preference by getting the preference
//Give the shared preference any name you like.
SharedPreferences sp = getSharedPreferences("logindetails", 0);
//Edit the Shared Preference
SharedPreferences.Editor spedit = sp.edit();
//Put the login details as strings
spedit.putString("user", username);
spedit.putString("pass", password);//May not need to store password
//Close the editor
spedit.commit();
//Display a Toast saying login was a success
Toast.makeText(getBaseContext(), "SUCCESS!", Toast.LENGTH_SHORT).show();
} else {
//Display a Toast saying it failed.
Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
}
}
}
} catch(Exception e){
e.printStackTrace();
//Display toast when there is a connection error
//Change message to something more friendly
Toast.makeText(getBaseContext(), "Login Unsuccessful.", Toast.LENGTH_SHORT).show();
}
}//END onClick()
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//END convertStreamToString()
}
package com.kibriaali.logintutorial;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.content.SharedReferences;
导入android.os.Bundle;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.Toast;
公共类主扩展活动实现OnClickListener{
编辑文本etUser,etPass;
按钮博客;
//创建将输入分配给它们的字符串变量
字符串用户名、密码;
//创建一个HTTPClient作为表单容器
HttpClient-HttpClient;
//使用HTTP POST方法
HttpPost-HttpPost;
//为要发送的输入数据创建数组列表
ArrayList名称值对;
//创建HTTP响应和HTTP实体
HttpResponse响应;
http实体;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
初始化();
}
私有无效初始化(){
//TODO自动生成的方法存根
etUser=(EditText)findViewById(R.id.etUser);
etPass=(EditText)findViewById(R.id.etPass);
bLogin=(按钮)findviewbyd(R.id.bSubmit);
//现在设置onclick侦听器
setOnClickListener(this);
}
公共void onClick(视图v){
//这就是我们现在工作的地方
//创建新的默认HTTPClient
httpclient=新的DefaultHttpClient();
//以php文件的URL作为参数创建新的HTTP POST
httppost=新的httppost(“http://127.0.0.1/wamp/www/index.php"); //92.4.131.132 //127.0.0.1 //10.0.2.2
//将输入文本指定给字符串
username=etUser.getText().toString();
password=etPass.getText().toString();
//下一个代码块需要被try/catch块包围,才能正常工作
试一试{
//创建新数组列表
nameValuePairs=新的ArrayList(2);
//将它们放入数组列表中
添加(新的BasicNameValuePair(“用户”、“用户名”);
添加(新的BasicNameValuePair(“pass”、“password”);
//将数组列表添加到http post
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
//将已执行的表单容器分配给响应
response=httpclient.execute(httppost);//来自PHP文件的响应
//检查状态代码,需要检查状态代码200
if(response.getStatusLine().getStatusCode()==200){
//将响应实体分配给http实体
entity=response.getEntity();
//检查实体是否不为空
如果(实体!=null){
//使用已分配的接收数据创建新的输入流
InputStream instream=entity.getContent();
//创建新的JSON对象。将转换后的数据指定为参数。
JSONObject jsonResponse=新的JSONObject(convertStreamToString(instream));
//将json响应分配给本地字符串
String retUser=jsonResponse.getString(“用户”);//mySQL表字段
String retPass=jsonResponse.getString(“pass”);
//验证登录
如果(username.equals(retUser)和&password.equals(retPass)){//检查“retUser”和“retPass”是否与用户名/密码匹配
//通过获取首选项来创建新的共享首选项
//为共享首选项指定任何您喜欢的名称。
SharedReferences sp=GetSharedReferences(“登录详细信息”,0);
//编辑共享首选项
SharedReferences.Editor spedit=sp.edit();
//将登录详细信息设置为字符串
spedit.putString(“用户”,用户名);
spedit.putString(“pass”,password);//可能不需要存储密码
//关闭编辑器
提交();
//显示祝酒词,表示登录成功
Toast.makeText(getBaseContext(),“SUCCESS!”,Toast.LENGTH\u SHORT.show();
}否则{
//展示一个祝酒词,说它失败了。
Toast.makeText(getBaseContext(),“无效的登录详细信息”,Toast.LENGTH_SHORT.show();
}
}
}
}捕获(例外e){
e、 printStackTrace();
//有连接时显示toast
<?php
//turn off error reporting
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
//Create fields for the database
//server, username, password, database
$dbhost = "localhost"; //92.4.131.132 //127.0.0.1 //10.0.2.2
$dbuser = "root";
$dbpass = "";
$dbdb = "mobiledb";
//connect to mySQL
$connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error");
//Select the database
mysql_select_db($dbdb)or die("database selection error");
//Retrieve the login details via POST
$username = $_POST['username'];
$password = $_POST['password'];
//Query the table android login
$query = mysql_query("SELECT * FROM androidlogin WHERE user='$username' AND pass='$password'");
//check if there any results returned
$num = mysql_num_rows($query);
//If a record was found matching the details entered in the query
if($num == 1){
//Create a while loop that places the returned data into an array
while($list=mysql_fetch_assoc($query)){
//Store the returned data into a variable
$output = $list;
//encode the returned data in JSON format
echo json_encode($output);
}
//close the connection
mysql_close();
}
?>