Sending json Post date in android with parameter - java

I'm trying to make a POST request with Android, but I'm not succeeding. I think the problem is in how to set the parameters for resquisição and Header. Below is my method I do the request ...
public void testPostDate() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
Gson gson = new Gson();
CrimePOST.Crime crime = new CrimePOST().new Crime(10, "São Paulo",
"descrição", 10.00, 30.00);
CrimePOST crimePost = new CrimePOST();
crimePost.setCrime(crime);
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("token",
"0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJa6JhMs="));
String json = gson.toJson(crimePost);
String paramString = URLEncodedUtils.format(params, Utils.ENCODE);
try {
HttpPost post = new HttpPost(
"http://safe-sea-4024.herokuapp.com/crimes/mobilecreate"
+ "?" + paramString);
post.setHeader("Content-Type", "application/json");
StringEntity entitty = new StringEntity(json);
entitty.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(entitty);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = toString(in);
System.out.println(a);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This method is responsible for converting an inputStream to String
private String toString(InputStream is) throws IOException {
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int lidos;
while ((lidos = is.read(bytes)) > 0) {
baos.write(bytes, 0, lidos);
}
return new String(baos.toByteArray());
}
Really I am passing the Header correctly?

You have to do this in an AsyncTask

I wrote this tutorial while back. it does send json data via HTTP Post to a url. Check it out. Original post can be found here:http://androidhappenings.blogspot.com/2013/03/android-app-development-201-1st.html
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity implements LocationListener{
private TextView textView =null;
LocationManager locationManager=null;
Location location=null;
protected String url;
protected JSONObject jsonData=null;
private EditText urlText=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(gpsEnabled!=true) {
Toast.makeText(getApplicationContext(), "GPS Disbled! Please Enable to Proceed!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
textView = (TextView)findViewById(R.id.textView);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this);
urlText = (EditText)findViewById(R.id.urlTextbox);
Button submitButton = (Button)findViewById(R.id.submitUrl);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (urlText.getText()!=null) {
url=urlText.getText().toString();
System.out.println(url);//for testing only, not required
Toast.makeText(getApplicationContext(), "Url Submitted, Sending data to Web Service at url: " + url, Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onLocationChanged(final Location location) {
this.location=location;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
int cnt=1;
public void run() {
handler.post(new Runnable() {
public void run() {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
Double altitude = location.getAltitude();
Float accuracy = location.getAccuracy();
textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt);
try {
jsonData = new JSONObject();
jsonData.put("Latitude", latitude);
jsonData.put("Longitude", longitude);
jsonData.put("Altitude", altitude);
jsonData.put("Accuracy", accuracy);
System.out.println(jsonData.toString());//not required, for testing only
if(url!=null) {
new HttpPostHandler().execute();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cnt++;
}
});
}};
ourtimer.schedule(timerTask, 0, 120000);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public class HttpPostHandler extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity dataEntity = null;
try {
dataEntity = new StringEntity(jsonData.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpPost.setEntity(dataEntity);
httpPost.setHeader("Content-Type", "application/json");
try {
httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Related

I have taken text from JSON format of an API now I want to add image to it from same API in my android app

I'm new to android and finding it tough to update realtime text and images from API's in JSON format. I've successfully added text to my listview. Now I want to add image beside it. Thanks in advance.
MainActivity.java file
package com.example.android.samplelayout;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.net.Uri;
import android.graphics.drawable.Drawable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://webhose.io/search?token=9c55cbb1-2f1c-4700-9c1e-67e685152506&format=json&q=Indian%20Startup";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONObject responseObject = jsonObj.getJSONObject("response");
JSONArray responseArray = jsonObj.getJSONArray("posts");
// looping through All Contacts
for (int i = 0; i < responseArray.length(); i++) {
JSONObject firstObject = responseArray.getJSONObject(i);
//JSONObject titleObject = firstObject.getJSONObject("title");
// Extract out the title, time, and tsunami values
//String image = firstObject.getString("main_image");
String title = firstObject.getString("title");
// tmp hash map for single contact
HashMap<String , String> contact = new HashMap<>();
// adding each child node to HashMap key => value
//contact.put("pic", image);
contact.put("name", title);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,R.layout.list_item, new String[]{"name"}, new int[]{ R.id.name});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java file
package com.example.android.samplelayout;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I would suggest using a library that automatically puts an Image into an ImageView only using the Url of the image you want to use. Picasso would be a good Library for your use. You have to fetch the Image URL off the Json object and load it into the ImageView using Picasso's load().into()

Sending periodic location updates to server using async task android

I am trying to develop an application that send locations periodically to a server through http post. I have tried the async task in the following code. I am new to android programming. I get the error "failed to connect to /10.0.2.2 (port 8080): connect failed: ETIMEDOUT (Connection timed out)" and "E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1" when I run this code. Please help me out
package com.example.vikram.locationinterval;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownServiceException;
import java.nio.charset.Charset;
import java.security.Permission;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
protected LocationManager locationManager;
TextView txtLat,content;
protected static int intervalInMillis = 500;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
content = (TextView)findViewById( R.id.content );
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, intervalInMillis, 0.5f, this);
}
#Override
public void onLocationChanged(Location location) {
long now = System.currentTimeMillis();
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude() + "\n now = " + now);
try{
System.out.println("\nTesting 2 - Send Http POST request");
new MyAsyncTask(String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude())).execute();
}
catch(Exception ex)
{
//System.out.println(ex.getCause());
}
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double> {
protected String latitude,longitude;
protected MyAsyncTask(String lat,String lon){
this.latitude = lat;
this.longitude = lon;
}
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
try {
postData(this.latitude, this.longitude);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result){
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
public void postData(String Lat,String Lon) throws UnsupportedEncodingException {
// Create data variable for sent values to server
String data = URLEncoder.encode("Latitude", "UTF-8")
+ "=" + URLEncoder.encode(Lat, "UTF-8");
data += "&" + URLEncoder.encode("Longitude", "UTF-8") + "="
+ URLEncoder.encode(Lon, "UTF-8");
System.out.println(data);
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://10.0.2.2:8080/GetSomeRest/webresources/service");
// Send POST data request
String charset = "UTF-8";
URLConnection conn = url.openConnection();
conn.setReadTimeout(5000);
System.out.println("coonnected.: ");
Permission p = conn.getPermission();
System.out.println("permission: " + p.toString());
conn.setDoOutput(true);
conn.setRequestProperty("Accept-Charset", charset);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
System.out.println("output gate opened.."+conn.toString());
OutputStream wr;
try {
//conn.connect();
wr = conn.getOutputStream();
if(wr == null){
System.out.println("-> no stream!");
}
else {
wr.write(data.getBytes(Charset.forName(charset)));
//wr.flush();
wr.close();
}
} catch (UnknownServiceException use){
System.out.println("error unknown server: "+use.getMessage());
} catch (IOException connOI){
System.out.println("error io stream: "+connOI.getMessage());
} catch (Exception connOSW){
System.out.println("error writing to stream: "+connOSW.getMessage());
}
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response on activity
content.setText( text );
}
}
}

image upload to server of php error come in response = httpclient.execute(httppost);

i was make two file one is mainActivity and second is MultipartEntity
i post both file
MainActivity.java
package com.example.picupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button mTakePhoto;
private ImageView mImageView;
private static final String TAG = "upload";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTakePhoto = (Button) findViewById(R.id.take_photo);
mImageView = (ImageView) findViewById(R.id.imageview);
mTakePhoto.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
switch (id) {
case R.id.take_photo:
takePhoto();
break;
}
}
private void takePhoto() {
// Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
// startActivityForResult(intent, 0);
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.i(TAG, "onActivityResult: " + this);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
setPic();
// Bitmap bitmap = (Bitmap) data.getExtras().get("data");
// if (bitmap != null) {
// mImageView.setImageBitmap(bitmap);
// try {
// sendPhoto(bitmap);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
}
private void sendPhoto(Bitmap bitmap) throws Exception {
new UploadTask().execute(bitmap);
}
private class UploadTask extends AsyncTask<Bitmap, Void, Void> {
protected Void doInBackground(Bitmap... bitmaps) {
if (bitmaps[0] == null)
return null;
setProgress(0);
Bitmap bitmap = bitmaps[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert Bitmap to ByteArrayOutputStream
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert ByteArrayOutputStream to ByteArrayInputStream
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://192.168.8.84:8003/savetofile.php"); // server
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("myFile",
System.currentTimeMillis() + ".jpg", in);
httppost.setEntity(reqEntity);
Log.i(TAG, "request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (response != null)
Log.i(TAG, "response " + response.getStatusLine().toString());
} finally {
}
} finally {
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(MainActivity.this, R.string.uploaded, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(TAG, "onResume: " + this);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
}
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
File photoFile = null;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
/**
* http://developer.android.com/training/camera/photobasics.html
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String storageDir = Environment.getExternalStorageDirectory() + "/picupload";
File dir = new File(storageDir);
if (!dir.exists())
dir.mkdir();
File image = new File(storageDir + "/" + imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.i(TAG, "photo path = " + mCurrentPhotoPath);
return image;
}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor << 1;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
Matrix mtx = new Matrix();
mtx.postRotate(90);
// Rotating Bitmap
Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
mImageView.setImageBitmap(rotatedBMP);
try {
sendPhoto(rotatedBMP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MultipartEntity.java
package com.example.picupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
#Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
#Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
#Override
public boolean isChunked() {
return false;
}
#Override
public boolean isRepeatable() {
return false;
}
#Override
public boolean isStreaming() {
return false;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
#Override
public Header getContentEncoding() {
return null;
}
#Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
#Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
saveimage.php
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "upload/" . $_FILES['myFile']['name']);
echo 'successful';
}
?>
geting error in
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
please help me to solve..
working for me and please try to different network like wifi or mobile data
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
} } catch (ClientProtocolException e) {
responseString = e.toString(); } catch (IOException e) {
responseString = e.toString(); } return responseString;
Hey you can use this method for sending image to server
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public static JSONObject sendJSONDataWithImage() {
String Content = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.8.84:8003/savetofile.php");
File file = new File(yourFilePathwithfileName);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
Charset chars = Charset.forName("UTF-8");
int size = (int) file.length();
byte[] bytes = new byte[size];
ByteArrayBody bab = null;
try {
BufferedInputStream buf = new BufferedInputStream(
new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
bab = new ByteArrayBody(bytes, yourFilePathwithfileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// reqEntity.addPart("user_id", new StringBody(otherParameter,chars));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
reqEntity.addPart("myFile", bab);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response;
try {
response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder s = new StringBuilder();
String sResponse;
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
json = s.toString();
System.out.println("Response.............: " + json);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
Log.e("add emp with img Response", "> " + json.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
Please try this code:
package com.secondhandbooks.http;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.secondhandbooks.util.ConvertStreamIntoString;
import com.secondhandbooks.util.SaveImageIntoDrawable;
public abstract class BaseAsync_Post extends AsyncTask<String, String, InputStream>
{
Context context ;
private HttpPost httppost;
String url ;
Dictionary<String, String> dictionary ;
public BaseAsync_Post(String url , Dictionary<String, String> dictionary, Context context) {
this.url = url ;
this.dictionary = dictionary;
this.context = context ;
Enumeration<String> enumeration = dictionary.keys() ;
showLogs("constructor") ;
while ( enumeration.hasMoreElements() )
{
showLogs( enumeration.nextElement() ) ;
}
}
#Override
abstract protected void onPreExecute() ;
#Override
abstract protected void onPostExecute(InputStream result) ;
#Override
protected InputStream doInBackground(String... params) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
InputStream is = null;
HttpClient httpclient = new DefaultHttpClient();
httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(50);
Enumeration<String> enumeration = dictionary.keys() ;
while ( enumeration.hasMoreElements() )
{
String key = enumeration.nextElement() ;
if ( key.equals("file") )
{
final File file = new File(SaveImageIntoDrawable.savedImagePath);
if ( file.isFile() )
{
showLogs("is file");
}
else
{
showLogs("no-file");
}
FileBody fb = new FileBody(file);
entity.addPart(key, fb);
}
else
{
entity.addPart(key, new StringBody(dictionary.get(key)));
}
}
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity1 = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity1);
is = bufHttpEntity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
showLogs("ClientProtocolException");
} catch (IOException e) {
e.printStackTrace();
showLogs("IOException");
}
return is;
}
public String getString(JSONObject json, String TAG) {
String returnParseData = "";
try {
Object aObj = json.get(TAG);
if (aObj instanceof Boolean) {
returnParseData = Boolean.toString(json.getBoolean(TAG));
} else if (aObj instanceof Integer) {
returnParseData = Integer.toString(json.getInt(TAG));
} else if (aObj instanceof String) {
returnParseData = json.getString(TAG);
} else {
returnParseData = json.getString(TAG);
}
} catch (Exception err) {
err.printStackTrace();
returnParseData = "";
}
return returnParseData;
}
public String getIntintoString(JSONObject json, String TAG) {
int returnParseData = -1;
try {
returnParseData = json.getInt(TAG) ;
} catch (Exception err) {
err.printStackTrace();
returnParseData = -1;
}
return Integer.toString(returnParseData) ;
}
public void showLogs ( String msg )
{
Log.e("HTTP-POST", msg) ;
}
}
Try this simple code in your android, it works for me,
String url = "";// URL where image has to be uploaded
String fileName = ""; //path of file to be uploaded
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent = new FiSystem.out.println("hello");
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Hope this helps you with your problem...!!!!!

ANDROID: Code not working after inserting Date string to GET Url

I am making a android client that reports its location to my server after every 10 seconds.
For server I'm using dynamic DNS. I have to sent latitude, longitude and time-stamp as GET parameters.
I made the following working code:
package in.kirancity.trackapp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity
{
TextView textLat;
TextView textLong;
TextView textRes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLat = (TextView)findViewById(R.id.textLat);
textLong = (TextView)findViewById(R.id.textLong);
textRes = (TextView)findViewById(R.id.textRes);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, ll);
}
class myLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location arg0)
{
if(arg0 != null)
{
double plong = arg0.getLongitude();
double plat = arg0.getLatitude();
String url = "http://vishalhome.myftp.org/insert.php?la="+Double.toString(plat)+"&ln="+Double.toString(plong)+"&d='Arbitrary'";
textLat.setText(Double.toString(plat));
textLong.setText(Double.toString(plong));
new RequestTask().execute(url);
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
class RequestTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
TextView tv=(TextView)findViewById(R.id.textRes);
tv.setText(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This code works fine for me. But instead of sending actual time-stamp i sent "Arbitrary" string.
After successfully executing asyncTask, the values are inserted and Response is: "inserted"(Returned by my php page).
But when I'm trying this in onLocationChanged:
String url = "http://vishalhome.myftp.org/insert.php?la="+Double.toString(plat)+"&ln="+Double.toString(plong)+"&d=\'";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
url = url + currentDateandTime + "\'";
the application crashes on location change event.
I tried to put try catch blocks, but no clue of problem.
I think problem is coming out after new RequestTask(url) is called.
Please assist !
I think you should encode the url before using it. Try this:
currentDateandTime = URLEncoder.encode(currentDateandTime, "utf-8");
url = url + currentDateandTime + "\'";
Please see URL encoding in Android

Android Emulator connecting to Local Web service

Hi all I have a local web service set up on my machine, it is a web service which was built in netbeans using the JPA. I have it connecting locally to a mySQL server also. I have both the database and web service connecting. The webservice can display XML/JSON. My problem is getting the android emulator to consume the JSON from the web service. The URL we are using is "http://10.0.2.2:8080/Web4/resources/hotel2s/" this should allow the emulator to connect to the web service am I correct? When I try to launch and consume the emulator crashes. Here is some source code. We are sure that it should read in and parse with GSON etc but we are not sure if it is connecting or not.
RESULT CLASS
public class hotel_Result
{
#SerializedName("hotelAddress")
protected String hotelAddress;
#SerializedName("HotelDescription")
protected String hotelDescription;
#SerializedName("hotelName")
protected String hotelName;
#SerializedName("hotelRating")
protected int hotelRating;
}
HOTEL RESPONSE CLASS
public class hotel_Response
{
public List<hotel_Result> hotelresults;
public String query;
}
MAIN CLASS
public class connectRest extends Activity
{
// We tried Reg's machines ip here as well and it crashed also used different ips is this correct for the emulator to connect to it?
String url = "http://10.0.2.2:8080/Web4/resources/hotel2s/";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputStream source = retrieveStream(url); // Stream in the URL
Gson gson = new Gson(); // GSON object
Reader reader = new InputStreamReader(source); // Read in the stream
hotel_Response response = gson.fromJson(reader,hotel_Response.class); // Fill in the variables in the class hotel_response
Toast.makeText(this,response.query,Toast.LENGTH_SHORT).show();
List<hotel_Result> hotelresults = response.hotelresults;
for(hotel_Result hotel_Result : hotelresults)
{
Toast.makeText(this,hotel_Result.hotelName,Toast.LENGTH_SHORT).show();
}
}
private InputStream retrieveStream(String url)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try{
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK)
{
Log.w(getClass().getSimpleName(),"Error" + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch(IOException e)
{
getRequest.abort();
Log.w(getClass().getSimpleName(),"Error for URL " + url, e);
}
return null;
}
}
Make sure you have the allow internet access permission in your manifest.
Here's a better try-catch implementation and it does the work in an AsyncTask() to keep the UI thread happy :) The original article can be found on Java Code Geeks (http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html) but it lacks my improvements!
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.Gson;
import com.javacodegeeks.android.json.model.Result;
import com.javacodegeeks.android.json.model.SearchResponse;
public class JsonParsingActivity extends Activity {
private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
protected InitTask _initTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
_initTask = new InitTask();
_initTask.execute( getApplicationContext() );
}
});
}
#Override
public void onStop() {
super.onStop();
_initTask.cancel(true);
}
protected class InitTask extends AsyncTask<Context, String, SearchResponse>
{
#Override
protected SearchResponse doInBackground( Context... params )
{
InputStream source = retrieveStream(url);
SearchResponse response = null;
if (source != null) {
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
try {
response = gson.fromJson(reader, SearchResponse.class);
publishProgress( response.query );
reader.close();
} catch (Exception e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
}
}
if (!this.isCancelled()) {
return response;
} else {
return null;
}
}
#Override
protected void onProgressUpdate(String... s)
{
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute( SearchResponse response )
{
super.onPostExecute(response);
StringBuilder builder = new StringBuilder();
if (response != null) {
String delim = "* ";
List<Result> results = response.results;
for (Result result : results) {
builder.append(delim).append(result.fromUser);
delim="\n* ";
}
}
if (builder.length() > 0) {
Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest;
try {
getRequest = new HttpGet(url);
HttpResponse getResponse = client.execute(getRequest);
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
} catch (Exception e) {
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
}
}
}
}
Here's a full try-catch implementation of the code above. I implemented this first and then realized all I really needed to know was pass/fail. Anyway, might help someone. Again, props go to Java Code Geeks for getting me started ... Android JSON Parsing with GSON Tutorial
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.javacodegeeks.android.json.model.Result;
import com.javacodegeeks.android.json.model.SearchResponse;
public class JsonParsingActivity extends Activity {
private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
protected InitTask _initTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
_initTask = new InitTask();
_initTask.execute( getApplicationContext() );
}
});
}
#Override
public void onStop() {
super.onStop();
_initTask.cancel(true);
}
protected class InitTask extends AsyncTask<Context, String, SearchResponse>
{
#Override
protected SearchResponse doInBackground( Context... params )
{
InputStream source = retrieveStream(url);
SearchResponse response = null;
if (source != null) {
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
try {
response = gson.fromJson(reader, SearchResponse.class);
publishProgress( response.query );
} catch (JsonSyntaxException e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
return null;
} catch (JsonIOException e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
return null;
} finally {
try {
reader.close();
} catch (IOException e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
}
}
}
if (!this.isCancelled()) {
return response;
} else {
return null;
}
}
#Override
protected void onProgressUpdate(String... s)
{
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute( SearchResponse response )
{
super.onPostExecute(response);
StringBuilder builder = new StringBuilder();
if (response != null) {
String delim = "* ";
List<Result> results = response.results;
for (Result result : results) {
builder.append(delim).append(result.fromUser);
delim="\n* ";
}
}
if (builder.length() > 0) {
Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest;
try {
getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
try {
return getResponseEntity.getContent();
} catch (IllegalStateException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
} catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
}
} catch (ClientProtocolException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
} catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
} catch (IllegalArgumentException e) {
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
}

Categories

Resources