android与php和mysql的连接返回空结果
我正在创建登录活动,该活动需要在android系统和php mysql之间使用json进行连接,以返回响应,并使用asynctask在后台进行连接,但当我使用id进行mysql查询选择时,结果总是空的 我知道错误在java代码中的id字符串中,但我不知道如何分配此字符串“id”以获取数据库中的id,然后检索所需的数据。如果有人能帮助我,我将不胜感激 memebers.sql check.php JSONParser.javaandroid与php和mysql的连接返回空结果,php,android,mysql,json,android-asynctask,Php,Android,Mysql,Json,Android Asynctask,我正在创建登录活动,该活动需要在android系统和php mysql之间使用json进行连接,以返回响应,并使用asynctask在后台进行连接,但当我使用id进行mysql查询选择时,结果总是空的 我知道错误在java代码中的id字符串中,但我不知道如何分配此字符串“id”以获取数据库中的id,然后检索所需的数据。如果有人能帮助我,我将不胜感激 memebers.sql check.php JSONParser.java package pack.coderzheaven; 导入java.i
package pack.coderzheaven;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.util.List;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.client.utils.URLEncodedUtils;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.util.Log;
公共类JSONParser{
静态InputStream为空;
静态jsonobjectjobj;
静态字符串json=“”;
//建造师
公共JSONParser(){
}
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数){
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“获取”){
//请求方法是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();
}
试一试{
Log.w(“缓冲读取器”,“缓冲读取器开始之前”);
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
某人附加(行);
}
is.close();
json=sb.toString().substring(0,sb.toString().length()-1);
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
Log.w(“缓冲读取器”,“JsonObject为”+jObj);
Log.w(“缓冲读取器”,“在解析beguin之前”);
jObj=新的JSONObject(json);
Log.w(“缓冲2读取器”,“JsonObject为”+jObj);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
}
AndroidHPConnectionDemo.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;
import android.widget.Toast;
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
******************************************************************
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));
Toast.makeText(
getBaseContext(),
et.getText().toString() + pass.getText().toString(),
Toast.LENGTH_LONG).show();
Log.e("success in login", "SUCCESS IN LOGIN");
} catch (Exception e) {
e.printStackTrace();
}
}
pDialog.dismiss();
}
}
}
import java.util.ArrayList;
导入java.util.List;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.message.BasicNameValuePair;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
导入android.widget.Toast;
公共类AndroidHPConnectionDemo扩展活动{
按钮b;
编辑文本,通过;
字符串用户名、密码;
文本视图电视;
HttpPost-HttpPost;
字符串缓冲区;
HttpResponse响应;
HttpClient-HttpClient;
列出nameValuePairs;
串pid;
//进度对话框
私人对话;
//JSON解析器类
JSONParser JSONParser=新的JSONParser();
//单人网址
******************************************************************
私有静态最终字符串url\u检查\u登录=”http://10.0.3.2/check.php";
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串标记_PERSON=“PERSON”;
私有静态最终字符串标记_PID=“PID”;
私有静态最终字符串标记\u NAME=“username”;
私有静态最终字符串标记\u pass=“password”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b=(按钮)findViewById(R.id.Button01);
et=(EditText)findViewById(R.id.username);
pass=(EditText)findViewById(R.id.password);
tv=(TextView)findviewbyd(R.id.tv);
b、 setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//在后台线程中获取完整的人员详细信息
新建CheckLogin().execute();
}
});
}
/**
*获取完整人员详细信息的后台异步任务
<?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_search = "select * from members where user_name = 'cptjs' AND password = 'cpt'";
$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);
}
?>
02-11 10:33:33.165: W/IInputConnectionWrapper(3520): showStatusIcon on inactive InputConnection
02-11 10:33:47.889: W/EGL_genymotion(3520): eglSurfaceAttrib not implemented
02-11 10:33:55.789: W/INbUFFERED Reader(3520): before the buffered reader beguin
02-11 10:33:55.793: W/INbUFFERED Reader(3520): the JsonObject is {"message":"No User found","success":0}
02-11 10:33:55.793: W/INbUFFERED Reader(3520): before the Parsing beguin
02-11 10:33:55.793: W/INbUFFERED 2 Reader(3520): the JsonObject is{"message":"No User found","success":0}
02-11 10:33:55.813: W/EGL_genymotion(3520): eglSurfaceAttrib not implemented
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 == "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;
}
}
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;
import android.widget.Toast;
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
******************************************************************
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));
Toast.makeText(
getBaseContext(),
et.getText().toString() + pass.getText().toString(),
Toast.LENGTH_LONG).show();
Log.e("success in login", "SUCCESS IN LOGIN");
} catch (Exception e) {
e.printStackTrace();
}
}
pDialog.dismiss();
}
}
}
package com.techlovejump.androidphpmysql;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
JSONObject jobj = null;
ClientServerInterface clientServerInterface = new ClientServerInterface();
TextView textView;
String ab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
//start background processing
new RetreiveData().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class RetreiveData extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
jobj = clientServerInterface.makeHttpRequest("http://www.yourwebsite.com/at/serverside.php");
try {
ab = jobj.getString("key");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ab;
}
protected void onPostExecute(String ab){
textView.setText(ab);
}
}
}