【发布时间】:2015-03-05 18:00:15
【问题描述】:
我目前正在开发一个android应用程序,以前我使用离线SQLite数据库为android工作,现在我正在尝试学习在线数据库,(目前仍在使用XAMPP localhost)
我已经阅读了一些教程,但仍然对 JSON、MySQL 及其连接感到困惑..
我想在这里问几个基本概念,以澄清我得到了什么,并防止自己进一步迷失方向,
(如果我错了,请纠正我)总之,当我想让我的应用程序在线存储数据库并进行 CRUD(创建、读取、更新、删除)操作时,应该这样做:
在我的 .php 文件和我的数据库之间建立连接
用我的 php 文件连接我的安卓设备
使用 JSON 将数据从 java 传递到 php
PHP 将使用 $_POST 或 $_GET 获取数据,然后将其存储在局部变量中
PHP 将使用从 java 传递的变量进行查询
PHP 将使用 JSON_encode 返回一些内容
Java 也会使用 JSON 获取它们
然后我看了这个教程 - MyBringBack Tutorial
并尝试实现那里的内容.. 我尝试在我的 pc 浏览器中运行这些代码并且它有效,但是当我尝试在我的 android 设备中运行这些代码时,它不起作用,它不会返回任何事情,我不知道我错在哪里,
您能帮我检查一下这些代码吗?
提前谢谢你
这是我的代码:
LoginActivity.java
public class LoginActivity extends Activity implements View.OnClickListener {
private EditText etUsername;
private EditText etPassword;
private Button bLogin, bRegis, bAdmin;
userSessionManager session;
Database checkLogin = new Database(LoginActivity.this);
static final String loginUrl = "http://192.168.0.102:8081/webservice/doLogin.php";
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "Success";
private static final String TAG_MESSAGE = "Message";
private ProgressDialog pDialog;
String a,b;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
session = new userSessionManager(getApplicationContext());
Declaration();
bLogin.setOnClickListener(this);
bRegis.setOnClickListener(this);
bAdmin.setOnClickListener(this);
}
private void Declaration() {
// TODO Auto-generated method stub
etUsername = (EditText) findViewById(R.id.etLoginUsername);
etPassword = (EditText) findViewById(R.id.etLoginPassword);
bLogin = (Button) findViewById(R.id.bLogin);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogin:
new AttemptLogin().execute();
break;
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
//Toast.makeText(getApplicationContext(), username+password, Toast.LENGTH_SHORT).show();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
//Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(loginUrl, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
startActivity(intent);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
Toast.makeText(getApplicationContext(), "a",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.thesis.teamizer.ROOTVIEW");
startActivity(intent);
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
Toast.makeText(getApplicationContext(), a,
Toast.LENGTH_SHORT).show();
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
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;
}
}
doLogin.php
<?php
require("config.inc.php");
if(!empty($_POST)){
//gets user's info based off a username
if(empty($_POST['username']) || empty($_POST['password'])){
$response["success"] = 0;
$response["message"] = "Please enter both username n password";
die(json_encode($response));
}
$query = "SELECT MemberUsername, MemberPassword From Member Where MemberUsername = :username";
$query_params = array(':username' => $_POST['username']);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch(PDOException $ex){
$response["succeess"] =0;
$response["message"]= "Database error1. please try again";
die(json_encode($response));
}
$validate_info=false;
//fetching rows from query
$row = $stmt->fetch();
$login_ok=false;
if($row){
if($_POST['password']==$row['MemberPassword']){
$login_ok=true;
}
}
if($login_ok){
//userLogin
$response["success"]=1;
$reponse["message"] = "Login Successfull";
die(json_encode($response));
}else{
$response["success"]=0;
$response["message"]= "Login Failed";
die(json_encode($response));
}
}
else {
?>
<h1> Register </h1>
<form action = "doLogin.php" method="post">
Username : <br />
<input type = "text" name = "username" placeholder= "user name"> <br/>
Password : <br />
<input type = "password" name = "password" placeholder= "password"> <br/>
<input type = "submit" value = "login" >
</form>
<?php
}
?>
【问题讨论】:
-
能否详细说明
it doesn't work, and I don't know where is my wrong? -
不起作用并不能告诉我们太多。怎么没用?你有错误吗?崩溃?数据损坏?没有数据?
-
它没有返回任何东西,我在 doInBackground 中创建了意图并检查从 php 传递到 java 的结果..
-
可能还有其他问题,但可以肯定的是,在 Java 中您无法使用
==比较字符串,例如if(method == "POST")您应该将其替换为if(method.equals("POST")) -
@Yazan 谢谢,找到了我的问题,是因为字符串,谢谢!