Last updated on January 8th, 2020 at 10:15 pm
In this post we are going to create a simple Android application in which we can send data to PHP webservice and get response from that service. In my last post i explain you how to read data from webservice and display in our android application. Today most of application used internet to send information and get updates from server. Download
A brief introduction what we are going to create. In this app first we create a EditText field where we write some thing and one button. When user press button we send EditText field data to service where we get posted data from application and we also perform (CRUD) operation but i simply echo that data and return same data as a response.
Start your New Android Project
1. Create a new project in Eclipse from File ⇒ New ⇒ Android Application Project. I had left my main activity name as MainActivity.java .
2. As we are Send and Recieve the JSON by making HTTP calls, we need to add INTERNET permission in our AndroidManifest.xml file. Open AndroidManifest.xml and add the following permission.
<uses-permission android:name="android.permission.INTERNET"/>
AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.rest" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="19" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.rest.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
3. Now open your activity_main.xml inside res ⇒ layout folder and create a EditText and button through which we can write and send data to webservice. And display result.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="132dp" android:ems="10" android:hint="@string/hint" android:singleLine="true" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText1" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:text="@string/send" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="51dp" android:text="Send Data to Server" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>
4. Now open your MainActivity.java inside src ⇒MainActivity.java. In this file we send data to webservice and get response note that i also use some extra jar file (httpclient-4.1-beta1.jar) to make my app work .
package com.rest; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { String name; Button button; // define url public static String URL = "<YOUR_API_LINK>"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub new AsyncTaskPayment().execute(); } }); } private class AsyncTaskPayment extends AsyncTask<String, Void, Void> { private final HttpClient Client = new DefaultHttpClient(); private String Content; private String Error = null; private final String TAG = null; private ProgressDialog Dialog = new ProgressDialog(MainActivity.this); @Override protected void onPreExecute() { Dialog.setMessage("Wait.."); Dialog.show(); Log.e(TAG, "------------------------------------- Here"); } protected Void doInBackground(String... urls) { try { HttpPost httppost = new HttpPost(URL); // Field EditText name = (EditText) findViewById(R.id.editText1); String nm = name.getText().toString(); JSONObject jObject = new JSONObject(); jObject.put("name", nm); MultipartEntity se = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE); se.addPart("request", new StringBody(jObject.toString())); httppost.setEntity(se); HttpResponse resp = Client.execute(httppost); Content = EntityUtils.toString(resp.getEntity()); Log.e("Response", "--------------------------------" + Content); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { // TODO Auto-generated method stub Dialog.dismiss(); // Log.e("ERROR", "--------------------------------" + Content); Toast.makeText(getBaseContext(), Content, Toast.LENGTH_LONG).show(); } } @Override protected void onStop() { super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
In above java code i create a AsyncTask to run this process and inside i call DefaultHttpClient() and call HttpPost() to send data in post method and create json object and pass my EditText field data to webservice. And data is send to server we get some response and convert that response to string using EntityUtils and save it to string variable.
Content = EntityUtils.toString(resp.getEntity());
Import jar to your project
Right click on your project folder inside eclipse ⇒ Build Path ⇒Add External Archives ⇒Browser external jar you want to use and select them. Now again right click on your project and go to Properties ⇒ Java Build Path ⇒ Order and Export.
PHP WebService
<?php $decode = json_decode($_REQUEST['request']); $json = $decode->name; header('Content-type: application/json'); echo json_encode($json); ?>
This is simple php code to return the get data.
Now your application is ready to test.