Search code examples
androidpostwebserverwebservice-clientandroid-webservice

Cannot post variable from android client to php server


I develop an android code for transmit and received between android apps and PHP. The received part which is based on JSON, is properly working. I have tested by set variable manually in PHP code. However, when I have posted the variable from android to php, it cannot receive it. Anyone can tell me the problem ?


Solution

  • @Override
    protected String doInBackground(Void... params) {
    
    
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    
    
        nameValuePairs.add(new BasicNameValuePair("username", <Your username here>));
    
    
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(<Your URL to php file>);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            HttpResponse response = httpclient.execute(httppost); // Execute Post to URL
            String st = EntityUtils.toString(response.getEntity()); // This is the result from php web
            Log.d(TK_Configuration.TAG, "In the try Loop" + st); // Still executing
            finalResult = st; // You should register a variable for finalResult;
    
        } catch (Exception e) {
            Log.d(TK_Configuration.TAG, "Connection error : " + e.toString());
        }
        return "OK";
    
    }
    
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    
        // After that, you will have final result and process to do with it here
        // Below is my simple code, please change it
        if(finalResult.equals("1")){
            Toast.makeText(context, context.getResources().getString(R.string.upload_bike_success), Toast.LENGTH_SHORT).show();
    
        }
        else{
            Toast.makeText(context, context.getResources().getString(R.string.upload_bike_fail), Toast.LENGTH_SHORT).show();
        }
        // End
    }
    


    Please try this, and one more point, you should use Gson library to decode JSON quickly to Java Object after you got JSON string from server.
    Note: Replace TK_Configuration.TAG << by your TAG.