Sending JSON Data to Server using Async Thread..

If you want to send JSON data from Android app to a server, how do you go about doing it. Follow the steps below to use Async thread to do it.

In the Android Manifest file add following permissions,

—————

<uses-permission android:name=”android.permission.INTERNET” />

<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />

The App Layout & Views

———————–

Main layout is LinearLayout

Three EditTextViews “FirstName, LastName & Age”

One Button to send “post” data to the server.

On button add attribute onclick and corresponds to the java function that is in current Activity

The App Layout for main_activity.xml

<LinearLayout android:layout_width=”fill_parent”

android:layout_height=”fill_parent”

android:layout_marginLeft=”16dp”

android:layout_marginTop=”16dp”

android:layout_marginRight=”16dp”

android:layout_marginBottom=”30dp”

android:orientation=”vertical”>
<EditText android:layout_width=”fill_parent”

android:id=”@+id/FirstName”

android:layout_height=”40dp”

android:hint=”First Name”

android:background=”#f3f3f3″

android:paddingLeft=”5dp”

android:layout_marginTop=”30dp”/>

<EditText android:layout_width=”fill_parent”

android:id=”@+id/LastName”

android:layout_height=”40dp”

android:hint=”Last Name”

android:background=”#f3f3f3″

android:paddingLeft=”5dp”

android:layout_marginTop=”15dp”/>

<EditText android:layout_width=”fill_parent”

android:id=”@+id/Age”

android:layout_height=”40dp”

android:hint=”Age”

android:background=”#f3f3f3″

android:paddingLeft=”5dp”

android:layout_marginTop=”15dp”

android:inputType=”number”/>

<Button android:layout_width=”190dp”

android:layout_height=”50dp”

android:layout_gravity=”center_horizontal”

android:layout_marginTop=”16dp”

android:text=”Submit”

android:textSize=”20sp”

android:id=”@+id/userinfo”

android:onClick=”senddatatoserver”/>

</LinearLayout>,

Activity

In the activity, create method to do the following:

Get reference to defined views in layout file.

Add function in activity that corresponds to layout button in function.

Get data from referenced views.

Create JSON object and add data to it with key value pairs.

Convert JSON object to string and send to Async Network background call thread.

 public class DashboardActivity extends Activity {

    EditText AgeView;

    EditText LastNameView;

    EditText FirstNameView;

    String FirstName;

    String LastName;

    String Age;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

       //Get reference to the defined views in layout file

        FirstNameView = (EditText) findViewById(R.id.FirstName);

        LastNameView = (EditText) findViewById(R.id.LastName);

        AgeView = (EditText) findViewById(R.id.Age);

    }

    public void senddatatoserver(View v) {

      //function in the activity that corresponds to the layout button

        FirstName = FirstNameView.getText().toString();

        LastName = LastNameView.getText().toString();

        Age = AgeView.getText().toString();

        JSONObject post_dict = new JSONObject();

        try {

            post_dict.put(“firstname” , FirstName);

            post_dict.put(“firstname”, LastName);

            post_dict.put(“firstname”, Age);

        } catch (JSONException e) {

            e.printStackTrace();

        }

        if (post_dict.length() > 0) {

            new SendJsonDataToServer().execute(String.valueOf(post_dict));

           #call to async class

        }

//add background inline class here 

class SendJsonDataToServer extends Async<String,String,String>{

}

}

Async Background Task

Helps in creating the connection in a separate thread so the UI will not freeze.

Do following steps to implement it:

Create inline class within the activity and extend it from AsyncTask<String,void,String>.

Override method doInBackground and onPostExecute.

You may notice AsyncTask has three parameters associated with it <String,void,String>.

The first one corresponds to the type of parameters passed to doInBackground, the second corresponds to type of parameters passed to onprogressUpdate function, and the third corresponds to type of parameters passed to onpostexecute function.

class SendDataToServer extends AsyncTask <String,String,String>{

    @Override

    protected String doInBackground(String… params) {       

    }    

    @Override

    protected void onPostExecute(String s) {

        }

    }

}

Network call

In the doInBackground do following things.

Create Url object for your URL.

 Open url connection from the url object.

 Set headers and output stream.

Write data to output stream.

 Send the POST request.

 Get response Inputstream, convert it to String and return it.

@Override

protected String doInBackground(String… params) {

    String JsonResponse = null;

    String JsonDATA = params[0];

 HttpURLConnection urlConnection = null;

 BufferedReader reader = null;

 try {

 URL url = new URL(“http://appliedinformatics.com/trialx&#8221;);

 urlConnection = (HttpURLConnection) url.openConnection();

 urlConnection.setDoOutput(true);

 // is output buffer writter

 urlConnection.setRequestMethod(“POST”);

 urlConnection.setRequestProperty(“Content-Type”, “application/json”);

 urlConnection.setRequestProperty(“Accept”, “application/json”);

//set headers and method

 Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), “UTF-8”));

 writer.write(JsonDATA);

// json data

 writer.close();

 InputStream inputStream = urlConnection.getInputStream();

//input stream

 StringBuffer buffer = new StringBuffer();

 if (inputStream == null) {

 // Nothing to do.

 return null;

 }

 reader = new BufferedReader(new InputStreamReader(inputStream));

 String inputLine;

 while ((inputLine = reader.readLine()) != null)

 buffer.append(inputLine + “\n”);

 if(buffer.length() == 0) {

 // Stream was empty. No point in parsing.

 return null;

 }

 JsonResponse = buffer.toString();

//response data

 Log.i(TAG,JsonResponse);

 try {

//send to post execute

 return JsonResponse;

 } catch (JSONException e) {

 e.printStackTrace();

 }

 return null;

 } catch (IOException e) {

 e.printStackTrace();

 }

 finally {

 if (urlConnection != null) {

 urlConnection.disconnect();

 }

 if (reader != null) {

 try {

 reader.close();

 } catch (final IOException e) {

 Log.e(TAG, “Error closing stream”, e);

 }

 }

 }

 return null;

}
Thank you please comment if you like.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s