php - Android 系统与 php mysql 之间的连接但出现错误

标签 php android mysql json android-asynctask

我有登录 Activity ,需要在 android 和 php mysql 之间进行连接,使用 jsn 从 php 获取响应,并使用 asynctask 在后台进行连接,但系统在 logcat 中显示响应为空。

日志猫

02-10 10:20:04.053: W/IInputConnectionWrapper(1797): showStatusIcon on inactive InputConnection
02-10 10:20:11.717: W/EGL_genymotion(1797): eglSurfaceAttrib not implemented
02-10 10:20:21.840: W/INbUFFERED Reader(1797): before  the buffered reader beguin
02-10 10:20:21.844: W/INbUFFERED Reader(1797): the JsonObject is {"message":"No User found","success":0}
02-10 10:20:21.844: W/INbUFFERED Reader(1797): before  the Parsing beguin
02-10 10:20:21.844: W/INbUFFERED  2 Reader(1797): the JsonObject is{"message":"No User found","success":0}
02-10 10:20:21.860: W/EGL_genymotion(1797): eglSurfaceAttrib not implemented

我认为问题出在 php 文件中,但我不知道在哪里,也没有找到它。

如果有人可以帮助我,我将不胜感激。

这是mysql中的表(这是一个测试)

-- Table structure for table `members`
--

CREATE TABLE IF NOT EXISTS `members` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `members`
--


INSERT INTO `members` (`id`, `user_name`, `password`) VALUES
(1, 'cptjs', 'cpt'),
(2, 'lt_p_g', 'lt123'); 

db_config.php

<?php

$hostname_localhost ="localhost";
$database_localhost ="fil";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);

?>

检查.php

<?php

require_once('db_config.php'); 


// array for JSON response
$response = array();




  if(isset($_GET['pid'])){


     $pid = $_GET['pid'];   



     $query_search = "select * from members where id = '".$pid."'";  

     $query_exec = mysql_query($query_search) or die(mysql_error());

   if (mysql_num_rows($query_exec)>0) 
   {
        $result = mysql_fetch_array($query_exec);

        $person = array();
        $response["pid"]=$result["id"];
        $person["username"]=$result["user_name"];
        $person["password"]=$result["password"];



   error_log(print_r($response, true));
   // success
        $response["success"] = 1;

   // user node
        $response["person"] = array();

        array_push($response["person"], $person);

   // echoing JSON response
        echo json_encode($response);

    }
    else
    {




    error_log(print_r($response, true));


   // no user found
            $response["success"] = 0;
            $response["message"] = "No User found";


  error_log(print_r($response, true));

   // echo no users JSON
           echo json_encode($response);
    }
}
else 
{
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) are missing";

    // echoing JSON response
    echo json_encode($response);
}    
?>

JSONParser.java

package pack.coderzheaven;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // 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 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();
             * 
             * }
             */

            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 {

            Log.w("INbUFFERED Reader", "before  the buffered reader beguin");
            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);

            }
            is.close();

            json = sb.toString().substring(0, sb.toString().length() - 1);
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            Log.w("INbUFFERED Reader", "the JsonObject is " + jObj);
            Log.w("INbUFFERED Reader", "before  the Parsing beguin");
            jObj = new JSONObject(json);

            Log.w("INbUFFERED  2 Reader", "the JsonObject is" + jObj);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

AndroidPHPConnectionDemo.java

package pack.coderzheaven;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidPHPConnectionDemo extends Activity {
    Button b;
    EditText et, pass;
    String Username, Password;
    TextView tv;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;

    String pid;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    // single person url
    // ******************************************************************
    // the localhost in the google android emulator = 10.0.2.2
    // the localhost in the genymotion emulator = 10.0.3.2
    // ******************************************************************
    private static final String url_check_login = "http://10.0.3.2/check.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PERSON = "person";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "username";
    private static final String TAG_pass = "password";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        b = (Button) findViewById(R.id.Button01);
        et = (EditText) findViewById(R.id.username);
        pass = (EditText) findViewById(R.id.password);
        tv = (TextView) findViewById(R.id.tv);

        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                // Getting complete person details in background thread
                new CheckLogin().execute();

            }
        });
    }

    /**
     * Background Async Task to Get complete person details
     * */
    class CheckLogin extends AsyncTask<String, String, String> {

        JSONArray productObj;

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AndroidPHPConnectionDemo.this);
            pDialog.setMessage("Loading person details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Getting person details in background thread
         * */

        @Override
        protected String doInBackground(String... arg0) {

            // updating UI from Background Thread

            // Check for success tag
            int success;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("pid", pid));

                // getting person details by making HTTP request
                // Note that person details url will use GET request
                JSONObject json = jsonParser.makeHttpRequest(url_check_login,
                        "GET", params);

//Log.e("JsonObject", json.toString());
// check your log for json response
// Log.d("Single person Details", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // successfully received person details
                    productObj = json.getJSONArray(TAG_PERSON); // JSON Array

                }

                else {
                    // product with pid not found
                }
            } 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 got all details
            if (productObj != null) {
                try {
                    // get first product object from JSON Array
                    JSONObject person = productObj.getJSONObject(0);

                    et.setText(person.getString(TAG_NAME));
                    pass.setText(person.getString(TAG_pass));

                    Log.e("success in login", "SUCCESS IN LOGIN");

                } catch (Exception e) {

                    e.printStackTrace();
                }

            }

            pDialog.dismiss();
        }
    }

}

最佳答案

在您的 MySQL 表中,将 id 更改为 pid。现在,在您的 xml 文件中,创建一个 textview 并为其指定 pid 的 id 和“gone”的可见性。在代码中

b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                // Getting complete person details in background thread
                new CheckLogin().execute();

            }

在 public void onClick(View v) { 之后,输入 String pid = (TextView)v.findViewById(R.id.pid).getText().toString();……希望这有帮助

关于php - Android 系统与 php mysql 之间的连接但出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21675085/

相关文章:

PHP 和 SQL 登录 - "User Not Found"

java - 使用Java Sockets发送ByteArray(Android编程)

mysql - 查找所有出现的相同值

php - 使用 PHP 重复数据删除 mysql 结果

php - 如何从同一服务器上的另一个页面提取特定div的内容?

扩展 Kotlin 基类的 Java 类无法调用基类的内部方法

mysql - MySQL 触发器创建错误 : 1064

javascript - mysql 和 XMLHttpRequest + PHP 的问题

php - 最佳实践 : Store Large Form Values into Database

Android改造导致socket超时异常