Simple JSON Parsing Example in Android – Part VI

In this blog post, ill show you how to Pass JSON data to Php as a Parameters.

My Other blog post on JSON Tutorial.

  1. Part I – What is JSON and how to code JSON data on Php
  2. Part II – How to retrieve a simplest JSON data in Android
  3. Part III – How to retrieve a JSON data to ListView in Android
  4. Part IV – How to retrieve a complex typed JSON data in Android
  5. Part V – How to retrieve a JSON data from a Secured Site with Basic Authentication
  6. Part VI – How to Pass a JSON data to Php as a Parameters

 

Please read Part I of this blog, there you can create JSON data in php. I’m using Example 5 from that blog in this tutorial for making this blog to be simple. Hope you have created JSON data in php, so lets get started with retrieving in Android.

Step 1: Create a new project File -> Android Project. While creating a new project give activity name as MainActivity and copy paste this code.


package com.skholingua.android.passing_params_using_json;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView outputText;
Button sendData;
EditText edtUser, edtPass;

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

outputText = (TextView) findViewById(R.id.textView1);
outputText.setMovementMethod(new ScrollingMovementMethod());
sendData = (Button) findViewById(R.id.button1);
edtUser = (EditText) findViewById(R.id.editText1);
edtPass = (EditText) findViewById(R.id.editText2);

sendData.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
requestData("http://serviceapi.skholingua.com/open-feeds/display_received_jsonparams.php");
}
});

}

public void requestData(String url) {
RequestPackage rp = new RequestPackage();
rp.setMethod("POST");
rp.setUri(url);
rp.setSingleParam("user", edtUser.getText().toString().trim());
rp.setSingleParam("pass", edtPass.getText().toString().trim());
MyTask task = new MyTask();
task.execute(rp);
}

@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;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

private class MyTask extends AsyncTask<RequestPackage, String, String> {

@Override
protected String doInBackground(RequestPackage... params) {
// TODO Auto-generated method stub
String content = MyHttpURLConnection.getData(params[0]);
return content;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
outputText.append(result + "\n");
}

}
}

Step 2: Create a new class, MyHttpURLConnection.java and copy paste this code.


package com.skholingua.android.passing_params_using_json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

public class MyHttpURLConnection {

public static String getData(RequestPackage requestPackage) {
// TODO Auto-generated method stub
BufferedReader reader = null;
String uri = requestPackage.getUri();

try {
URL url = new URL(uri);

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod(requestPackage.getMethod());
/*
* Json parameters requred params are converted to json object and
* passing as string value with a suffix "params=".
* Json Parameters can only send via POST method.
*/
JSONObject json = new JSONObject(requestPackage.getParams());
String param = "params=" + json.toString();
if (requestPackage.getMethod().equals("POST")) {
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
con.getOutputStream());
writer.write(param);
writer.flush();
}
con.connect();
InputStream is = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String data = null;
StringBuilder sb = new StringBuilder();
while ((data = reader.readLine()) != null) {
sb.append(data + "\n");
}
return sb.toString();

} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}

}

Step 3: Create a new class, RequestPackage.java and copy paste this code:


package com.skholingua.android.passing_params_using_json;

import java.util.HashMap;
import java.util.Map;

public class RequestPackage {

private String uri;
private String method;
private Map<String, String> params = new HashMap<String, String>();

public String getUri() {
return uri;
}

public void setUri(String uri) {
this.uri = uri;
}

public String getMethod() {
return method;
}

public void setMethod(String method) {
this.method = method;
}

public Map<String, String> getParams() {
return params;
}

public void setParams(Map<String, String> params) {
this.params = params;
}

public void setSingleParam(String key, String value) {
params.put(key, value);
}

}

Step 4: Open your activity_main.xml and copy paste this code:


<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: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="com.skholingua.android.passing_params_using_json.MainActivity" >

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Username" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Password"
android:inputType="textPassword" >
</EditText>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="Send Data" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="36dp"
android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Step 5: Open your AndroidManifest.xml and add Internet Permission.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.skholingua.android.passing_params_using_json"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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=".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>

ScreenShot:

Screenshot_2015-04-06-11-59-37 Screenshot_2015-04-06-12-00-14

 

 


Hope this helpful. Your valuable comments are always welcomed. It will help to improve my post and understanding.

Download Source Code from here.

durga chiranjeevi

durga chiranjeevi

I'm currently working as Android developer at Energy Alternatives India. Interested in Application and Game development.
durga chiranjeevi
Comments
  1. omid

Leave a Reply

Your email address will not be published. Required fields are marked *