In this
Calling Web Services in Android-Part-2
We learn How to get and set data from the form encoded Post API.
Call as simple and pass parameter user_id and name and it give appropriate response. we can handle it.
call : new getAndsetMyData().execute();
public class getAndsetMyData extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String… params) {
JSONObject jsonObjSend;
JSONArray total_beam_array;
String content = null;
try {
// Constants.BASE_URL = “your url”
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Constants.BASE_URL);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
nameValuePair.add(new BasicNameValuePair(“user_id”, user_id));
nameValuePair.add(new BasicNameValuePair(“name”, name));
// Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
content = EntityUtils.toString(entity);
Log.d(“aaa”, content);
jsonObjSend = new JSONObject(content.toString());
total_array = jsonObjSend.getJSONArray(“data”);
Constants.arr = new ArrayList<HashMap<String, String>>();
Constants.arr.clear();
Constants.length = total_array.length();
if (total_array.length() != 0) {
//
for (int i = 0; i < total_array.length(); i++) {
String user_id = total_beam_array.getJSONObject(i).getString(“user_id”);
String city= total_beam_array.getJSONObject(i).getString(“city”);
Constants.map = new HashMap<String, String>();
Constants.map.put(“user_id”, user_id);
Constants.map.put(“city”, city);
Constants.arr.add(0, Constants.map);
}
} else {
//
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
return content;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Set data to Adapter
MyAdapter adpt = new MyAdapter(getActivity(), Constants.arr);
adpt.notifyDataSetChanged();
list.setAdapter(adpt);
}
}
// Set Custom Adapter
class MyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
long temp_days;
public MyAdapter (Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
vi = inflater.inflate(R.layout.raw_file, null);
TextView val2 = (TextView) vi.findViewById(R.id.val1);
TextView val2 = (TextView) vi.findViewById(R.id.val2);
HashMap<String, String> product = new HashMap<String, String>();
product = data.get(position);
// setFont
Typeface type2 = Typeface.createFromAsset(getActivity().getAssets(), “Roboto-Regular.ttf”);
val1.setTypeface(type2);
val2.setTypeface(type2);
val1.setText(product.get(“user_id”));
val2.setText(product.get(“city”));
return vi;
}
}
==========================================================
In Second Part of form encoded post API we learn about how to upload image with other data.
Declare :
private final int GALLERY_ACTIVITY_CODE = 200;
private final int RESULT_CROP = 400;
Select Image From the Gallery or Camera
Dialog dg = new Dialog(getActivity());
dg.requestWindowFeature(Window.FEATURE_NO_TITLE);
dg.setContentView(R.layout.custom_dialog);
TextView txt_camera = (TextView) dg.findViewById(R.id.txt_camera);
TextView txt_gallary = (TextView) dg.findViewById(R.id.txt_gallry);
dg.show();
txt_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(“android.media.action.IMAGE_CAPTURE”);
File file = new File(iPath);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, 3);
dg.dismiss();
}
});
txt_gallary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent gallery_Intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
dg.dismiss();
}
});
// onActivity for result and crop image
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = null;
if (requestCode == GALLERY_ACTIVITY_CODE) {
if (resultCode == Activity.RESULT_OK) {
selectedImage = data.getData();
//perform Crop on the Image Selected from Gallery
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Log.d(“picturePath”, picturePath);
cursor.close();
Constants.bitmap_profile_Picture = BitmapFactory.decodeFile(picturePath);
performCrop(picturePath);
}
}
if (requestCode == 3) {
try {
/* the user’s device may not support cropping */
performCrop(iPath);
} catch (ActivityNotFoundException aNFE) {
// display an error message if user device doesn’t support
String errorMessage = “Sorry – your device doesn’t support the crop action!”;
Toast toast = Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
if (requestCode == RESULT_CROP) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
Constants.bitmap_profile_Picture = extras.getParcelable(“data”);
img_capture_photo.setImageBitmap(Constants.bitmap_profile_Picture);
try {
if (Constants.bitmap_profile_Picture != null) {
Log.d(“RESULT_CROP”, ” RESULT_CROP”);
StoreByteImage(Constants.bitmap_profile_Picture, 90, “my_image”);
} else {
Toast.makeText(getActivity(), “Image can not be selected”, Toast.LENGTH_LONG).show();
}
} catch (ActivityNotFoundException aNFE) {
// display an error message if user device doesn’t support
String errorMessage = “Sorry – your device doesn’t support the crop action!”;
Toast toast = Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
private void performCrop(String picUri) {
try {
//Start Crop Activity
Intent cropIntent = new Intent(“com.android.camera.action.CROP”);
// indicate image type and Uri
File f = new File(picUri);
Uri contentUri = Uri.fromFile(f);
cropIntent.setDataAndType(contentUri, “image/*”);
// set crop properties
cropIntent.putExtra(“crop”, “true”);
// indicate aspect of desired crop
cropIntent.putExtra(“aspectX”, 1);
cropIntent.putExtra(“aspectY”, 1);
// indicate output X and Y
cropIntent.putExtra(“outputX”, 280);
cropIntent.putExtra(“outputY”, 280);
// retrieve data on return
cropIntent.putExtra(“return-data”, true);
// start the activity – we handle returning in onActivityResult
startActivityForResult(cropIntent, RESULT_CROP);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = “your device doesn’t support the crop action!”;
Toast toast = Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
// Store image
public boolean StoreByteImage(Bitmap bitmap, int quality, String expName) {
FileOutputStream fileOutputStream = null;
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + “/beam_it_up”);
if (myNewFolder.mkdirs()) {
myNewFolder.mkdir();
}
try {
iPath = myNewFolder + “/” + Constants.user_id + “.png”;
fileOutputStream = new FileOutputStream(iPath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bitmap.compress(Bitmap.CompressFormat.PNG, quality, bos);
// way 1
Log.d(“u r in StoreByteImage”, “StoreByteImage call UpdateImageUploadTask”);
isInternetPresent = cd.isConnectingToInternet();
System.out.println(“intenet is : ” + isInternetPresent);
if (isInternetPresent) {
new UpLoadImage().execute();
} else {
Toast.makeText(getActivity(), “No Internet Connection”, Toast.LENGTH_LONG).show();
}
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
////// call api ////////
class UpdateImageUploadTask extends AsyncTask<Void, Void, String> {
String sResponse;
private String msg;
int register_error = 1;
JSONObject jsonObjSend;
String result, beam_registered = “”;
String message=””;
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(“UpdateImageUploadTask”, ” pre of UpdateImageUploadTask”);
}
@SuppressWarnings(“deprecation”)
@Override
protected String doInBackground(Void… unsued) {
try {
File image = new File(iPath);
FileBody fileBody = new FileBody(image);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(Constants.BASE_URL);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart(“user_id”, new StringBody(“1”));
entity.addPart(“name”, new StringBody(“xyz”));
if (fileBody != null) {
entity.addPart(“profileImage”, fileBody);
} else {
entity.addPart(“profileImage”, new StringBody(“”));
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
“UTF-8”));
sResponse = reader.readLine();
System.out.println(“new beam add responce=” + sResponse);
jsonObjSend = new JSONObject(sResponse.toString());
result = jsonObjSend.getString(“Result”).toString();
// other stuff
} catch (Exception e) {
System.out.println(“error=” + e.getMessage());
return null;
}
return “”;
}
@Override
protected void onProgressUpdate(Void… unsued) {
}
@Override
protected void onPostExecute(String sResponses) {
}
}
Library jar Required for it :
1) apache-mime4j-core-0.7.2
2) commons-cli-1.2
3) commons-io-2.4
4) fluent-hc-4.3.1
5) google-http-client-1.10.3-beta
6) google-http-client-android3-1.10.1-beta
7) google-ouath-client-appengine-1.10.0-beta
8) google-oauth-client-java6-1.13.1-beta-sources
9) httpmime-4.2.3
10)signpost-commonshttp4-1.2.1.1-beta
11)signpost-core-1.2.1.1
This is simple tutorial to learn set form encoded data and upload image to server.