2

我的 android 模拟器正在向 PHP 脚本发送请求,以访问 MySQL 数据。我通过为 sql 查询提供值来检查 PHP 脚本,并且能够在我的 Android 模拟器中获取它。但我无法在 PHP 中使用我从 Android 发送的 JSON 数据。那么,如何从 PHP 中读取 JSON 数据呢?

获取详细信息.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 的值。但无法将“成功”的值放入变量中。

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

用户函数.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 的新手。谢谢..

4

2 回答 2

0

我省略了 patid.getText() 和 mobnum.getText() 的 .toString()。所以我应该像下面这样通过。否则 EditText 的名称将被传递。

 json = userFunctions.loginUser(patid.getText().toString(), mobnum.getText().toString()); 
于 2013-04-28T10:40:19.047 回答
0

您可以在 PHP API 文件中简单地读取移动发布的 json 数据,如下所示。

<?php
$foo = file_get_contents("php://input");
$result=json_decode($foo, true);
print"<pre>";
print_r($result);
?>
于 2015-06-30T10:15:50.380 回答