1

I would like to achieve the following in the same session in this order:

  1. get android variable (imei)
  2. send variable to php
  3. use variable in sql
  4. send results back to android

I use the following:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contacts);

     // 01 - first i get imei
     TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
     IMEI = mngr.getDeviceId();

    // 02 - then i call class to post imei to php
    new loadData().execute();

     // 03 - on php side i use "select ... where $imei ..." 

    // 04 - get the results back to android
// (yes i am aware that this method is commented out, i will explain why below)
    //accessWebService();

    }

POST:

    class loadData extends AsyncTask<String, Integer, String> {
    private StringBuilder sb;
    private ProgressDialog pr;
    private HttpResponse req;
    private InputStream is;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected String doInBackground(String... arg0) {

          ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

          String imeino = String.valueOf(IMEI);

            nameValuePairs.add(new BasicNameValuePair("imeino",imeino));

                try
                {
                HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://blah/contacts.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost); 
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    InputStreamReader ireader = new InputStreamReader(is);
                    BufferedReader bf = new BufferedReader(ireader);
                    sb = new StringBuilder();
                    String line = null;
                    while ((line = bf.readLine()) != null) {
                        sb.append(line);
                    }
                    Log.e("pass 1", "connection success ");

            }
                catch(Exception e)

            {       
                    Log.e("Error Send",e.toString());
            }
                return id;     

    }
}

GET

 private class JsonReadTask extends AsyncTask<String, Void, String> {
      @Override
      protected String doInBackground(String... params) {
       HttpClient httpclient = new DefaultHttpClient();
       HttpPost httppost = new HttpPost(params[0]);
       try {
        HttpResponse response = httpclient.execute(httppost);
        jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

        System.out.println("jsonResult: "+jsonResult);
       }


       catch (ClientProtocolException e) {
        e.printStackTrace();
       } catch (IOException e) {
        e.printStackTrace();
       }
       return null;
      }

      private StringBuilder inputStreamToString(InputStream is) {
       String rLine = "";
       StringBuilder answer = new StringBuilder();
       BufferedReader rd = new BufferedReader(new InputStreamReader(is));

       try {
        while ((rLine = rd.readLine()) != null) {
         answer.append(rLine);
        }
       }

       catch (IOException e) {
        // e.printStackTrace();
        Toast.makeText(getApplicationContext(),
          "Error..." + e.toString(), Toast.LENGTH_LONG).show();
       }
       return answer;
      }

      @Override
      protected void onPostExecute(String result) {
       ListDrwaer();
      }
     }// end async task

     public void accessWebService() {
      JsonReadTask task = new JsonReadTask();
      // passes values for the urls string array
      task.execute(new String[] { "http://blah/contacts.php" });
     }

     // build hash set for list view
     public void ListDrwaer() {

      try {
       JSONObject jsonResponse = new JSONObject(jsonResult);
       JSONArray jsonMainNode = jsonResponse.optJSONArray("contact_info");

       for (int i = 0; i < jsonMainNode.length(); i++) {
        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
        String name = jsonChildNode.optString("Name");
        String number = jsonChildNode.optString("Number");
        String username = jsonChildNode.optString("Username");
        String status = jsonChildNode.optString("Status");

        System.out.println("jsonResult: "+jsonResult);
        System.out.println("getName: "+name);
        System.out.println("getNumber: "+number);
        System.out.println("getUsername: "+username);
        System.out.println("getStatus: "+status);

       }
      } catch (JSONException e) {
          System.out.println("Json Error" +e.toString());
          Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
      }
}

PHP:

    <?php

include 'config.php';

$con=mysql_connect("$servername", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$dbname")or die("cannot select DB");

$imei = isset($_POST['imeino']) ? $_POST['imeino'] : '';
//$imei = "000000000000000";

$sql = "select * from users WHERE IMEI ='$imei'"; 
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['contact_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 

    $f = fopen("log.txt", "w");
    fwrite($f, print_r($json, true));
    fclose($f);  

?>  

Ok here's the story with the code:

When I just POST [ new loadData().execute() ] and not GET [ accessWebService(); ] I can read my $imei = isset($_POST['imeino']) ? $_POST['imeino'] : ''; variable as 0000000000000 but of course I cannot return back the results because accessWebService() is commented out.

HOWEVER when I uncomment accessWebService() I can get the results back to android BUT they are null because now $imei = isset($_POST['imeino']) ? $_POST['imeino'] : ''; is empty.

so to summarize:

Whenever I call the GET method I lose my POST variable!

Siyual
  • 16,415
  • 8
  • 44
  • 58
user3560827
  • 632
  • 1
  • 5
  • 22
  • That's right. You could use `$_GET`, or, to support both `$_POST` and `$_GET` at the same time, use `$_REQUEST`. – Kenney Nov 28 '15 at 12:59
  • How can I edit my code to use $_REQUEST – user3560827 Nov 28 '15 at 13:03
  • 1
    Simply use your editor of choice to change `$_POST` to `$_REQUEST`. – Kenney Nov 28 '15 at 13:06
  • @Kenney Oh so you meant on .php, ok i did that, null is still returned by objects, post variable is lost – user3560827 Nov 28 '15 at 15:08
  • 1
    In you GET Java code, I don't see where you pass the IMEI to the PHP script. You should append it to the URL: `"http://blah/contacts.php?imeino=..."`. Btw, your PHP code is [vulnerable to SQL injection](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1). – Kenney Nov 28 '15 at 15:16
  • @Kenney OK your answer is perfect (from reading logcat) AWESOME!!! now I have to reevaluate everything i thought i knew about God, the universe and programming.. I am confused though, I would have done your answer on POST instead of GET (which it didn't work) but worked in the GET method as you suggested, so this means I can remove my POST method completely then.. confused but happy it's working, please post as answer and i will accept. You made my day buddy!!! – user3560827 Nov 28 '15 at 15:48
  • :-) You're welcome. The POST method should also still work, though (if it worked before!). – Kenney Nov 28 '15 at 16:03

1 Answers1

1

PHP

To support both GET and POST variables in PHP you could use $_REQUEST:

$imei = isset($_REQUEST['imeino']) ? $_REQUEST['imeino'] : '';

It's also wise to check if the parameter is set and return an error if it is not:

if ( empty($imei) ) {
    echo json_encode( array( 'error' => 'Missing imeino parameter' ) );
    return;
}

And, very important, sanitize the input before you pass it to mysql. This is dangerous:

$sql = "select * from users WHERE IMEI ='$imei'"; 

because someone might call your PHP script with contacts.php?imeino=';DROP TABLE users'. See here for more information.

Btw, PHP's mysql module is deprecated; I would recommend using PDO.

Java

The GET method of accessing your API only needs a small change to pass the imeino parameter to your PHP script:

 public void accessWebService( String imei ) {
    JsonReadTask task = new JsonReadTask();     
    task.execute(new String[] { "http://blah/contacts.php?imeino=" + imei });
 }

And, you'll need to call accessWebService with the IMEI.

Community
  • 1
  • 1
Kenney
  • 9,003
  • 15
  • 21