Global AsynTask class to do background process and get the response within in activity.
PostAsynTas.java
<pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnbDC7MPHHW8IIEJH1g2jNx4ZMNB1xp3_cx-AyaviwgTjGErFi-96LEGgoAwnnAj8v-cDufG1SyDvnY0ht7EzlIHvq_U1erBJo3n5OA5rx3fvOOJqAw_kc4yh1RIMow1SH-fLlaEcN9tvP/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> public abstract class PostAsynTask extends AsyncTask<Void, Void, String> {
private List<NameValuePair> paramValues;
Context ctx;
HttpManager http;
String _StrResult = "", _StrApiKey = "", _StrUrl = "", _StrUserId,
_StrToken, _StrImagePath;
boolean isWithHeader, isPostImage = false;
// PostWithHeader(String url,List<NameValuePair> nameValuePairs,String
// PublicKey,String UserId,String token, boolean flag) {
//Method to do background process:
public PostAsynTask(Context context, String _StrUrl,
List<NameValuePair> params, String _StrApiKey, String _StrUserId,
String _StrToken, boolean isWithHeader) {
this.paramValues = params;
ctx = context;
http = new HttpManager();
this._StrApiKey = _StrApiKey;
this._StrUrl = _StrUrl;
this._StrUserId = _StrUserId;
this._StrToken = _StrToken;
this.isWithHeader = isWithHeader;
}
//Method to do background process with image post:
public PostAsynTask(Context context, String _StrUrl,
List<NameValuePair> params, String _StrApiKey, String _StrUserId,
String _StrToken, boolean isWithHeader, boolean isPostImage, String _StrImagePath) {
this.paramValues = params;
ctx = context;
http = new HttpManager();
this._StrApiKey = _StrApiKey;
this._StrUrl = _StrUrl;
this._StrUserId = _StrUserId;
this._StrToken = _StrToken;
this.isWithHeader = isWithHeader;
this.isPostImage = isPostImage;
this._StrImagePath = _StrImagePath;
}
//Do-in background process:
@Override
protected String doInBackground(Void... params) {
try {
if (isPostImage) {
_StrResult = http.postImageWithHeader(_StrUrl, paramValues, _StrApiKey, _StrUserId, _StrToken, _StrImagePath);
} else {
_StrResult = http.PostWithHeader(_StrUrl, paramValues, _StrApiKey,
_StrUserId, _StrToken, isWithHeader);
}
} catch (Exception e) {
e.printStackTrace();
}
return _StrResult;
}
}
</code></pre>
GetAsynTask.java
public class GetAsynTask extends AsyncTask<Void, Void, String> {
Context context;
HttpManager http;
String _StrResult = "", _StrApiKey = "", _StrUrl = "", _StrUserId = "", _StrToken = "";
// (String url, String iUserID,String PublicKey, String accesstoken) {
public GetAsynTask(Context context, String _StrUrl, String _StrUserId, String _StrApiKey, String _StrToken) {
http = new HttpManager();
this.context = context;
this._StrApiKey = _StrApiKey;
this._StrUrl = _StrUrl;
this._StrUserId = _StrUserId;
this._StrToken = _StrToken;
}
@Override
protected String doInBackground(Void... params) {
try {
_StrResult = http.GetWithHeader(_StrUrl, _StrUserId, _StrApiKey, _StrToken);
} catch (Exception e) {
e.printStackTrace();
}
return _StrResult;
}
}
HttpManager.java
public class HttpManager {
private static final String TAG = null;
HttpClient httpClient = new DefaultHttpClient();
private String X_API_KEY="X-API-KEY",IUSER_ID="iUserID",ACCESS_TOKEN="accesstoken";
//Get the defaulKey Method:
public String getDefaultKey(String urlString,String key) throws IOException,ProtocolException {
HttpClient httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
HttpPost httppost = new HttpPost(urlString);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
httppost.addHeader(X_API_KEY, key);
// reqEntity.addPart("vEmail", new StringBody(email));
// reqEntity.addPart("vPassword", new StringBody(password));
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
String str_response = EntityUtils.toString(response.getEntity());
Log.e("########","response " + str_response);
return str_response;
}
//Logout Method:
public String LogOut(String urlString, String token, String UserId,String key) throws IOException, ProtocolException {
HttpClient httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
HttpPost httppost = new HttpPost(urlString);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
httppost.addHeader(X_API_KEY, key);
httppost.addHeader(IUSER_ID, UserId);
httppost.addHeader(ACCESS_TOKEN, token);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
String str_response = EntityUtils.toString(response.getEntity());
Log.e("########", "response " + str_response);
return str_response;
}
//Post method with Header:
public String PostWithHeader(String url,List<NameValuePair> nameValuePairs,String PublicKey,
String UserId,String token, boolean flag) {
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 10000);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
if(flag){
Log.e("#####", "others services");
httpPost.addHeader(X_API_KEY, PublicKey);
httpPost.addHeader(IUSER_ID, UserId);
httpPost.addHeader(ACCESS_TOKEN, token);
}else{
Log.e("#####", "sign up");
httpPost.addHeader(X_API_KEY, PublicKey);
}
try {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// MultipartEntity entity = new MultipartEntity();
for (int index = 0; index < nameValuePairs.size(); index++) {
// Normal string data
Log.i(TAG, "Adding Normal strings");
entity.addPart(
nameValuePairs.get(index).getName(),
new StringBody(nameValuePairs.get(index).getValue()));
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
String _Str = EntityUtils.toString(response.getEntity());
Log.e("########","response " + _Str);
return _Str;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Get method with Header:
public String GetWithHeader(String url, String iUserID,String PublicKey, String accesstoken) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader(IUSER_ID, iUserID);
httpGet.addHeader(X_API_KEY, PublicKey);
httpGet.addHeader(ACCESS_TOKEN, accesstoken);
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
String _Str = EntityUtils.toString(response.getEntity());
Log.e("########","response " + _Str);
return _Str;
} catch (Exception e) {
Log.i(TAG, "Exception :" + e.toString());
return null;
}
}
//PostImage with Header:
public String postImageWithHeader(String url,List<NameValuePair> nameValuePairs,String PublicKey, String iUserID,
String token, String Picture_Path) {
Bitmap bm;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(IUSER_ID, iUserID);
httpPost.addHeader(X_API_KEY, PublicKey);
httpPost.addHeader(ACCESS_TOKEN, token);
try {
bm = BitmapFactory.decodeFile(Picture_Path);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// MultipartEntity entity = new MultipartEntity();
for (int index = 0; index < nameValuePairs.size(); index++) {
if (nameValuePairs.get(index).getName().equalsIgnoreCase("vProfilePic")) {
// If the key equals to "image", we use FileBody to transfer
// the data
// if (!isfb) {
Log.i(TAG, "Adding File strings");
File file = new File(Picture_Path);
if (file.exists()) {
Log.i(TAG, "file Exists");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data,"image/jpg", Picture_Path);
Log.e("#####", "byte array="+bab);
entity.addPart("vProfilePic", bab);
} else {
Log.i(TAG, "file not Exists");
}
}
else {
// Normal string data
Log.i(TAG, "Adding Normal strings");
entity.addPart(nameValuePairs.get(index).getName(),
new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
String _Str = EntityUtils.toString(response.getEntity());
Log.e("########","response " + _Str);
return _Str;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public byte[] readFile (String file) throws IOException {
return readFile(new File(file));
}
public byte[] readFile (File file) throws IOException {
// Open file
RandomAccessFile f = new RandomAccessFile(file, "r");
try {
// Get and check length
long longlength = f.length();
int length = (int) longlength;
if (length != longlength) throw new IOException("File size >= 2 GB");
// Read file and return data
byte[] data = new byte[length];
f.readFully(data);
return data;
}
finally {
f.close();
}
}
}
Way to call GetAsynTask. pass appropriate data and the result in onPostExecute method.
private void FetchGroupTask(){
GetAsynTask Task= new GetAsynTask(getActivity(), URL, _StrUserID, _StrApiKey, _StrAccessToken){
ProgressDialog progress;
@Override
protected void onPreExecute() {
progress= ProgressDialog.show(getActivity(), null, "Please wait...", true);
progress.setCancelable(true);
}
@Override
protected void onPostExecute(String result) {
}
};
Task.execute();
}
Way to call PostAsynTask. pass appropriate data and the result in onPostExecute method.
private void ReceivedNotificationTask(List<NameValuePair> params,final String msg) {
PostAsynTask Task = new PostAsynTask(getActivity(), URL_RECEIVED,
params, _StrApiKey, _StrUserID, _StrAccessToken, true) {
private ProgressDialog _progressDialog;
protected void onPreExecute() {
_progressDialog = ProgressDialog.show(getActivity(), null,
msg, true);
_progressDialog.setCancelable(true);
}
@Override
protected void onPostExecute(String result) {
}
};
Task.execute();
}
PostAsynTas.java
<pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnbDC7MPHHW8IIEJH1g2jNx4ZMNB1xp3_cx-AyaviwgTjGErFi-96LEGgoAwnnAj8v-cDufG1SyDvnY0ht7EzlIHvq_U1erBJo3n5OA5rx3fvOOJqAw_kc4yh1RIMow1SH-fLlaEcN9tvP/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> public abstract class PostAsynTask extends AsyncTask<Void, Void, String> {
private List<NameValuePair> paramValues;
Context ctx;
HttpManager http;
String _StrResult = "", _StrApiKey = "", _StrUrl = "", _StrUserId,
_StrToken, _StrImagePath;
boolean isWithHeader, isPostImage = false;
// PostWithHeader(String url,List<NameValuePair> nameValuePairs,String
// PublicKey,String UserId,String token, boolean flag) {
//Method to do background process:
public PostAsynTask(Context context, String _StrUrl,
List<NameValuePair> params, String _StrApiKey, String _StrUserId,
String _StrToken, boolean isWithHeader) {
this.paramValues = params;
ctx = context;
http = new HttpManager();
this._StrApiKey = _StrApiKey;
this._StrUrl = _StrUrl;
this._StrUserId = _StrUserId;
this._StrToken = _StrToken;
this.isWithHeader = isWithHeader;
}
//Method to do background process with image post:
public PostAsynTask(Context context, String _StrUrl,
List<NameValuePair> params, String _StrApiKey, String _StrUserId,
String _StrToken, boolean isWithHeader, boolean isPostImage, String _StrImagePath) {
this.paramValues = params;
ctx = context;
http = new HttpManager();
this._StrApiKey = _StrApiKey;
this._StrUrl = _StrUrl;
this._StrUserId = _StrUserId;
this._StrToken = _StrToken;
this.isWithHeader = isWithHeader;
this.isPostImage = isPostImage;
this._StrImagePath = _StrImagePath;
}
//Do-in background process:
@Override
protected String doInBackground(Void... params) {
try {
if (isPostImage) {
_StrResult = http.postImageWithHeader(_StrUrl, paramValues, _StrApiKey, _StrUserId, _StrToken, _StrImagePath);
} else {
_StrResult = http.PostWithHeader(_StrUrl, paramValues, _StrApiKey,
_StrUserId, _StrToken, isWithHeader);
}
} catch (Exception e) {
e.printStackTrace();
}
return _StrResult;
}
}
</code></pre>
GetAsynTask.java
public class GetAsynTask extends AsyncTask<Void, Void, String> {
Context context;
HttpManager http;
String _StrResult = "", _StrApiKey = "", _StrUrl = "", _StrUserId = "", _StrToken = "";
// (String url, String iUserID,String PublicKey, String accesstoken) {
public GetAsynTask(Context context, String _StrUrl, String _StrUserId, String _StrApiKey, String _StrToken) {
http = new HttpManager();
this.context = context;
this._StrApiKey = _StrApiKey;
this._StrUrl = _StrUrl;
this._StrUserId = _StrUserId;
this._StrToken = _StrToken;
}
@Override
protected String doInBackground(Void... params) {
try {
_StrResult = http.GetWithHeader(_StrUrl, _StrUserId, _StrApiKey, _StrToken);
} catch (Exception e) {
e.printStackTrace();
}
return _StrResult;
}
}
HttpManager.java
public class HttpManager {
private static final String TAG = null;
HttpClient httpClient = new DefaultHttpClient();
private String X_API_KEY="X-API-KEY",IUSER_ID="iUserID",ACCESS_TOKEN="accesstoken";
//Get the defaulKey Method:
public String getDefaultKey(String urlString,String key) throws IOException,ProtocolException {
HttpClient httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
HttpPost httppost = new HttpPost(urlString);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
httppost.addHeader(X_API_KEY, key);
// reqEntity.addPart("vEmail", new StringBody(email));
// reqEntity.addPart("vPassword", new StringBody(password));
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
String str_response = EntityUtils.toString(response.getEntity());
Log.e("########","response " + str_response);
return str_response;
}
//Logout Method:
public String LogOut(String urlString, String token, String UserId,String key) throws IOException, ProtocolException {
HttpClient httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
HttpPost httppost = new HttpPost(urlString);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
httppost.addHeader(X_API_KEY, key);
httppost.addHeader(IUSER_ID, UserId);
httppost.addHeader(ACCESS_TOKEN, token);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
String str_response = EntityUtils.toString(response.getEntity());
Log.e("########", "response " + str_response);
return str_response;
}
//Post method with Header:
public String PostWithHeader(String url,List<NameValuePair> nameValuePairs,String PublicKey,
String UserId,String token, boolean flag) {
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 10000);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
if(flag){
Log.e("#####", "others services");
httpPost.addHeader(X_API_KEY, PublicKey);
httpPost.addHeader(IUSER_ID, UserId);
httpPost.addHeader(ACCESS_TOKEN, token);
}else{
Log.e("#####", "sign up");
httpPost.addHeader(X_API_KEY, PublicKey);
}
try {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// MultipartEntity entity = new MultipartEntity();
for (int index = 0; index < nameValuePairs.size(); index++) {
// Normal string data
Log.i(TAG, "Adding Normal strings");
entity.addPart(
nameValuePairs.get(index).getName(),
new StringBody(nameValuePairs.get(index).getValue()));
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
String _Str = EntityUtils.toString(response.getEntity());
Log.e("########","response " + _Str);
return _Str;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Get method with Header:
public String GetWithHeader(String url, String iUserID,String PublicKey, String accesstoken) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader(IUSER_ID, iUserID);
httpGet.addHeader(X_API_KEY, PublicKey);
httpGet.addHeader(ACCESS_TOKEN, accesstoken);
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
String _Str = EntityUtils.toString(response.getEntity());
Log.e("########","response " + _Str);
return _Str;
} catch (Exception e) {
Log.i(TAG, "Exception :" + e.toString());
return null;
}
}
//PostImage with Header:
public String postImageWithHeader(String url,List<NameValuePair> nameValuePairs,String PublicKey, String iUserID,
String token, String Picture_Path) {
Bitmap bm;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(IUSER_ID, iUserID);
httpPost.addHeader(X_API_KEY, PublicKey);
httpPost.addHeader(ACCESS_TOKEN, token);
try {
bm = BitmapFactory.decodeFile(Picture_Path);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// MultipartEntity entity = new MultipartEntity();
for (int index = 0; index < nameValuePairs.size(); index++) {
if (nameValuePairs.get(index).getName().equalsIgnoreCase("vProfilePic")) {
// If the key equals to "image", we use FileBody to transfer
// the data
// if (!isfb) {
Log.i(TAG, "Adding File strings");
File file = new File(Picture_Path);
if (file.exists()) {
Log.i(TAG, "file Exists");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data,"image/jpg", Picture_Path);
Log.e("#####", "byte array="+bab);
entity.addPart("vProfilePic", bab);
} else {
Log.i(TAG, "file not Exists");
}
}
else {
// Normal string data
Log.i(TAG, "Adding Normal strings");
entity.addPart(nameValuePairs.get(index).getName(),
new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
String _Str = EntityUtils.toString(response.getEntity());
Log.e("########","response " + _Str);
return _Str;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public byte[] readFile (String file) throws IOException {
return readFile(new File(file));
}
public byte[] readFile (File file) throws IOException {
// Open file
RandomAccessFile f = new RandomAccessFile(file, "r");
try {
// Get and check length
long longlength = f.length();
int length = (int) longlength;
if (length != longlength) throw new IOException("File size >= 2 GB");
// Read file and return data
byte[] data = new byte[length];
f.readFully(data);
return data;
}
finally {
f.close();
}
}
}
Way to call GetAsynTask. pass appropriate data and the result in onPostExecute method.
private void FetchGroupTask(){
GetAsynTask Task= new GetAsynTask(getActivity(), URL, _StrUserID, _StrApiKey, _StrAccessToken){
ProgressDialog progress;
@Override
protected void onPreExecute() {
progress= ProgressDialog.show(getActivity(), null, "Please wait...", true);
progress.setCancelable(true);
}
@Override
protected void onPostExecute(String result) {
}
};
Task.execute();
}
Way to call PostAsynTask. pass appropriate data and the result in onPostExecute method.
private void ReceivedNotificationTask(List<NameValuePair> params,final String msg) {
PostAsynTask Task = new PostAsynTask(getActivity(), URL_RECEIVED,
params, _StrApiKey, _StrUserID, _StrAccessToken, true) {
private ProgressDialog _progressDialog;
protected void onPreExecute() {
_progressDialog = ProgressDialog.show(getActivity(), null,
msg, true);
_progressDialog.setCancelable(true);
}
@Override
protected void onPostExecute(String result) {
}
};
Task.execute();
}
Comments
Post a Comment