Not able to upload image from android camera to .net server - android

I am using .net Web services in my app. I have to upload image and put it on server but when I am getting socketTimeOutException each time.
// code to upload image
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
imageFlag = true;
//get the current timeStamp and strore that in the time Variable
Long tsLong = System.currentTimeMillis() / 1000;
timestamp = tsLong.toString();
Bitmap image1 = ((BitmapDrawable) ivImage.getDrawable()).getBitmap();
new PaymentSlips(image1).execute();
}
// code for asynk task
private class PaymentSlips extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
String ResposeFromPaymentRequestApi;
private Bitmap userfile;
public PaymentSlips(Bitmap image) {
this.userfile = image;
}
#Override
protected Void doInBackground(String... params) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//compress the image to jpg format
if (!(userfile == null))
userfile.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
/*
* encode image to base64 so that it can be picked by saveImage.php file
* */
String encodeImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
//generate hashMap to store encodedImage and the name
HashMap<String, String> detail = new HashMap<>();
detail.put("image", encodeImage);
try {
String dataToSend = hashMapToUrl(detail);
WebService wsc = new WebService();
ResposeFromPaymentRequestApi = wsc.PaymentSlips("1", dataToSend, "reqSlip", serviceToken, "PaymentSlips");
return null;
/*String response = Request.post(new Config().updateProfilePic, dataToSend);
//return the response
return response;*/
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Void result) {
//Set response
try {
Log.e("TAG", "getimageupload" + ResposeFromPaymentRequestApi);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
//Make ProgressBar invisible
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait.......");
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
private String hashMapToUrl(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
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"));
}
return result.toString();
}
// code for .net web service
public static String PaymentSlips(String installmentid,String image,String slipStatus,String serviceToken, String webMethName) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, webMethName);
PropertyInfo loginUserPI = new PropertyInfo();
// Adding firstname
loginUserPI.setName("installmentid");
loginUserPI.setValue(installmentid);
loginUserPI.setType(String.class);
request.addProperty(loginUserPI);
request.addProperty("image",""+image);
request.addProperty("slipStatus",""+slipStatus);
request.addProperty("serviceToken", "" + serviceToken);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION + webMethName, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
resTxt = response.toString();
} catch (Exception e) {
e.printStackTrace();
resTxt = "Error occured";
}
return resTxt;
}

Related

How to avoid force close application in Android

