2

My android emulator is sending a request to PHP script, to access MySQL data. I checked PHP script by giving values to sql query & is able to get it in my Android emulator.But i`m not able to use JSON data in PHP, which i sent from Android. So, how to read JSON data from PHP?

get_details.php

The if($tag ==..) block and if (isset($_POST['pid'])) block are executing, but when i use it with query, i cannot get value from database

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

        }
    });
}


}

For the query values i have given in PHP, Toast is showing values from database for patid,name,mobile and also success=1.But can`t get value of 'success' into a variable.

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

if i am to use, json_decode() in php how should i call it? Any help is greatly appreciated as i`m a newbie to android.Thanks..

7

2 Answers 2

0

I omitted .toString() for patid.getText() and mobnum.getText(). So i should pass like below. Otherwise name of EditText will get passed.

 json = userFunctions.loginUser(patid.getText().toString(), mobnum.getText().toString()); 
Sign up to request clarification or add additional context in comments.

Comments

0

You can simply read mobile posted json data in your PHP API file as below.

<?php
$foo = file_get_contents("php://input");
$result=json_decode($foo, true);
print"<pre>";
print_r($result);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.