How to post a image instead of message to facebook? - android

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();
}

Related

Android high memory usage when uploading a bitmap to server (100MB)

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);

Why does my json result only shows one record in textview?

I am new to android and stuck with the following problem. This is my async task and I want to show result in next activity. I am getting the whole result in the console but in textview, it only shows the last name.
private class MyTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
String link = "http://www.amtechnologies.org/emergency/get_medicine.php";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(link));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("disease_name", result2));
System.out.println("Result2:"+result2);
UrlEncodedFormEntity form = new UrlEncodedFormEntity(postParameters);
request.setEntity(form);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String result=EntityUtils.toString(entity);
result1 = result;
System.out.println("Result: "+result);
System.out.println("Result1: "+result1);
Intent i= new Intent(Medicines.this,View_medicines.class);
i.putExtra("result", result.toString());
startActivity(i);
}catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Next activty :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_medicines);
mnm=(EditText) findViewById(R.id.m3);
mi=(TextView) findViewById(R.id.m2);
nextbtn=(Button) findViewById(R.id.okmedi);
nextbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(View_medicines.this,Homepage.class);
startActivity(myIntent);
finish();
}
});
try {
Intent intent = getIntent();
String jsonArray=intent.getStringExtra("result");
jArray = new JSONArray(jsonArray);
System.out.println("Universe Acitivy Json Array: "+jArray);
for(int i=0;i<jArray.length();i++){
String names=new JSONObject(jArray.getString(i)).get("medicine_name").toString();
System.out.println(names+"");
mnm.setText(names);
mi.setText(""+new JSONObject(jArray.getString(i)).get("medicine_intake"));
Toast.makeText(getApplicationContext(),""+new JSONObject(jArray.getString(i)).get("medicine_name").toString(), Toast.LENGTH_SHORT).show();
}
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Change this part
for(int i=0;i<jArray.length();i++){
String names=new JSONObject(jArray.getString(i)).get("medicine_name").toString();
System.out.println(names+"");
mnm.setText(names);
mi.setText(""+new JSONObject(jArray.getString(i)).get("medicine_intake"));
Toast.makeText(getApplicationContext(),""+new JSONObject(jArray.getString(i)).get("medicine_name").toString(), Toast.LENGTH_SHORT).show();
}
to following
for(int i=0;i<jArray.length();i++){
String names=new JSONObject(jArray.getString(i)).get("medicine_name").toString();
System.out.println(names+"");
mnm.append(names);
mi.append(""+new JSONObject(jArray.getString(i)).get("medicine_intake"));
Toast.makeText(getApplicationContext(),""+new JSONObject(jArray.getString(i)).get("medicine_name").toString(), Toast.LENGTH_SHORT).show();
}

Images inside gridView takes long time in loading as well as it disappear on scroll of GridView

When i am scrolling the GridView the images disappear in it. In log Cat its also showing outofmemory i dont know what i am doing wrong here.! It takes long time to display the images also. Thanks in Advance.
BaseActivity.java
public class BaseActivity extends Activity{
private Context context = this;
boolean server_connection = false;
static final Comparator<HashMap<String, String>> byDate = new Comparator<HashMap<String, String>>() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public int compare(HashMap<String, String> ord1, HashMap<String, String> ord2) {
Date d1 = null;
Date d2 = null;
try {
if(ord1.get("datetime")!=null){
d1 = sdf.parse(ord1.get("datetime"));
}
else{
d1 = sdf.parse("1970-01-01 00:00:00");
}
if(ord2.get("datetime")!=null){
d2 = sdf.parse(ord2.get("datetime"));
}
else{
d2 = sdf.parse("1970-01-01 00:00:00");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.d("Date", ""+d1+"..........."+d2);
return (d1.getTime() > d2.getTime() ? -1 : 1); //descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<HashMap<String, String>> byCount = new Comparator<HashMap<String, String>>() {
public int compare(HashMap<String, String> ord1, HashMap<String, String> ord2) {
int c1,c2;
if(ord1.get("download_count")!=null && !ord1.get("download_count").equals("null")){
c1=Integer.parseInt(ord1.get("download_count"));
}
else{c1=0;}
if(ord2.get("download_count")!=null && !ord2.get("download_count").equals("null")){
c2=Integer.parseInt(ord2.get("download_count"));
}
else{c2=0;}
return (c1>c2 ? -1 : 1); //descending
}
};
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public String prepareWebserviceRequest(String methodname, String[] keys, String[] values) throws JSONException{
String retStr = null;
String strParams = null;
JSONObject json = new JSONObject();
for(int i=0;i<keys.length;i++){
json.put(keys[i],values[i]);
}
JSONObject fJson = new JSONObject();
fJson.put("method_name", methodname);
fJson.put("body", json);
retStr = fJson.toString();
return retStr;
}
public String prepareWebserviceRequestOnlyMethod(String methodname) throws JSONException{
String retStr = null;
String strParams = null;
JSONObject json = new JSONObject();
JSONObject fJson = new JSONObject();
fJson.put("method_name", methodname);
// fJson.put("body", json);
retStr = fJson.toString();
return retStr;
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
class Download extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bmp=null;
bmp = getBitmapFromURL(params[0]);
return bmp;
}
}
public void WriteFile(String path,String filename,String data) {
try{
File direct = new File(path);
if(!direct.exists())
{
direct.mkdir();//directory is created;
}
String fpath= path +filename;
File txtfile=new File(fpath);
txtfile.createNewFile();
FileOutputStream fout=new FileOutputStream(txtfile);
OutputStreamWriter myoutwriter=new OutputStreamWriter(fout);
myoutwriter.write(data);
myoutwriter.close();
fout.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public String ReadFile(String path,String filename)
{ File myFile = new File(path + filename);
if(!myFile.exists())
{
return null;
}
FileInputStream fIn = null;
try {
fIn = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
try {
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return aBuffer;
}
public boolean FileExist(String filename)
{
String PATH2 = Environment.getExternalStorageDirectory() + "/"+Constant.Alert_Name+filename;
Log.v("log_tag initial path", "PATH: " + PATH2);
File file2 = new File(PATH2);
if(file2.exists()==true)
{
return true;
}
return false;
}
public String callAPI(String strRequest) {
String result = null;
String new_params;
int ResponseCode;
// TODO Auto-generated method stub
try {
JSONObject json = new JSONObject();
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache-HttpClient/Android");
//httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
httpParams.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
HttpClient client = new DefaultHttpClient(cm,httpParams);
String url = Constant.WebService_URL;
//String url = "http://192.168.1.3/messages_app/main.php";
URL url1 = new URL(Constant.WebService_URL);
// URL url1 = new URL("http://192.168.1.3/messages_app/main.php");
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
new_params =strRequest;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("json","{\"method_name\":\"get_all_category\"}"));
nameValuePairs.add(new BasicNameValuePair("json",new_params));
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
ResponseCode = response.getStatusLine().getStatusCode();
//Log.d("ResponseCode", ""+ResponseCode);
if(ResponseCode==200){
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
result = RestClient.convertStreamToString(instream);
// Log.i("Read from server", result);
}
}
else if(ResponseCode!=200){
return "Server down";
}
} catch (Throwable t) {
return null;
}
return result;
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private String data[];
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
DisplayImageOptions options;
ArrayList<HashMap<String, String>> list;
public LazyAdapter(Activity a,ArrayList<HashMap<String, String>> list) {
this.list=list;
activity = a;
inflater = (LayoutInflater)LayoutInflater.from(a);
File cacheDir = StorageUtils.getOwnCacheDirectory(a, "Download");
// Get singletone instance of ImageLoader
imageLoader = ImageLoader.getInstance();
// Create configuration for ImageLoader (all options are optional)
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
// You can pass your own memory cache implementation
.memoryCacheExtraOptions(480,800)
.denyCacheImageMultipleSizesInMemory()
.discCacheExtraOptions(480, 480, CompressFormat.PNG, 100)
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.enableLogging()
.build();
// Initialize ImageLoader with created configuration. Do it once.
imageLoader.init(config);
//imageLoader.init(ImageLoaderConfiguration.createDefault(a));
// imageLoader=new ImageLoader(activity.getApplicationContext());
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.cacheInMemory()
// .cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(20))
.build();
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if(convertView==null)
{
vh = new ViewHolder();
convertView= inflater.inflate(R.layout.other, parent,false);
vh.iv=(ImageView)convertView.findViewById(R.id.picture);
vh.pb= (ProgressBar)convertView.findViewById(R.id.pb);
vh.tv = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
// vh.tv.setText("Image in postion ="+position);
if(Global.getCurrent_tab()==1){
vh.tv.setText(""+list.get(position).get("download_count"));
}
display(vh.iv, Constant.img_URL+list.get(position).get("photo_name"), vh.pb);
return convertView;
}
public void display(ImageView img, String url, final ProgressBar pb)
{
imageLoader.displayImage(url, img, options, new ImageLoadingListener() {
#Override
public void onLoadingCancelled() {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(Bitmap arg0) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(FailReason arg0) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
}
#Override
public void onLoadingStarted() {
// TODO Auto-generated method stub
pb.setVisibility(View.VISIBLE);
}
});
}
static class ViewHolder
{
ImageView iv;
TextView tv;
ProgressBar pb;
}
}
DefaultGridView.java
public class DefaultGridView extends Activity {
GridView gridView;
Context context=this;
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.latestphotos);
gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new LazyAdapter(DefaultGridView.this,Global.getPhotos_list()));
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
String url =Constant.img_URL+Global.getPhotos_list().get(position).get("photo_name");
Intent i = new Intent(DefaultGridView.this, FullImageActivity.class);
i.putExtra("idkey", url); // pass the id
startActivity(i);
}
});
}
}
FullImageActivity.java
public class FullImageActivity extends Activity {
Button download, setaswallpaper, reportissue;
String url1;
Bitmap myBitmap;
ImageDownloader mDownloader;
FileOutputStream fos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
setaswallpaper = (Button) findViewById(R.id.setaswallpaper);
download = (Button)findViewById(R.id.download);
reportissue = (Button)findViewById(R.id.reportissue);
final ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
url1 = getIntent().getStringExtra("idkey"); //get id
Log.i(".............",""+url1);
//imageView.setImageResource(id);
new Thread( new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
URL url = new URL(url1.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
}
catch(Exception e)
{
e.printStackTrace();
}
runOnUiThread( new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
imageView.setImageBitmap(myBitmap);
}
});
}
}).start();
setaswallpaper.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(myBitmap);
Toast.makeText(getApplicationContext(), "Wallpaper has been set...!!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
download.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
saveImageToSD();
// Toast.makeText(getApplicationContext(), "Wallpaper has been Downloaded...!!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
reportissue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Report Issue");
intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
intent.setData(Uri.parse("mailto:reportissue#gmail.com")); // or just "mailto:" for blank
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(intent);
}
});
}
private void saveImageToSD() {
/*--- this method will save your downloaded image to SD card ---*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
long current = System.currentTimeMillis();
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + (current / 1000) + "wallpaper.jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}

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);
}

Upload photo to FB from Android : No Error but no file uploaded to facebook

Here is the code for uploading picture into my facebook :
Bundle parameters = new Bundle();
parameters.putString("message", msg);
byte[] imgData = getImage("http://bandungraos.in/wp-content/resto/1/gallery/kepiting1.jpg");
parameters.putByteArray("picture", imgData);
if (imgData != null) {
try {
String response = facebook.request("me/photos", parameters,"POST");
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
}
.....
private byte[] getImage(String url) {
try {
URL imgUrl = new URL(url);
HttpURLConnection cn = (HttpURLConnection) imgUrl.openConnection();
cn.setDoInput(true);
cn.connect();
int length = cn.getContentLength();
byte[] imgData = new byte[length];
InputStream is = cn.getInputStream();
is.read(imgData);
return imgData;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I checked that either access token or imgData is not null
There is no error but I can't find the image in my facebook.
Thanks in advance
According to the User object documentation about the Photos connection the image parameter is named "source" and not "picture", have you tried:
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putByteArray("source", getImage("..."));
I had the same problem and i used this code `
private void upload_FB(Bitmap photo2) {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
String name = c.getTime().toString();
AsyncFacebookRunner fruner = new AsyncFacebookRunner(facebook);
Log.d("adr", mCurrentPhotoPath);
if(photo2!=null && mCurrentPhotoPath!=null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo2.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bMapArray = baos.toByteArray();
Bundle params = new Bundle();
params.putByteArray("photo",bMapArray);
params.putString("caption", name);
fruner.request("me/photos",params,"POST",new PhotoUploadListener(),null);
}else
Toast.makeText(ctx, "ERROR", Toast.LENGTH_LONG).show();
}
don't forget to add premision photo_upload
`

Categories

Resources