AsyncTask with Gson Libarary For Json Parsing
Android
AsyncTask with Gson Libarary For Json Parsing
There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.
Gson Goals
Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
Allow pre-existing unmodifiable objects to be converted to and from JSON
Extensive support of Java Generics
Allow custom representations for objects
Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
Here I create a empty class name as DataModel and implement it as a Serializable
import
java.io.Serializable;
public
class
DataModel
implements
Serializable{
}
This
is a empty class so you can add any object to this class and get the
value of that objects
Now
we write one interface which will give the return datamodel
public
interface
NotifyTasKDone {
public
void
onTaskDone(DataModel in);
}
So
start writting an AsyncTask. Create a class name as TaskHandler or
any other name you may want.
Here
we are parsing the URL via the post methods. We get the response as a
encrepted format or normal
@SuppressWarnings("deprecation")
public
class
TaskAsycnHandler extends
AsyncTask<String, Void, DataModel> {
public
NotifyTasKDone taskDone;
private
Activity activity;
private
ProgressDialog progressDialog;
private
int
msgId;
private
int
val;
private
Map<String, String> keyValue;
@SuppressWarnings("deprecation")
private
HttpClient
httpclient;
@SuppressWarnings("deprecation")
private
HttpPost
httppost;
@SuppressWarnings("deprecation")
private
List<NameValuePair>
nameValuePairs;
AnimationDrawable
rocketAnimation;
JsonElement
jsonResponse
= null;
private
String action;
private
static
final
String TAG
= "MyURLs";
public
TaskAsycnHandler(NotifyTasKDone taskDone, Activity activity,
int
msgId, int
val, Map<String, String> keyValue) {
this.taskDone
= taskDone;
this.activity
= activity;
this.msgId
= msgId;
this.val
= val;
this.keyValue
= keyValue;
this.action
= keyValue.get("action");
}
@SuppressLint("NewApi")
@Override
protected
void
onCancelled(DataModel result) {
//
TODO
Auto-generated method stub
super.onCancelled(result);
}
@Override
protected
synchronized
void
onPostExecute(DataModel result) {
taskDone.onTaskDone(result);
Log.v("webservice",
final_result);
if
(val
== 2){
Constants.flagRoomList_Search
= false;
System.err.println("*-*-*545644646
*-*-*");
} else
{
progressDialog.dismiss();
}
}
@SuppressLint("NewApi")
@Override
protected
void
onPreExecute() {
if
(val
== 0) {
progressDialog
= ProgressDialog.show(activity,
"",
"");
progressDialog.setContentView(R.layout.progress_circular);
WindowManager.LayoutParams
params = progressDialog.getWindow().getAttributes();
params.y
=200;
progressDialog.getWindow().setAttributes(params);
}
else
if
(val
== 1) {
progressDialog
= ProgressDialog.show(activity,
activity
.getResources().getString(R.string.str_Wait),
activity
.getResources().getString(R.string.str_Progressing));
progressDialog.setContentView(R.layout.progress);
progressDialog.setCancelable(false);
ImageView
progress = (ImageView) progressDialog
.findViewById(R.id.progressbar);
rocketAnimation
= (AnimationDrawable) progress.getBackground();
rocketAnimation.start();
TextView
hold_msg = (TextView) progressDialog
.findViewById(R.id.hold_msg);
hold_msg.setText(msgId);
}else
if
(val
== 2)
Constants.progress_flag
= true;
else
Constants.progress_flag
= false;
}
String
result
= "",final_result="";
@SuppressWarnings("deprecation")
protected
synchronized
DataModel doInBackground(String... params) {
//
TODO
Auto-generated method stub
final
HttpParams
httpParams = new
BasicHttpParams();
registry.register(new
Scheme("http",
new
PlainSocketFactory(), 80));
registry.register(new
Scheme("https",
new
TlsSniSocketFactory(), 443));
httpclient
= new
DefaultHttpClient(new
ThreadSafeClientConnManager(
httpparams,
registry), httpparams);
httppost
= new
HttpPost(Constants.URL);
nameValuePairs
= new
ArrayList<NameValuePair>(keyValue.size());
for
(Entry<String, String> entry : keyValue.entrySet())
{
String
keys = entry.getKey();
String
values = entry.getValue();
nameValuePairs.add(new
BasicNameValuePair(keys, values));
}
try
{
httppost.setEntity(new
UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
{
String
urldata = nameValuePairs.toString().replace(",
",
"&");
System.out.println("Urls
===> "
+ Constants.URL
+ ""
+
urldata.substring(1, urldata.length() - 1)
+
"&debug=1");
Log.v("webservice",
Constants.URL
+ ""
+
urldata.substring(1, urldata.length() - 1)
+
"&debug=1");
}
InputStream
instream;
if
(entity != null)
{
if
(Constants.isGZIPPED)
{
instream
= entity.getContent();
result
= Constants.uncompressInputStream(instream);
}
else
{
instream
= entity.getContent();
result
+= Constants.convertStreamToString(instream);
}
System.out.println("**
result **"
+ result);
}
}
catch
(Exception e) {
Constants.TimeOutError
= "No
Responce";
System.err.println("noReponce
time out error :==> "+e.getMessage());
e.printStackTrace();
}
final_result
+= result;
String
st = result;
DataModel
model = null;
InputStream
is = new
ByteArrayInputStream(st.getBytes());
Class<DataModel>
cls = null;
String
cls_name = params[0].toString();
System.out.println("cls_name"
+ cls_name);
JsonReader
reader = new
JsonReader(new
InputStreamReader(is));
JsonParser
parser = new
JsonParser();
jsonResponse
= parser.parse(reader);
//
parse the response
//
YourResponseClass response;
try
{
cls
= (Class<DataModel>)
Class.forName(cls_name);
}
catch
(ClassNotFoundException e) {
//
TODO
Auto-generated catch block
e.printStackTrace();
}
Gson
gson = new
Gson();
//
Gson
gson
= new GsonBuilder().serializeNulls().create();
try
{
model
= gson.fromJson(jsonResponse,
cls);
}
catch
(RuntimeException r) {
Constants.TimeOutError
= "Data
is not in Json Format";
System.err.println("Data
is not in Json Format");
}
return
model;
}
}
Make
a class called as Constants.java which will hold the constant
variables and function this variable and function can call
directly. Here Constants.isGZIPPED is a boolean variable
If the json data from web is gzip ie compress then this variable
become true and I call a function which will unzip the json response
and fill our data model with
respected data
uncompressInputStream
is
a function which will un compress the data and the
convertStreamToString
function is for normal json response
Now see the below Constants.java file class
public
class
Constants
{
public
static
boolean
isGZIPPED
= true;
public
static
boolean
progress_flag
= false;
public
static
String TimeOutError;
public
static
String uncompressInputStream(InputStream inputStream)
throws
IOException
{
StringBuilder
value = new
StringBuilder();
GZIPInputStream
gzipIn = null;
InputStreamReader
inputReader = null;
BufferedReader
reader = null;
try
{
gzipIn
= new
GZIPInputStream(inputStream);
inputReader
= new
InputStreamReader(gzipIn, "UTF-8");
reader
= new
BufferedReader(inputReader);
String
line = "";
while
((line = reader.readLine()) != null)
{
value.append(line
+ "\n");
}
}
finally
{
try
{
if
(gzipIn != null)
{
gzipIn.close();
}
if
(inputReader != null)
{
inputReader.close();
}
if
(reader != null)
{
reader.close();
}
}
catch
(IOException
io) {
io.printStackTrace();
}
}
return
value.toString();
}
public
static
String convertStreamToString(InputStream is) {
BufferedReader
reader = new
BufferedReader(new
InputStreamReader(is));
StringBuilder
sb = new
StringBuilder();
String
line = null;
try
{
while
((line = reader.readLine()) != null)
{
sb.append(line
+ "\n");
}
}
catch
(IOException
e) {
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch
(IOException
e) {
e.printStackTrace();
}
}
return
sb.toString();
}
}
Lets
start to create a sample app, create a android project name as
xyz....
Here I
create a LoginActivity.java, It have edittext box for user name and
password & login button
See the
below code for this one
public
class
LoginActivity extends
Activity
implements
OnClickListener,
NotifyTasKDone
{
private
Context currObj;
private
EditText user_name,
password;
private
Login_model login_model;
private
Map<String,
String> keypair;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
initialized();
}
private
void
initialized() {
user_name
= (EditText) findViewById(R.id.user_name);
password
= (EditText) findViewById(R.id.password);
btn_sign
= (Button) findViewById(R.id.btn_sign);
btn_sign.setOnClickListener(this);
}
@Override
public
void
onClick(View v) {
//
TODO
Auto-generated method stub
switch
(v.getId()) {
case
R.id.btn_sign:
if
(user_name.getText().length()
<= 0) {
//Show
Error Message
}
else
if
(Constants.isValidEmailAddress(user_name.getText()
.toString())
== false)
{
//Show
Error Message
}
else
if
(password.getText().length()
<= 0) {
//Show
Error Message
}
else
{
LoginWebService(user_name.getText().toString(),
password
.getText().toString());
}
break;
default:
break;
}
}
@SuppressWarnings("unchecked")
private
void
LoginWebService(String username, String password) {
//
TODO
Auto-generated method stub
Constants.isGZIPPED
= true;
try
{
this.username
= username;
if
(NetworkUtil.isNetworkAvailable(currObj))
{
keypair
= new
HashMap<String, String>();
keypair.put("action",
"customer_login");
keypair.put("device_type",
"android");
keypair.put("customer_email",
username);
keypair.put("customer_password",
password);
final
String model_name = "com.SampleApp.models.Login_model";
final
TaskAsycnHandler tt = new
TaskAsycnHandler(this,
getActivity(),
R.string.loginmsg,
1, keypair);
tt.execute(model_name);
}
else
{
NetworkUtil.noNetworkAlert(currObj,
this.getResources()
.getString(R.string.noInternet));
}
}
catch
(Exception e) {
}
}
@Override
public
void
onTaskDone(DataModel in) {
login_model
= (Login_model) in;
if
(login_model
!= null)
{
String
login_msg = login_model.getlogin_msg();
if
(login_msg.toLowerCase().equals("true"))
{
System.out.println("Login
Success");
}else
{
System.out.println("Login
Fail");
}
}
}
Now
here we write a model class,its a class just with a
getter methods
Gson
libary having some structure for writting getter
method
Following class show
the Login_model
import
java.io.Serializable;
import
com.google.gson.annotations.SerializedName;
public
class
Login_model extends
DataModel {
private
static
final
long
serialVersionUID
= 1L;
@SerializedName("login")
public
String login_msg;
public
String getlogin_msg() {
return
login_msg;
}
}
Here
@SerializedName("login")
is a json key which we get
from the web services
Thanks
Comments
Post a Comment