我的android模拟器正在向PHP脚本发送请求,以访问MySQL数据。我通过给sql query&提供值来检查PHP脚本。能够在我的Android模拟器中获取它。但是我无法在PHP中使用JSON数据,这是我从Android发送的。那么,如何从PHP读取JSON数据?
get_details.php
if($ tag == ..)块和if(isset($ _ POST ['pid']))块正在执行,但当我用它查询时,我无法从数据库中获取值
<?php
$response = array();
$result = array();
$con = mysql_connect("localhost", "root", "system") or die(mysql_error());
mysql_select_db("patient", $con);
$tag = $_POST['tag'];
if ($tag == 'get_details')
{
if (isset($_POST['pid']))
{ $pid = intval($_POST['pid']); //PATID in Database is in BIGINT
$mob = $_POST['mob']; //MOBILE is in VARCHAR
//$result=mysql_query("SELECT * FROM patientinfo WHERE PATID =13 AND MOBILE= 25");
$result=mysql_query("SELECT * FROM patientinfo WHERE PATID =$pid AND MOBILE= $mob");
if (!empty($result))
{
$result = mysql_fetch_array($result);
$response["success"] = 1;
$response["patid"] = $result["PATID"];
$response["name"] = $result["FIRSTNAME"];
$response["mobile"] = $result["MOBILE"];
echo json_encode($response);
}
else {
$response["success"] = 2;
$response["message"] = "No patient found in that PatId";
echo json_encode($response);
}
}
else {
$response["success"] = 3;
$response["message"] = "PatientId Not Set";
echo json_encode($response);
}
}
else
{ $response["success"] = 4;
$response["message"] = "Tag not matching";
echo json_encode($response);
}
?>
Main_activity.java
public class Main_activity extends Activity {
String response;
EditText patid;
EditText mobnum;
TextView loginErrorMsg;
private static String KEY_SUCCESS ="success";
private static String KEY_PID ="patid";
private static String KEY_MOBNUM ="mobile";
private static String KEY_NAME ="name";
//private static String KEY_CREATED_AT ="created_at";
DatabaseHandler db;
UserFunctions userFunctions;
JSONObject json_user;
JSONObject json;
Intent listview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnLogin = (Button) findViewById(R.id.login_button);
btnLogin.setOnClickListener( new View.OnClickListener() {
public void onClick(View arg0) {
try{
patid = (EditText) findViewById(R.id.patid_field);
mobnum = (EditText) findViewById(R.id.pswd_field);
if( (patid!=null && patid.getText().length()!=0) && (mobnum!=null && mobnum.getText().length()!=0))
{
userFunctions = new UserFunctions();
json = userFunctions.loginUser(patid.toString(), mobnum.toString());
//Toast.makeText(getBaseContext(), json.getString("success"), Toast.LENGTH_LONG).show();
//Toast.makeText(getBaseContext(), json.getString("name"), Toast.LENGTH_LONG).show();
//Toast.makeText(getBaseContext(), json.getString("mobile"), Toast.LENGTH_LONG).show();
try{
if(json.getString(KEY_SUCCESS)!=null) loginErrorMsg.setText("Authenticated");
int res = Integer.parseInt(json.getString(KEY_SUCCESS)); //Unable to get value in res
Toast.makeText(getBaseContext(), "Res="+res, Toast.LENGTH_LONG).show();
if(res==1) //logged in
{
db = new DatabaseHandler(getApplicationContext());
json_user = json.getJSONObject("user");
userFunctions.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_PID),json_user.getString(KEY_NAME),json_user.getString(KEY_MOBNUM), json_user.getString(KEY_CREATED_AT));
Toast.makeText(getBaseContext(), "next", Toast.LENGTH_LONG).show();
listview= new Intent(Main_activity.this, activity_listview.class);
listview.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(listview);
Toast.makeText(getBaseContext(), "finish", Toast.LENGTH_LONG).show();
finish();
}
else{
Toast.makeText(getBaseContext(), "Invalid ID/Mob", Toast.LENGTH_LONG).show();
loginErrorMsg.setText("Invalid Patient-ID/Mobile No.");
}
}
}
catch(JSONException je)
{
Toast.makeText(getBaseContext(), "json Exception", Toast.LENGTH_LONG).show();
je.printStackTrace();
}
}
else
{
}
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
JsonParser.java
public class JsonParser {
static InputStream is= null;
static JSONObject jObj= null;
static String json = "";
public JsonParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) throws Exception
{
try{
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();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(Exception e1){
e1.printStackTrace();
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8); //or iso-8859-1
StringBuilder sb= new StringBuilder();
String line=null;
while((line = reader.readLine())!=null)
{
sb.append(line+ "\n"); // \n
}
is.close();
json = sb.toString();
Log.e("JSON", json);
}catch(Exception e1){
Log.e("Buffer Error", "Error converting result"+ e1.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
UserFunctions.java
public class UserFunctions {
private JsonParser jsonParser;
private static String loginUrl ="http://10.0.2.2/hcsapi/get_details.php";
private static String getdetails_tag ="get_details";
public UserFunctions()
{
jsonParser =new JsonParser();
}
public JSONObject loginUser(String patid, String mobnum)throws Exception
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag",getdetails_tag));
params.add(new BasicNameValuePair("pid",patid));
params.add(new BasicNameValuePair("mob",mobnum));
System.out.print(patid);
JSONObject json= jsonParser.getJSONFromUrl(loginUrl, params);
return json;
}
}
如果我要使用,php中的json_decode()应该怎么称呼它? 任何帮助都非常感谢,因为我是android.Thanks ..
的新手答案 0 :(得分:0)
我为patid.getText()和mobnum.getText()省略了.toString()。所以我应该通过如下。否则,EditText的名称将被传递。
json = userFunctions.loginUser(patid.getText().toString(), mobnum.getText().toString());
答案 1 :(得分:0)
您可以在PHP API文件中简单地阅读移动发布的json数据,如下所示。
<?php
$foo = file_get_contents("php://input");
$result=json_decode($foo, true);
print"<pre>";
print_r($result);
?>