私の Android エミュレーターは、MySQL データにアクセスするために、PHP スクリプトに要求を送信しています。SQLクエリに値を指定してPHPスクリプトをチェックしましたが、Androidエミュレーターで取得できますが、Androidから送信したJSONデータをPHPで使用できません。では、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();
}
}
});
}
}
PHP で指定したクエリ値について、Toast はデータベースから patid、name、mobile および success=1 の値を表示しています。しかし、'success' の値を変数に取得できません。
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() をどのように呼び出す必要がありますか? 私はアンドロイドの初心者なので、どんな助けも大歓迎です.Thanks..