This artical described how to used JSON in android. In this example we implement Registration an Login via JSON.explain below...
Step 1:
first,you have add manifest permission.
<uses-permission android:name="android.permission.INTERNET" />
Step 2:
create the Registratio and Login UserInteface (UI) field inside res/layout/login and registration xml class.
registration.xml
..................................................................................................................................................
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center"
android:orientation="vertical"
tools:ignore="ScrollViewSize" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:orientation="vertical"
android:paddingBottom="10dp"
android:paddingTop="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical"
android:padding="5dp" >
<EditText
android:id="@+id/editText_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:ems="10"
android:hint="@string/edit_name"
android:inputType="textPersonName"
android:textColorHint="@color/hint_edittextcolor"
android:textSize="14sp" >
</EditText>
<EditText
android:id="@+id/editText_mobile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:ems="10"
android:hint="@string/edit_mobile"
android:inputType="number"
android:textColorHint="@color/hint_edittextcolor"
android:textSize="14sp" />
<EditText
android:id="@+id/editText_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:ems="10"
android:hint="@string/edit_email"
android:inputType="textEmailAddress"
android:textColorHint="@color/hint_edittextcolor"
android:textSize="14sp" />
<EditText
android:id="@+id/editText_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:ems="10"
android:hint="@string/edit_pass"
android:inputType="textPassword"
android:textColorHint="@color/hint_edittextcolor"
android:textSize="14sp" />
<EditText
android:id="@+id/editText_cofPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:ems="10"
android:hint="@string/edit_confpass"
android:inputType="textPassword"
android:textColorHint="@color/hint_edittextcolor"
android:textSize="14sp" />
</LinearLayout>
<Button
android:id="@+id/btn_signUp"
android:layout_width="fill_parent"
android:layout_height="47dp"
android:layout_marginBottom="7dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="30dp"
android:text="@string/btn_submit" />
</LinearLayout>
</ScrollView>
</LinearLayout>
login.xml
.......................................................................................................................................................
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dip"
android:orientation="vertical" >
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:ems="10"
android:hint="@string/edit_email"
android:inputType="textEmailAddress"
android:textColorHint="@color/hint_edittextcolor"
android:textSize="14sp" />
<requestFocus />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:layout_marginTop="8dip"
android:ems="10"
android:hint="@string/edit_pass"
android:inputType="textPassword"
android:textColorHint="@color/hint_edittextcolor"
android:textSize="14sp" />
<Button
android:id="@+id/btn_signUp"
android:layout_width="fill_parent"
android:layout_height="47dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="40dp"
android:text="@string/btn_login" />
</LinearLayout>
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:stretchColumns="2" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="50dip"
android:layout_weight="1"
android:gravity="center"
android:text="@string/dolnt_Account" />
<TextView
android:id="@+id/textView_registration"
android:layout_width="wrap_content"
android:layout_height="50dip"
android:layout_gravity="right"
android:layout_marginRight="12dp"
android:gravity="right|center"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:text="@string/btn_submit"
android:textColor="@color/yellow"
android:textSize="20sp"
android:textStyle="bold|italic" />
</TableRow>
</TableLayout>
</LinearLayout>
</ScrollView>
Step 3:
create rest JSON Api class inside Src/RestAPI .java
package
com.example.androidbeginnerpoint;
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStream;
import
java.io.InputStreamReader;
import
java.util.ArrayList;
import
java.util.HashMap;
import
java.util.Map.Entry;
import
org.apache.http.HttpResponse;
import
org.apache.http.client.HttpClient;
import
org.apache.http.client.methods.HttpPost;
import
org.apache.http.entity.StringEntity;
import
org.apache.http.impl.client.DefaultHttpClient;
import
org.json.JSONObject;
import
android.content.Context;
import
android.util.Log;
@SuppressWarnings("deprecation")
public
class RestAPI {
String
apiUrl;
Context
context;
ArrayList<HashMap<String,
String>> ParameterList = new ArrayList<HashMap<String,
String>>();
public
String getApiUrl() {
return
apiUrl;
}
public
void setApiUrl(String apiUrl) {
this.apiUrl
= apiUrl;
}
public
String ResponseApi() {
InputStream
inputStream = null;
String
result = "";
JSONObject
jsonObject = new JSONObject();
try
{
for
(HashMap<String, String> map : ParameterList)
for
(Entry<String, String> mapEntry : map.entrySet()) {
jsonObject.accumulate(mapEntry.getKey(),mapEntry.getValue());
}
HttpClient
httpclient = new DefaultHttpClient();
HttpPost
httpPost = new HttpPost(apiUrl);
String
json = "";
json
= jsonObject.toString();
StringEntity
se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept",
"application/json");
httpPost.setHeader("Content-type",
"application/json");
HttpResponse
httpResponse = httpclient.execute(httpPost);
inputStream
= httpResponse.getEntity().getContent();
if
(inputStream != null)
result
= convertInputStreamToString(inputStream);
else
result
= "Did not work!";
}
catch (Exception e) {
Log.d("InputStream",
e.getLocalizedMessage());
}
return
result;
}
public
ArrayList<HashMap<String, String>> getParameterList() {
return
ParameterList;
}
public
void setParameterList(ArrayList<HashMap<String, String>>
parameterList) {
ParameterList
= parameterList;
}
private
static String convertInputStreamToString(InputStream inputStream)
throws
IOException {
BufferedReader
bufferedReader = new BufferedReader(
new
InputStreamReader(inputStream));
String
line = "";
String
result = "";
while
((line = bufferedReader.readLine()) != null)
result
+= line;
inputStream.close();
return
result;
}
}
Step 4:
create Resgistration.java class inside src folder.
package com.example.androidbeginnerpoint;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.Webnetware.Sqlitedatabase.DatabaseAdapter;
import com.Webnetware.adapter.ConnectionDetector;
import com.Webnetware.adapter.Listview_Utility;
import com.Webnetware.resApi.RestAPI;
public class Registrations extends Activity implements
OnFocusChangeListener,
android.view.View.OnClickListener
{
EditText
edit_name, edit_mobile, edit_email,editText_cofPassword,editText_password;
String
string_name, string_mobile, string_email,string_password ;
String
customerId="";
Button
btn_signUp;
ProgressDialog
progressdialog;
public
static final String Pssword = "PsswordKey";
public
static final String Email = "emailKey";
// get the rest api class
RestAPI
obj_restapi = new RestAPI();
//created all Json parameter store in array.you have to check json
ArrayList<HashMap<String,
String>> ParameterList = new ArrayList<HashMap<String,
String>>();
HashMap<String,
String> map = new HashMap<String, String>();
@Override
protected
void onCreate(Bundle savedInstanceState) {
//
TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_form);
edit_name
= (EditText) findViewById(R.id.editText_name);
edit_mobile
= (EditText) findViewById(R.id.editText_mobile);
edit_email
= (EditText) findViewById(R.id.editText_email);
editText_password
= (EditText) findViewById(R.id.editText_password);
editText_cofPassword
= (EditText) findViewById(R.id.editText_cofPassword);
btn_signUp
= (Button) findViewById(R.id.btn_signUp);
btn_signUp.setOnClickListener(this);
edit_name.setOnFocusChangeListener(this);
edit_mobile.setOnFocusChangeListener(this);
edit_email.setOnFocusChangeListener(this);
editText_password.setOnFocusChangeListener(this);
editText_cofPassword.setOnFocusChangeListener(this);
}
}
@Override
public
void onFocusChange(View v, boolean hasFocus) {
switch
(v.getId()) {
case
R.id.editText_name:
edit_name.setError(null);
break;
case
R.id.editText_mobile:
edit_mobile.setError(null);
break;
case
R.id.editText_email:
edit_email.setError(null);
case
R.id.editText_password:
edit_mobile.setError(null);
break;
case
R.id.editText_cofPassword:
edit_email.setError(null);
default:
break;
}
}
@Override
public
void onClick(View v) {
// editText validation
if
(edit_name.getText().toString().equals("")) {
edit_name.setError("Enter
Name");
edit_name.requestFocus();
}
else if (editText_password.getText().toString().equals("")) {
editText_password.setError("Enter
Email Address");
editText_password.requestFocus();
}
else if (editText_cofPassword.getText().toString().equals("")) {
editText_cofPassword.setError("Enter
Email Address");
editText_cofPassword.requestFocus();
}else
if
(!editText_cofPassword.getText().toString().equals(editText_password.getText().toString()))
{
utils.AlertDialogBox1(Registrations.this);
}
else if (edit_email.getText().toString().equals("")) {
edit_email.setError("Enter
Email Address");
edit_email.requestFocus();
}
else if (!edit_email.getText().toString()
.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+
"[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")) {
edit_email.setError("Enter
valid Email address");
edit_email.requestFocus();
}
else if (edit_mobile.getText().toString().equals("")) {
edit_mobile.setError("Enter
Mobile Number");
edit_mobile.requestFocus();
}
else if (edit_mobile.getText().toString().length() < 10
||
edit_mobile.getText().toString().length() > 10) {
edit_mobile.setError("Enter
10 Digt Number");
edit_mobile.requestFocus();
}
else
{
string_name
= edit_name.getText().toString();
string_mobile
= edit_mobile.getText().toString();
string_email
= edit_email.getText().toString();
string_password
= editText_password.getText().toString();
// put the all editText String in map array
map.put("Name",
string_name);
map.put("EmailID",
string_email);
map.put("Password",
string_password);
map.put("Mobile1",
string_mobile);
ParameterList.add(map);
new
HttpAsyncTask().execute();
}
}
private
class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected
void onPreExecute() {
super.onPreExecute();
progressdialog
= new ProgressDialog(Registrations.this);
progressdialog.setMessage("Please
Wait...");
progressdialog.show();
progressdialog.setCancelable(false);
progressdialog.setCanceledOnTouchOutside(false);
}
@Override
protected
String doInBackground(String... cname) {
try
{
// set the URL via rest api object
obj_restapi .setApiUrl("http://www.Register.com/apis/Registration.ashx");
// set the parameter array
ob j_restapi.setParameterList(ParameterList);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return obj_restapi.ResponseApi()
}
@Override
protected void onPostExecute(String result) {
JSONObject json2;
String value = "True";
try {
// json object
json2 = new JSONObject(result);
// get json response
JSONArray Profiles =
json2.getJSONArray("Profiles");
for (int i = 0; i < Profiles.length(); i++)
{
JSONObject e = Profiles.getJSONObject(i);
customerId = e.getString("ID");
}
if (value.equals(json2.getString("Message"))) { Toast.makeText(getApplication(), "Your Well Come" ,Toast.LENGTH_LONG).show(); Intent intent = new Intent(Registrations.this,LoginActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right,R.anim.stay); finish();
if (progressdialog != null) {
progressdialog.dismiss();
}
} else {
Toast.makeText(getApplication(), "Please Try Again...", Toast.LENGTH_LONG).show();
if (progressdialog != null) {
progressdialog.dismiss();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Step 5:
create Login.java class inside src folder.
package com.example.androidbeginnerpoint;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.Webnetware.Sqlitedatabase.DatabaseAdapter;
import com.Webnetware.adapter.ConnectionDetector;
import com.Webnetware.adapter.Listview_Utility;
import com.Webnetware.resApi.RestAPI;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends Activity implements
android.view.View.OnClickListener {
TextView sginUp_btn;
EditText edit_email, editText_password;
String string_email, string_password;
Button btn_signIn;
ProgressDialog progressdialog;
RestAPI obj_restapi = new RestAPI();
ArrayList<HashMap<String, String>> ParameterList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
public static final String Pssword = "PsswordKey";
public static final String Email = "emailKey";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle(" LogIn");
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.login_actvity);
setContentView(R.layout.login_actvity);
sginUp_btn = (TextView) findViewById(R.id.textView_registration);
edit_email = (EditText) findViewById(R.id.email);
editText_password = (EditText) findViewById(R.id.password);
btn_signIn = (Button) findViewById(R.id.btn_signUp);
btn_signIn.setOnClickListener(this);
sginUp_btn.setOnClickListener(this);
}
}
//
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(LoginActivity.this);
progressdialog.setMessage("Please Wait...");
progressdialog.show();
progressdialog.setCancelable(false);
progressdialog.setCanceledOnTouchOutside(false);
}
@Override
protected String doInBackground(String... cname) {
try {
// set json url
obj_restapi.setApiUrl("http://.comp/ais/Login.ashx");
//set json parameter array
//set json parameter array
obj_restapi.setParameterList(ParameterList);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return obj_restapi.ResponseApi();
}
@Override
protected void onPostExecute(String result) {
JSONObject json2;
String value = "True";
try {
json2 = new JSONObject(result);
if (value.equals(json2.getString("Message"))) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Email, string_email);
editor.putString(Pssword, string_password);
editor.commit();
Toast.makeText(getApplication(), "Your Well Come...",Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right,R.anim.stay);
if (progressdialog != null) {
progressdialog.dismiss();
}
}
else {
Toast.makeText(getApplication(), "Please Try Again...",Toast.LENGTH_LONG).show();
if (progressdialog != null) {
progressdialog.dismiss();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
overridePendingTransition(R.anim.stay, R.anim.slide_out_right);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_signUp:
string_email = edit_email.getText().toString();
string_password = editText_password.getText().toString();
map.put("EmailID", string_email);
map.put("Password", string_password);
ParameterList.add(map);
new HttpAsyncTask().execute();
break;
case R.id.textView_registration:
Intent intent = new Intent(LoginActivity.this,Registrations.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right,R.anim.stay);
break;
default:
break;
}
}
}
Step 6:
Login json
Parameter:
{"EmailID":"com@gmail.com","Password":"123"}
Result:
{"Message":"True","Profiles":[{"ID":"30"}]}
Step 7:
Registration Json
Parameter:
{"Name":"jhone","EmailID":"com@gmail.com","Password":"123”,"Mobile1":"674543223"
}
Result:
{"Message":"True","Profiles":[{"ID":"35"}]}
wow its wonerfull code...its code is solve my problem
ReplyDelete