I've tried searching the internet for solution unfortunately I could not find the answer. I tried using try catch to catch error exception but still it won't work.
Here's my code. I have private class LoginTask
private class LoginTask extends AsyncTask<String,String,JSONObject> {
private String[] privateCredentials;
private String privateRequest;
private String errorMessage = "";
//initialize all here
//constructor
LoginTask(String[] credentials,String request) {
this.privateRequest = request;
this.privateCredentials = credentials;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if(this.privateRequest=="login"){
try {
String response = result.getString("status");
if(response.equals("ok")){
onLoginSuccess(result.getString("username"),result.getString("full_name"),result.getInt("user_id"));
}else{
onLoginFails();
}
} catch (JSONException e) {
if(errorMessage!=""){
Toast ts;
ts = Toast.makeText(LoginActivity.this,errorMessage,Toast.LENGTH_LONG);
ts.show();
}
//e.printStackTrace();
}
}
}
#Override
protected JSONObject doInBackground(String... params) {
String result = "";
JSONObject resultObj = null;
HttpURLConnection con = null;
BufferedReader br = null;
JSONObject cred = new JSONObject();
if(this.privateRequest=="login"){
try {
cred.put("username", this.privateCredentials[0]);
cred.put("password", this.privateCredentials[1]);
URL url = new URL(params[0]);
con = (HttpURLConnection) url.openConnection();
;
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
OutputStream outputStream = con.getOutputStream();
outputStream.write(cred.toString().getBytes());
InputStream stream = con.getInputStream();
br = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
buffer.append(line);
}
//get the result
JSONObject jsonObj = new JSONObject(buffer.toString());
resultObj = jsonObj;
// return buffer.toString();
}catch (JSONException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
} catch (ProtocolException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
//e.printStackTrace();
} catch (IOException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
//e.printStackTrace();
} finally {
if(con!=null) {
con.disconnect();
}
}
return resultObj;
}
return null;
}
}
And here's my event listener code in the login activity.
//when clicking the login button
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do now the login process
userText.setVisibility(view.INVISIBLE);
passwordText.setVisibility(view.INVISIBLE);
tvRegister.setVisibility(view.INVISIBLE);
umlogo.setVisibility(view.INVISIBLE);
//set textviews to invisible
/* tv[0].setVisibility(view.INVISIBLE);
tv[1].setVisibility(view.INVISIBLE);*/
//set also the button to invisible
loginBtn.setVisibility(view.INVISIBLE);
//set visible the progress bar
pb.setVisibility(view.VISIBLE);
//set now the user login credentials
credentials[0] = userText.getText().toString();
credentials[1] = passwordText.getText().toString();
loginTask = new LoginTask(credentials,"login");
//loginTask.execute("http://10.0.2.2/sampleRequest.php");
//loginTask.execute("http://10.0.2.2/motorpool_june_2016_laravel/public/mobile/login");
loginTask.execute("http://128.199.105.49/mobile/login");
//SessionHolder.login(credentials, la);
}
});
However it is still not working. Please help. :(
You can't compare Strings with == in java. You must write it like below:
if(this.privateRequest.equals("login")){
== tests for reference equality (whether they are the same object)

How to send multiple bitmap images to the server

I want to send the multiple images to server.I have created the bitmap for each selected images.But the last bitmap image are send to the server.How to send all bit map images at once in android.I have tried like this
class ImageUploadTask extends AsyncTask<String, Void, String> {
String sResponse = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(Room_addroom1.this, "Uploading",
"Please wait...", true);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
String url ="http://airbnb.abservetech.com/demo/public/mobile/hotel/roomsadd";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
int i=0;
mImageIds = new ArrayList<String>();
ByteArrayBody mImageByteArray = null;
for ( i = 0; i < ImgData.size(); i++) {
Log.d("ImgData(i)--", String.valueOf(ImgData.get(i)));
Bitmap bitmap = decodeFile(ImgData.get(i));
String image = getStringImage(bitmap);
mImageIds.add(image);
Log.d("Image--", image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
mImageByteArray = new ByteArrayBody(byteArray, Long.toString(System.currentTimeMillis()) + ".jpg");
entity.addPart("room_images", mImageByteArray);
Log.d("ByteArray--", String.valueOf(mImageByteArray));
// entity.addPart("room_images", mImageByteArray);
}
Log.d("ByteArray-out--", String.valueOf(mImageByteArray));
/* entity.addPart("room_images", new ByteArrayBody(byteArray,
"image/jpeg", params[1]));*/
entity.addPart("user_id", new StringBody("52"));
entity.addPart("room_type",new StringBody( "premium"));
entity.addPart("room_prize", new StringBody("2356"));
httpPost.setEntity(entity);
// String entityContentAsString = new String(bos.toByteArray());
// Log.e("multipartEntitty:", "" + entityContentAsString);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
entity.writeTo(bytes);
String content = bytes.toString();
String content1 = entity.toString();
/* Log.e("MultiPartEntityRequest:",content);
Log.e("MultiPartEntity---11:",content1);*/
HttpResponse response = httpClient.execute(httpPost,
localContext);
sResponse = EntityUtils.getContentCharSet(response.getEntity());
System.out.println("sResponse : " + sResponse);
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return sResponse;
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
count++;
if (count <ImgData.size()) {
Toast.makeText(getApplicationContext(),
sResponse + " Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
// new ImageUploadTask().execute(count + "", "hm" + count
// + ".jpg");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
First you can create bitmap to base64.
then create jsonstring of these all base64 String of bitmap and send JsonString to post the server.
That's easy wat to send multiple image to server.
Another way,
When you select first image then you create base64 of these image at a time you send base64 to server, then select another image and convert to base64 and send another base64 to server. That method also use for one by one image store to server.
try this :
mImageIds = new ArrayList<String>();
for ( i = 0; i < ImgData.size(); i++) {
Log.d("ImgData(i)--", String.valueOf(ImgData.get(i)));
Bitmap bitmap = decodeFile(ImgData.get(i));
String image = getStringImage(bitmap);
mImageIds.add(image);
Log.d("Image--", image);
entity.addPart("images", new StringBody(image));
}
The only thing you were doing wrong was you were intializing a new object of the ArrayList for every iteration of the for loop. So, only the last element was being added to the ArrayList. Moving it outside will solve your problem.

Android: Downloading images crashing app on API 8

I have a problem in API 8 with AsyncTask...
Here is my code...
try{
new loadPhotos().execute(""+USER._id,"date","DESC");
}catch(Exception e){
e.printStackTrace();
}
Before you ask... YES I am desperate, so I surrounded EVERYTHING with try{}catch
public class loadPhotos extends AsyncTask<String,Object,Void>{
ProgressBar pb;
ImageView img;
TableRow.LayoutParams paramsImage;
List<String> urlsOfImages;
TableLayout tl;
TableRow tr;
LayoutParams lp;
int numberOfPhotos=0;
#Override
protected void onPreExecute(){
urlsOfImages = new ArrayList<String>(); //There is stored urls of all images ( www.example.com/image1.jpg ... etc)
try {
allUserPhotoBitmaps.clear(); //allUserPhotoBitmaps is List<Bitmap>
pb = (ProgressBar) findViewById(R.id.profile_photos_progress_bar);
pb.setVisibility(View.VISIBLE);
tl = (TableLayout) findViewById(R.id.profile_photos_table_layout);
tl.removeAllViews();
tr = new TableRow(Profile.this);
lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tr.setLayoutParams(lp);
}catch(Exception e){
Toast.makeText(Profile.this, "Error in onPreExecute", Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(String... arg) {
try{
// This function basicaly returns List<HashMap<String,String>> with informations about photos ( web_path, latitude, longitude, city, etc...)
allUserPhotoInformations = myDb.getUrlsOfUserImages(arg[0],arg[1],arg[2]);
}catch(Exception e){
Toast.makeText(Profile.this, "Error downloading images", Toast.LENGTH_SHORT).show();
}
if ( allUserPhotoInformations != null ) {
for (int i=0 ; i < allUserPhotoInformations.size() ; i++){
try{
Bitmap bm = getBitmapFromURL(allUserPhotoInformations.get(i).get("file_path"));
allUserPhotoBitmaps.add(bm);
publishProgress(bm,i);
}
catch(Exception e){
return null;
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Object... arg){
img = new ImageView(getBaseContext());
paramsImage = new TableRow.LayoutParams( (((int)screenWidth)/2)-16 , (((((int)screenWidth)/2)-15)/16)*11 );
paramsImage.setMargins(10,10,0,0);
img.setLayoutParams(paramsImage);
img.setBackgroundColor(Color.parseColor("#FF000000"));
try{
img.setImageBitmap((Bitmap) arg[0]);
}catch(Exception e){
Toast.makeText(Profile.this,"Cannot put Bitmap into ImageView",Toast.LENGTH_LONG).show();
}
img.setVisibility(View.VISIBLE);
img.setOnClickListener(new ImageListener((Integer)arg[1])); //here I passing index to onClickListener
tr.addView(img);
if ( numberOfPhotos==1 ){
try{
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}catch(Exception e){
e.printStackTrace();
Toast.makeText(Profile.this,"Cannot inflate tableLayout",Toast.LENGTH_LONG).show();
}
tr = new TableRow(Profile.this);
tr.setLayoutParams(lp);
numberOfPhotos--;
}
else {
numberOfPhotos++;
}
}
#Override
protected void onPostExecute(Void arg){
pb.setVisibility(View.GONE);
userPhotos.setText("uploaded: "+allUserPhotoBitmaps.size()+" photos");
if ( numberOfPhotos==1 ){
try{
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}catch(Exception e){
e.printStackTrace();
Toast.makeText(Profile.this,"Cannot inflate tableLayout",Toast.LENGTH_LONG).show();
}
tr = new TableRow(Profile.this);
tr.setLayoutParams(lp);
}
}
In my device ( API > 15 ) everything works great, but in API 10 it crashes the app... I you want , I can provide also OnClickListener or some othere methods...
Yes, here ... How I download pictures :
public Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
double width;
double height;
width = (screenWidth)/myBitmap.getRowBytes();
if ( myBitmap.getWidth() > myBitmap.getHeight() ){
Log.w("size","landscape");
height = ((myBitmap.getRowBytes()*width)/16)*11;
width = (height/11)*16;
}
else {
Log.w("size","protrait");
height = ((myBitmap.getRowBytes()*width)/11)*16;
width = (height/16)*11;
}
Bitmap bitmap = Bitmap.createScaledBitmap(myBitmap, (int)width, (int)height, true);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Profile.this, "Error parsing image to bitmap", Toast.LENGTH_LONG).show();
return null;
}
}
Any help ?
call new loadPhotos().execute(""+USER._id,"date","DESC"); in onCreate and Use Asynctask and try to avoid load in main thread. Your application crash one of the main reason may be if you are calling the methode in main thread.
Ex:
String zoomouturl = "your url";
new ImageDownload().execute(zoomouturl);
Try
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
loadBitmap(zoomouturl, bmOptions);
return zoomouturl;
}
protected void onPostExecute(String imageUrl) {
if (!imageUrl.equals("")) {
Constants._image.setImageBitmap(bm);
} else {
Toast.makeText(this,
"not found proper bitmap.. ", Toast.LENGTH_LONG)
.show();
}
}
}
and
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}

FourSquare Photo upload on checkin with Android

I need to upload photo on checkin using FourSquare.If anybody has done it,Please help me in passing parameters.I have referred FourSquare Offical Document :
https://developer.foursquare.com/docs/photos/add. I am facing issue in Last three parameters.
Please Help me if you have done it.Thank You in Advance...
The parameters postUrl, postContentId, and postText are optional, so you do not need to provide them. postUrl and postContentId are used to provide a link that your photo can link to for more information. postText is a short comment about the photo.
/*
* put foursquare sdk file into projects libs folder and the later code into the Activity file
*/
todaydate = Latest Date;
venueId = The Venue Id is important.
URL = The image url from which the image will be downloaded to sd card;
foursquare = new Foursquare(
"Your Client Id", //*client id
"Your Client Secret", //*client secret
"Callback Url");
foursquare.authorize(ActivityName.this, new FoursquareAuthenDialogListener());
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#SuppressLint("SdCardPath")
private class FoursquareAuthenDialogListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
foursquareAccessToken = Foursquare.mAccessToken;
//Toast.makeText(getApplicationContext(), "TOKEN: " + foursquareAccessToken, Toast.LENGTH_LONG).show();
new downloadUploadedImage().execute();
}
#Override
public void onFoursquareError(FoursquareError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
}
/*
* downloadUploadedImage Class will download image from url and convert to bitmap image,
* using that bitmap image then convert it to file and get the file path from sd card
* to upload image to fs from sdcard.
*/
public class downloadUploadedImage extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(MyActivityName.this, "", "Posting Image to Foursquare...", true);
}
#Override
protected String doInBackground(String... params) {
bitMapImage = downloadImage(URL);
writeExternalToCache(bitMapImage, file);
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
if(file.exists()){
//Toast.makeText(getApplicationContext(), "PIC PATH: " + file.toString(), Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), "PIC PATH: " + picPATH, Toast.LENGTH_LONG).show();
picturePath = file.toString();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath,options);
final int REQUIRED_SIZE=200;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(options.outWidth/scale/2>=REQUIRED_SIZE && options.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
preview_bitmap = BitmapFactory.decodeFile(picturePath,o2);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
preview_bitmap.compress(CompressFormat.JPEG, 75, bos);
fileContent = bos.toByteArray(); //byte array static byte[] fileContent;
new UploadImageToFsProfile().execute();
} else {
//Toast.makeText(getApplicationContext(), "Image not exist in sdcard.", Toast.LENGTH_LONG).show();
}
}
}
public class UploadImageToFsProfile extends AsyncTask<String, Void, String>{//params,progress,result
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://api.foursquare.com/v2/photos/add");
try
{
#SuppressWarnings("deprecation")
/*
* To use MultipartEntity class use httpclient-X.x.jar , httpcore-X.x.jar ,httpmime-X.x.jar
* and apachemime4jcore-X.x.jar
*/
MultipartEntity entity = new MultipartEntity();
entity.addPart("v", new StringBody(todaydate));
entity.addPart("venueId", new StringBody(venueId));
entity.addPart("public", new StringBody("1"));
entity.addPart("oauth_token", new StringBody(foursquareAccessToken));
ByteArrayBody imgBody = new ByteArrayBody(ChFsLogin.fileContent, "image/jpeg", "FS_image");
entity.addPart("image",imgBody);
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
responseResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e)
{ }
catch (IOException e)
{ }
return responseResult;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
dialog.dismiss();
System.out.println("RES"+responseResult);
JSONObject obj;
try {
obj = new JSONObject(result);
//JSONArray meta =
obj = obj.getJSONObject("meta");
code = obj.getInt("code");
if(obj.has("errorDetail")){
Toast.makeText(getApplicationContext(), obj.getString("errorDetail"), Toast.LENGTH_LONG).show();
}
//Toast.makeText(getApplicationContext(), "code:"+code, Toast.LENGTH_LONG).show();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (code ==200) {
Toast.makeText(getApplicationContext(), "Your Image Has Successfully Posted to FourSquare.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to Post Image to FourSquare.", Toast.LENGTH_LONG).show();
}
File fileToDelete = new File(file.toString());
boolean deleted = fileToDelete.delete();
if (deleted) {
} else {
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
I successfully uploaded the images to Foursquare via the code below:
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://api.foursquare.com/v2/photos/add");
try
{
MultipartEntity entity = new MultipartEntity();
entity.addPart("v", new StringBody("20121210"));
entity.addPart("venueId", new StringBody(venue.getId()));
entity.addPart("public", new StringBody("1"));
entity.addPart("oauth_token", new StringBody(mAccessToken));
ByteArrayBody imgBody = new ByteArrayBody(bitmapdata, "image/jpeg", "FS_image");
entity.addPart("image",imgBody);
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
Log.v("response","" +response);
responseResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e)
{
Log.d(TAG, "Opening URL " +e);
}

Sending the files (At least 11 files) from folder through web service to android app

I stuck in middle of this situation,Please help me out.
My question is that I want to send files (Total 11 PDF Files) to android app using web service.
I tried it with below code.Main Class from which web service is created
public class MultipleFilesImpl implements MultipleFiles {
public FileData[] sendPDFs() {
FileData fileData = null;
// List<FileData> filesDetails = new ArrayList<FileData>();
File fileFolder = new File(
"C:/eclipse/workspace/AIPWebService/src/pdfs/");
// File fileTwo = new File(
// "C:/eclipse/workspace/AIPWebService/src/simple.pdf");
File sendFiles[] = fileFolder.listFiles();
// sendFiles[0] = fileOne;
// sendFiles[1] = fileTwo;
DataHandler handler = null;
char[] readLine = null;
byte[] data = null;
int offset = 0;
int numRead = 0;
InputStream stream = null;
FileOutputStream outputStream = null;
FileData[] filesData = null;
try {
System.out.println("Web Service Called Successfully");
for (int i = 0; i < sendFiles.length; i++) {
handler = new DataHandler(new FileDataSource(sendFiles[i]));
fileData = new FileData();
data = new byte[(int) sendFiles[i].length()];
stream = handler.getInputStream();
while (offset < data.length
&& (numRead = stream.read(data, offset, data.length
- offset)) >= 0) {
offset += numRead;
}
readLine = Base64Coder.encode(data);
offset = 0;
numRead = 0;
System.out.println("'Reading File............................");
System.out.println("\n");
System.out.println(readLine);
System.out.println("Data Reading Successful");
fileData.setFileName(sendFiles[i].getName());
fileData.setFileData(String.valueOf(readLine));
readLine = null;
System.out.println("Data from bean " + fileData.getFileData());
outputStream = new FileOutputStream("D:/"
+ sendFiles[i].getName());
outputStream.write(Base64Coder.decode(fileData.getFileData()));
outputStream.flush();
outputStream.close();
stream.close();
// FileData fileDetails = new FileData();
// fileDetails = fileData;
// filesDetails.add(fileData);
filesData = new FileData[(int) sendFiles[i].length()];
}
// return fileData;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return filesData;
}
}
Also The Interface MultipleFiles:-
public interface MultipleFiles extends Remote {
public FileData[] sendPDFs() throws FileNotFoundException, IOException,
Exception;
}
Here I am sending an array of bean "File Data",having properties viz. FileData & FileName.
FileData- contains file data in encoded.
FileName- encoded file name.
The Bean:- (FileData)
public class FileData {
private String fileName;
private String fileData;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileData() {
return fileData;
}
public void setFileData(String string) {
this.fileData = string;
}
}
The android DDMS gives out of memory exception when tried below code & when i tried to send two files then only first file is created.
public class PDFActivity extends Activity {
private final String METHOD_NAME = "sendPDFs";
private final String NAMESPACE = "http://webservice.uks.com/";
private final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
private final String URL = "http://192.168.1.123:8080/AIPWebService/services/MultipleFilesImpl";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textViewOne = (TextView) findViewById(R.id.textViewOne);
try {
SoapObject soapObject = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(soapObject);
textViewOne.setText("Web Service Started");
AndroidHttpTransport httpTransport = new AndroidHttpTransport(URL);
httpTransport.call(SOAP_ACTION, envelope);
// SoapObject result = (SoapObject) envelope.getResponse();
Object result = envelope.getResponse();
Log.i("Result", result.toString());
// String fileName = result.getProperty("fileName").toString();
// String fileData = result.getProperty("fileData").toString();
// Log.i("File Name", fileName);
// Log.i("File Data", fileData);
// File pdfFile = new File(fileName);
// FileOutputStream outputStream =
// openFileOutput(pdfFile.toString(),
// MODE_PRIVATE);
// outputStream.write(Base64Coder.decode(fileData));
Log.i("File", "File Created");
// textViewTwo.setText(result);
// Object result = envelope.getResponse();
// FileOutputStream outputStream = openFileOutput(name, mode)
} catch (Exception e) {
e.printStackTrace();
}
}
}
Please help with some explanation or changes in my code.
Thanks in Advance.
Myself got the solution of this question.
The major problem I faced using kSoap2 api 2.4 version is that I can't able to get complex object (array of bean in my case)
Then I changed my code from this (using ver 2.4):-
try {
SoapObject soapObject = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(soapObject);
textViewOne.setText("Web Service Started");
AndroidHttpTransport httpTransport = new AndroidHttpTransport(URL);
httpTransport.call(SOAP_ACTION, envelope);
// SoapObject result = (SoapObject) envelope.getResponse();
Object result = envelope.getResponse();
Log.i("Result", result.toString());
// String fileName = result.getProperty("fileName").toString();
// String fileData = result.getProperty("fileData").toString();
// Log.i("File Name", fileName);
// Log.i("File Data", fileData);
// File pdfFile = new File(fileName);
// FileOutputStream outputStream =
// openFileOutput(pdfFile.toString(),
// MODE_PRIVATE);
// outputStream.write(Base64Coder.decode(fileData));
Log.i("File", "File Created");
// textViewTwo.setText(result);
// Object result = envelope.getResponse();
// FileOutputStream outputStream = openFileOutput(name, mode)
} catch (Exception e) {
e.printStackTrace();
}
to this code (using ver 2.5.1):-
try {
SoapObject soapObject = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(soapObject);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
for (int i = 0; i < result.getPropertyCount(); i++) {
SoapObject object = (SoapObject) result.getProperty(i);
Log.i("File Data", object.getProperty("fileData").toString());
Log.i("File Name", object.getProperty("fileName").toString());
pdfFiles = new File(object.getProperty("fileName").toString());
outputStream = openFileOutput(pdfFiles.toString(), MODE_PRIVATE);
outputStream.write(Base64Coder.decode(object.getProperty(
"fileData").toString()));
}
outputStream.flush();
outputStream.close();
Log.d("File Creation Message", "Files Created Succesfully");
} catch (SoapFault fault) {
fault.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
outputStream = null;
}
}
Hence I got solution.
The main help is through the issue-24 of this :- Please read that if u are facing such problem.Link-Issue-24

Categories

Resources