I am trying to solve my problem that sometimes causes OutOfMemoryException. I am simply uploading a bitmap to server and then exiting activity. I've tried to recycle my bitmaps but the frag is still somehow big. This is my code:
private class UploadTask extends AsyncTask<Bitmap, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewEvent.this);
pDialog.setMessage("Uploading data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
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
bitmap.recycle();
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"my server"); // server
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("fileToUpload",
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)
try {
response1 = EntityUtils.toString(response.getEntity());
response1 = response1.replace("\n", "").replace("\r", "");
Log.i("TAG", "response " + response1);
} catch (IOException e) {
e.printStackTrace();
}
} 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) {
super.onPostExecute(result);
pDialog.dismiss();
uploadJSON();
}
}
bitmap.compress may cause OOM error. Try using BitmapFactory.decodeStream with BitmapFactory.Options
BitmapFactory.Options options = new BitmapFactory.Options();
options.outHeight=400;
options.outWidth=600;
BitmapFactory.decodeStream(inputStream, null, options);
Related
when the connection is so low i get an exception " failed to connect to : http ......", this is my code, can any one please helps me to avoid the exception.
when the connection is so low i get an exception " failed to connect to : http ......", this is my code, can any one please helps me to avoid the exception
private void parseM3uUrlAndPrepare_new(final String url) {
AsyncTask<String, Integer, String> asyn = new AsyncTask<String, Integer, String>(){
URL the_url;
HttpURLConnection conn;
String filePath = "";
InputStream inputStream;
HttpGet getRequest;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
the_url = new URL(url);
conn = (HttpURLConnection) the_url.openConnection(Proxy.NO_PROXY);
getRequest = new HttpGet(url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... params) {
if(conn != null) {
try {
inputStream = new BufferedInputStream(conn.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("#")) {
}
else if (line.length() > 0) {
filePath = "";
if (line.startsWith("http://")) { // Assume it's a full URL
filePath = line;
}
else { // Assume it's relative
try{
filePath = getRequest.getURI().resolve(line).toString();
}
catch(IllegalArgumentException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return filePath;
}
#Override
protected void onPostExecute(String filePath) {
try {
mediaPlayer.setDataSource(filePath);
DATA_SET = true;
mediaPlayer.prepareAsync(); //this will prepare file a.k.a buffering
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
asyn.execute("");
}
Maybe the problem is the BufferedInputStream. I wrote this code (a long time ago) if you want to try it.
Give an input stream to the fonction and let it work.
import java.io.InputStream;
import java.util.Scanner;
/**
* Created by badetitou.
*/
public class ReadIt {
public static String ReadIt(InputStream is){
return new Scanner(is,"UTF-8").useDelimiter("").next();
}
}
I am trying to save every output data in asynctask for each http call.But I am unable to see any data in a file.I really appreciate any help.Thanks in Advance.
final String[] ar={"1","2","3",.............,"25"}
filename="test_file";
myFile = new File("/sdcard/"+filename);
try {
myFile.createNewFile();
fOut = new FileOutputStream(myFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
myOutWriter = new OutputStreamWriter(fOut);
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = params[0];
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url_select));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
//
// // Read content & Log
// inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try{
JSONObject jArray = new JSONObject(result);
String name = jArray.getString("name");
if (name!=null) {
Log.w("idname", name);
//
myOutWriter.append(name).append("\r\n");
//
Toast.makeText(getBaseContext(), name, 5).show();
}
// End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You close the myOutWriter after start MyAsyncTask. So when MyAsyncTask try to write data to file, it throw OutputStreamWriter is closed exception.
You need remove the code of close myOutWriter from here. Add add close code at the end of onPostExecute like below:
void onPostExecute(Void v) {
.....
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count = taskCount.decrementAndGet()
if(count == 0 ) {
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // protected void onPostExecute(Void v)
the definition of taskCount is like this:
AtomicInteger taskCount = new AtomicInteger(ar.length - 1);
At last, I think Thread and CountDownLatch is better option
check if entity not null then write to db
HttpEntity entity = response.getEntity();
if(entity!=null ){
inputStream = entity.getContent();
}
I am trying to allow Android users to post images to Twitter/Tumblr using my app. I am able to authenticate and retrieve user and account info, but I am having trouble with the actual image upload. (Basically I'm ok with all of the HTTP GET api calls, but not the HTTP POST).
I am receiving the following errors (Twitter/Tumblr respectively):
"response":{"errors":[{"message":"Error creating status","code":189}]}
"response":{"errors":["Error uploading photo."]},"meta":{"msg":"Bad Request","status":400}
Does anyone know what this means? I don't believe it's an authentication error, because I am able to get user info, etc... It looks to me like the problem is with the parameters, presumably media.
I have tried a number of options, including using the image file/data/url, using HttpParams/MultipartEntity, and using "media"/"media[]" but haven't had much success. Below is the current code that I am using. Is there something wrong with my format? Is there something else Twitter/Tumblr is looking for? If anyone has any ideas, suggestions, or improvements, they would be much appreciated. Thanks!
private class TwitterShareTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
HttpClient httpclient = GlobalValues.getHttpClient();
HttpPost request = new HttpPost("https://api.twitter.com/1.1/statuses/update_with_media.json");
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("status", new StringBody(ETdescription.getText().toString()));
entity.addPart("media[]", new FileBody(new File(GlobalValues.getRealPathFromURI(
Camera_ShareActivity.this, imageUri))));
request.setEntity(entity);
TwitterUtils.getTwitterConsumer().sign(request);
HttpResponse response = httpclient.execute(request, GlobalValues.getLocalContext());
HttpEntity httpentity = response.getEntity();
InputStream instream = httpentity.getContent();
result = GlobalValues.convertStreamToString(instream);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
return result;
}
public void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result.trim());
System.out.println(jObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
~~~ Edit: As requested by YuDroid ~~~
private static class TwitterUploadTask extends AsyncTask<String, Void, String> {
private File image;
private String message;
private OAuthConsumer twitterConsumer;
public TwitterUploadTask(OAuthConsumer consumer, File file, String string) {
this.image = file;
this.message = string;
this.twitterConsumer = consumer;
}
#Override
protected String doInBackground(String... params) {
String result = "";
HttpClient httpclient = GlobalValues.getHttpClient();
HttpPost request = new HttpPost("https://api.twitter.com/1.1/statuses/update_with_media.json");
ByteArrayInputStream bais = null;
try {
FileInputStream fis = new FileInputStream(image);
BufferedInputStream bis = new BufferedInputStream(fis, 8192);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
fis.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] myTwitterByteArray = baos.toByteArray();
bais = new ByteArrayInputStream(myTwitterByteArray);
} catch (IOException e) {
e.printStackTrace();
}
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("status", new StringBody(message));
entity.addPart("media[]", new InputStreamBody(bais, image.getName()));
request.setEntity(entity);
twitterConsumer.sign(request);
HttpResponse response = httpclient.execute(request, GlobalValues.getLocalContext());
HttpEntity httpentity = response.getEntity();
InputStream instream = httpentity.getContent();
result = GlobalValues.convertStreamToString(instream);
Log.i("statuses/update_with_media", result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
return result;
}
public void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result.trim());
System.out.println(jObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
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);
}
I used this code to post image to facebook. But there is no response from this code. please help me.
//I had created onCreate() method as :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebook = new Facebook(APP_ID);
restoreCredentials(facebook);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
postToWall();
}
//used this code for postToWall(): In this method I gave path of a image to post //and this method is calling in onCreate().
private void postToWall() {
FileInputStream fis = null;
try {
fis = new FileInputStream("/mnt/sdcard/Blue_Dock_by_dimage.jpg");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeStream(fis);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream); // where bm is bitmap from Sdcard
byte[] byteArray = stream.toByteArray();
Bundle param = new Bundle();
param = new Bundle();
param.putString("message", "All");
param.putString("filename", "TEst");
param.putByteArray("image", byteArray);
mAsyncRunner.request("me/photos", param, "POST", new fbRequestListener(), null);
}
//used this code for fbRequestListener() class:
public class fbRequestListener implements RequestListener {
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
Log.d("RESPONSE",""+response);
}
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
Log.d("RESPONSE",""+e);
showToast("Authentication with Facebook failed!");
finish();
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
Log.d("RESPONSE",""+e);
showToast("Authentication with onFileNotFoundException failed!");
finish();
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
showToast("Authentication with onMalformedURLException!");
finish();
}
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
Log.d("RESPONSE",""+e);
showToast("Authentication with onFacebookError failed!");
finish();
}
}
you have to use GRAPH API for this or HACKBOOK Example
this is easy way...
download code from here
check below code..
replace below code in that example.
public static void postToWall1(String message, Context con, String url,
String Product) {
facebook1 = new Facebook(APP_ID);
Bundle parameters = new Bundle();
parameters.putString("caption", Product);
parameters.putString("description", "Share photo!");
parameters.putString("picture", "" + url);
parameters.putString("message", "" + message);
try {
facebook1.request("me");
String response = facebook1.request("me/feed", parameters, "POST");
if (response != null
|| !response.equals("")
|| !response.equals("false")
)
showToast("Message posted to your facebook wall!", con);
}
} catch (Exception e) {
showToast("Failed to post to wall!", con);
e.printStackTrace();
}
}
Try this code:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
"https://graph.facebook.com/me/photos?access_token="+ acess_token);
URL url = new URL("image_url");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bi = BitmapFactory.decodeStream(input);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bi.compress(CompressFormat.PNG,100, bos);
byte[] data = bos.toByteArray();
entity.addPart("source",new ByteArrayBody(data,"testimage.png"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,localContext);
Log.v("response ", response+ "");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}