Work is under progress...
public interface APIResponseReceiver {
int onDataReceived(String response);
void getResult(int resultCode);
}
import android.content.Context;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/** * Created by Yograj Shinde on 1/9/15,2:30 PM. */public class CallAPI {
private final String TAG = "Mehboob";
private Context mContext;
private String response = "";
private URL mUrl;
private HttpURLConnection httpURLConnection;
public CallAPI(Context context) {
this.mContext = context;
}
/** * This method will upload image and return response */ public String uploadImage(String url, String imagePath, String keyName ,HashMap<String, String> postDataParams) {
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024; // 1 * 1024 * 1024
File sourceFile = new File(imagePath);
FileInputStream fileInputStream;
response = "";
try {
mUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
mUrl = null;
}
if (mUrl != null) {
Log.d(TAG, "File path:- " + imagePath);
if (sourceFile.isFile()) {
try {
fileInputStream = new FileInputStream(sourceFile);
// Open a HTTP connection to the URL httpURLConnection = (HttpURLConnection) mUrl.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false); // Don't use cached copy httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(httpURLConnection.getOutputStream());
//Add HashMap Data here // dos.writeBytes(getPostDataString(postDataParams)); for (Map.Entry<String, String> entry : postDataParams.entrySet()) {
// add parameters dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=" + entry.getKey()
+ lineEnd);
dos.writeBytes(lineEnd);
// assign value dos.writeBytes(entry.getValue());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
}
// send image dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\""+keyName+"\";filename=\"" + sourceFile.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necessary after file data... dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
int serverResponseCode = httpURLConnection.getResponseCode();
Log.i(TAG, "Server Response Code:- " + serverResponseCode);
Log.i(TAG, "Server Response Message:- " + httpURLConnection.getResponseMessage());
InputStream inputStream = httpURLConnection.getInputStream();
response = convertStreamToString(inputStream);
//close the streams fileInputStream.close();
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
/** * This method will call webservice and returns response */ public String getAPIResponse(String url, HashMap<String, String> postDataParams) {
response = "";
try {
mUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
mUrl = null;
}
if (mUrl != null) {
try {
// Open a HTTP connection to the URL httpURLConnection = (HttpURLConnection) mUrl.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setReadTimeout(20000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(getPostDataString(postDataParams));
wr.flush();
wr.close();
InputStream inputStream = httpURLConnection.getInputStream();
response = convertStreamToString(inputStream);
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
private String convertStreamToString(InputStream inputstream) {
String line;
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(
inputstream));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return total.toString();
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
if (params == null || params.isEmpty()) {
result.append("");
} else {
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
}
Log.d(TAG, "Param:- " + result.toString());
return result.toString();
}
}
package com.eeshana.qisma.network;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.eeshana.qisma.R;
import com.eeshana.qisma.utilities.CommonUsage;
import com.eeshana.qisma.utilities.Config;
import java.util.HashMap;
/** * Created by Yograj Shinde on 23/7/15,12:58 PM. */public class MyAsyncTask {
private Context mContext;
private ProgressDialog pDialog;
private CallAPI callAPI;
private String mURL;
private HashMap<String, String> arr_param = new HashMap<>();
private APIResponseReceiver apiResponseReceiver;
public static String errorMSG = "";
private CommonUsage mCommonUsage;
public MyAsyncTask(Context mContext, String url, HashMap<String, String> arr_param, APIResponseReceiver responseReceiver) {
this.mContext = mContext;
this.arr_param = arr_param;
this.apiResponseReceiver = responseReceiver;
mURL = url;
mCommonUsage = CommonUsage.getCommonUsageObj(mContext);
callAPI = new CallAPI(mContext);
new MyAsync().execute(arr_param);
}
class MyAsync extends AsyncTask<HashMap<String, String>, Integer, Integer> {
@Override protected void onPreExecute() {
super.onPreExecute();
mCommonUsage.showProgressDialog(mContext.getResources().getString(R.string.please_wait));
}
@Override protected Integer doInBackground(HashMap... params) {
String response = "";
int resultCode = Config.RESULT_FAIL;
try {
response = callAPI.getAPIResponse(mURL, params[0]);
} catch (Exception e) {
e.printStackTrace();
response = "";
}
Log.d(Config.TAG, "API Response:- " + response);
resultCode = apiResponseReceiver.onDataReceived(response);
return resultCode;
}
@Override protected void onPostExecute(Integer resultCode) {
super.onPostExecute(resultCode);
mCommonUsage.dismissmPdialog();
switch (resultCode) {
case Config.RESULT_SERVER_ERROR:
mCommonUsage.showToast(mContext.getResources().getString(R.string.response_null_error));
break;
case Config.RESULT_PARSE_ERROR:
mCommonUsage.showToast(mContext.getResources().getString(R.string.response_parse_error));
break;
case Config.RESULT_FAIL:
//mCommonUsage.showToast(errorMSG); Log.i("API Status","API Other that 1 msg"+errorMSG);
apiResponseReceiver.getResult(Config.RESULT_FAIL);
break;
case Config.RESULT_SUCCESS:
apiResponseReceiver.getResult(Config.RESULT_SUCCESS);
break;
}
}
}
}
@Overridepublic int onDataReceived(String response) {
if (response == null || response.equalsIgnoreCase("")) {
return Config.RESULT_SERVER_ERROR;
} else {
try {
JSONObject jsonObjResult = new JSONObject(response.trim());
int status = jsonObjResult.getInt("status");
if (status == 1) {
if (jsonObjResult.has("data"))
{
}
return Config.RESULT_SUCCESS;
} else {
Log.i("Got Status","0 here");
String error;
if (jsonObjResult.has("statusInfo")) {
error = jsonObjResult.getString("statusInfo");
} else {
error = getResources().getString(R.string.response_fail_error);
}
MyAsyncTask.errorMSG = error;
return Config.RESULT_FAIL;
}
} catch (Exception e) {
e.printStackTrace();
return Config.RESULT_PARSE_ERROR;
}
}
}
@Overridepublic void getResult(int resultCode) {
if (resultCode == Config.RESULT_SUCCESS) {
}
}
public interface Config {
String GCM_SENDER_ID = "";
String TAG = "Mehboob App";
// Result codes int RESULT_FAIL = 0;
int RESULT_SUCCESS = 1;
int RESULT_SERVER_ERROR = 2;
int RESULT_PARSE_ERROR = 3;
}
HashMap<String, String> param = new HashMap<String, String>();
param.put(ParamKeys.FB_ID, object.getString("id").toString());
if (comObj.isDeviceHasNetwork()) {
isFbLodgedIn = true;
new MyAsyncTask(LoginActivity.this, WebServiceURL.VERIFY_FB_ID, param, LoginActivity.this);
} else {
comObj.showToast(getString(R.string.no_internet_connection));
}
public class CommonUsage {
private static Context _mContext;
private static CommonUsage _commonUsageObj;
private ProgressDialog mProgressDialog;
public static SharedPreferences common_user_data;
//Default constructor public CommonUsage(){}
public static CommonUsage getCommonUsageObj(Context con){
_mContext = con;
if(_commonUsageObj == null)
_commonUsageObj = new CommonUsage();
return _commonUsageObj;
}
/**
* This method will print toast at the center of the screen * **/public void showToast(String msg)
{
Toast tstObj = Toast.makeText(_mContext, msg, Toast.LENGTH_SHORT);
tstObj.setGravity(Gravity.CENTER, tstObj.getXOffset()/ 2, tstObj.getYOffset()/ 2);
tstObj.show();
}
/** * Checking for all possible Internet providers * Returns true if connected else fails * * **/
public boolean isDeviceHasNetwork()
{
ConnectivityManager connectivity = (ConnectivityManager)_mContext.
getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivity != null){
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if(info != null)
for (int i = 0; i < info.length; i++) {
if(info[i].getState() == NetworkInfo.State.CONNECTED){
return true;
}
}
}
return false;
}
/*** This method will show the processing dialog with given msg** **/
public void showProgressDialog(String msg)
{
mProgressDialog = new ProgressDialog(_mContext);
mProgressDialog.setMessage(msg);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.setCanceledOnTouchOutside(false);
if(!((Activity)_mContext).isFinishing()){
mProgressDialog.show();
}
}
/** * This method will close the processing dialog which is running now. * * **/public void dismissmPdialog()
{
try{
if(mProgressDialog!=null)
{
mProgressDialog.dismiss();
Log.i("GeneralNeedLibM", "progressDialog dismissed successfully");
}else{
Log.i("GeneralNeedLibM", "progressDialog dismiss error You might be trying to dismiss the progress dialog" +
"which is created with different context Or the progressDialog which not at all created");
}
}catch(Exception e)
{
e.printStackTrace();
Log.i("GeneralNeedLibM", ""+e);
Log.i("GeneralNeedLibM", "progressDialog dismiss exception You might be trying to dismiss the progress dialog" +
"which is created with different context");
}
}
}
/*Just Validate empty EditText*/public static boolean Is_Empty_EditText(EditText et){
String text = et.getText().toString().trim();
if(text.isEmpty() || text.length()== 0){
et.requestFocus();
et.setError("Required!");
}else{
et.setError(null);
return true;
}
return false;
}