benid
benid

Reputation: 79

How do I send a string from Android to PHP? And how should my PHP script handle it?

I need to send a string obtained from EditText in android to the PHP to be used as an id to query the database. So, I got the string from EditText as follows:

childIDVal = childID.getText().toString();
 Toast.makeText(getApplicationContext(),childIDVal,Toast.LENGTH_LONG).show();
 // To do : transfer data to PHP
 transferToPhp(childIDVal);

So, what should my transferToPhp() contain? And also the php code is:

<?php 

if( isset($_POST["ChildID"]) ) {
 $data = json_decode($_POST["ChildID"]);
 $data->msg = strrev($data->msg);

 echo json_encode($data);

}

Is it okay? I am a newbie to both android and Php, so i need some help right now. Thanks!

Upvotes: 2

Views: 81

Answers (1)

Dumbo
Dumbo

Reputation: 1827

I' m offering you to use AsyncTask which reaches PHP file existing in your server using HttpClient:

    /*Sending data to PHP and receives success result*/
    private class AsyncDataClass extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost(params[0]);
        String jsonResults = "";
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            // SENDING PARAMETERS WITH GIVEN NAMES
            nameValuePairs.add(new BasicNameValuePair("paramName_1", params[1]));
            nameValuePairs.add(new BasicNameValuePair("paramName_2", params[2]));
            // ...
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpClient.execute(httpPost);
            jsonResults = inputStreamToString(response.getEntity().getContent()).toString();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonResults;
    }

    // DO SOMETHING BEFORE PHP RESPONSE
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    // DO SOMETHING AFTER PHP RESPONSE
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if(result.equals("") || result.equals(null)){
            return;
        }

        // Json response from PHP
        String jsonResult = returnParsedJsonObject(result);

        // i.e.
        if (jsonResult.equals("some_response") {
            // do something
        }
    }

    // READING ANSWER FROM PHP
    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        try {
            while ((rLine = br.readLine()) != null) {
                answer.append(rLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return answer;
    }
}

// GET ALL RETURNED VALUES FROM PHP
private String returnParsedJsonObject(String result){
    JSONObject resultObject;
    String returnedResult = "0";
    try {
        resultObject = new JSONObject(result);
        returnedResult = resultObject.getString("response");
        String value1 = resultObject.getString("value1");
        String value2 = resultObject.getString("value2");
        //...
        // do something with retrieved values
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return returnedResult;
}

To send some parameters use:

AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute("server_url", param1, param2,...);

Hope it helps you.

Upvotes: 1

Related Questions