学习基本的 JSON,MySQL 及其联系

Learning Basic JSON, MySQL and its connection

我目前正在开发一个 android 应用程序,之前我使用离线 SQLite 数据库 android,现在我正在尝试学习在线数据库,(目前仍在使用 XAMPP本地主机)

我已经阅读了一些教程,但对 JSON、MySQL 及其连接仍然有点困惑..

我想在这里问几个基本概念,弄清楚我得到的东西,防止自己再迷路,

(如果我错了请纠正我)所以简而言之,当我想让我的应用程序在线存储数据库并进行 CRUD(创建、读取、更新、删除)操作时,这是应该做的:

  1. 在我的 .php 文件和我的数据库之间建立连接

  2. 将我的 android 设备与我的 php 文件连接

  3. 使用JSON

  4. 将数据从java传递到php
  5. PHP 将使用 $_POST 或 $_GET 获取数据,然后将其存储在局部变量中

  6. PHP 将使用来自 java

  7. 的传递变量进行查询
  8. PHP 将 return 使用 JSON_encode

  9. Java 也会用 JSON 获取它们

然后我看了看这个教程-MyBringBack Tutorial

并尝试实现那里的内容..我尝试在我的电脑浏览器中运行这些代码并且它有效,但是当我尝试在我的 android 设备中运行这些代码时,它不起作用,它没有return任何东西,我不知道我错在哪里,

你能帮我检查一下这些代码吗?

提前致谢

这是我的代码:

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
}
?> 

可能还有其他问题,但可以肯定的是,在 Java 中您不能使用 == 比较字符串,例如 if(method == "POST") 您应该将其替换为 if(method.equals("POST"))对于字符串比较

的所有其他==也是如此

一旦 makeHttpRequest() 被调用,没有任何东西与方法 if 语句匹配, 并且没有进行 http 调用,因此该方法将 return Null。