android facebook api post to wall with image - android

I would like to be able to use the facebook android sdk and post a link to facebook. An example of what I want would be is if you were on facebook and you type a link into your status part, like "http://www.google.com". When you do this a box pops up and your post ends up being a block that has an image and a link. I found documentation in the facebook api for this using an attatchment, though when I try to do this with the android facebook api it doesn't seem to work. I've looked for hours on the net, with no luck. Thanks.

Asuming when you read this that you know how to log onto facebook and such via the api...
private void fbImageSubmit(Facebook fb, String imageurl, String caption, String description, String name, String linkurl)
{
if(fb != null)
{
if(fb.isSessionValid())
{
Bundle b = new Bundle();
b.putString("picture", imageurl);
b.putString("caption",caption);
b.putString("description",description );
b.putString("name",name);
b.putString("link",linkurl);
try {
String strRet = "";
strRet = fb.request("/me/feed",b,"POST");
JSONObject json;
try {
json = Util.parseJson(strRet);
if(!json.isNull("id"))
{
Log.i("Facebook", "Image link submitted.");
}
else
{
Log.e("Facebook","Error: " + strRet);
}
} catch (FacebookError e) {
Log.e("Facebook","Error: " + e.getMessage());
}
} catch (Exception e) {
Log.e("Facebook", "Error: " + e.getMessage());
}
}
}
}

This works perfect fine with Progress Dialog box.. I have used it...
You must added the jar of Facebook...
Facebook authenticatedFacebook = new Facebook(APP_ID);
private static final String[] PERMISSIONS = new String[] { "publish_stream", "read_stream", "offline_access" };
Call below function on button Click....
authenticatedFacebook.authorize(YOUR_CLASS_NAME.this, PERMISSIONS, new FaceBookWallPostListener());
Now Add this class...
public class FaceBookWallPostListener implements DialogListener {
public void onComplete(Bundle values) {
new FacebookWallPost().execute();
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class FacebookWallPost extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
path = "Path OF YOUR IMAGE";
Bundle parameters = new Bundle();
parameters.putString("message", "MESSAGE YOU WANT TO POST");
try {
File file = new File(path, "IMAGE_NAME.jpg");
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
data = baos.toByteArray();
if (data != null) {
parameters.putByteArray("picture", data);
}
parameters.putString("access_token", authenticatedFacebook.getAccessToken());
authenticatedFacebook.request("me");
authenticatedFacebook.request("me/photos", parameters, "POST");
} catch (Exception e) {
return e.getMessage();
}
return "success";
} catch (Exception e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
if (result.equals("success")) {
Toast.makeText(YOUR_CLASS_NAME.this, "WallPost Successfully Done", Toast.LENGTH_SHORT).show();
try {
new File(Environment.getExternalStorageDirectory().toString() + "/Diegodeals", "diegodeals.jpg").delete();
} catch (Exception e) {
}
} else {
Toast.makeText(YOUR_CLASS_NAME.this, "Failed to post \n " + result, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(YOUR_CLASS_NAME.this);
pDialog.setMessage("Posting Picture & Message on Facebook...");
pDialog.show();
}
}
/////GOOOD LUCK.

Related

How to send a file to a REST service?

I want to get file in rest service from android. In my code i send filestream from android via url. If i use like this My entire app is not working by saying...
Logcat
Operation Fileacces in contract 'IREST' has a query variable named
stream of type System.IO.FileStream, but type
System.IO.FileStream is not convertible by QueryStringConverter.
Variables for UriTemplate query values must have types that can
be converted by QueryStringConverter
Here I have post my coding FYR
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri content_describer = data.getData();
String src = null;
try {
src = getFilePath(UploadActivity.this, content_describer);
} catch (URISyntaxException e) {
e.printStackTrace();
}
Log.d("src is: ", src);
source = new File(src);
fname = source.getName();
Button text = (Button) findViewById(R.id.txt);
text.setText(fname);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
FileOpen.openFile(UploadActivity.this, source);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Onclick event in action bar icon:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.mybutton) {
new Save().execute();
return true;
}
return super.onOptionsItemSelected(item);
}
SAVE function asynctask
private class Save extends AsyncTask<String,Void,String> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
fis=new FileInputStream(source);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ServiceHandler jsonParser = new ServiceHandler();
String fileaccess = ip+"Mobile/rest.svc/Fileacces?stream="+fis+"&filename="+fname;
Log.d("Fileaccess","fileaccess"+fileaccess);
String result = jsonParser.makeServiceCall(fileaccess, ServiceHandler.GET);
Log.i("fileaccess", "result: > " + result);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
System.out.println(s);
}
}
My rest function in vb.net
Public Function fileacces(ByVal stream As FileStream, ByVal filename As String) As String Implements IREST.fileacces
Dim result = ""
Try
Dim path = "D:\XXX\YYY\ECM Source\Archive\EZECM\Settings\Monitor\" + filename
Dim fileStream = New FileStream(path, FileMode.Create, FileAccess.Write)
stream.CopyTo(fileStream)
fileStream.Dispose()
result = "file uploaded"
Catch ex As Exception
End Try
Return result
End Function
kindly use base 64
like this
public void uploadFile(final String selectedFilePath) {
try {
FileInputStream inputStream = new FileInputStream(selectedFilePath);
byte[] byteArray = IOUtils.toByteArray(inputStream);
final String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// tvFileName.setText(encoded);
Log.e("File Base 64",encoded);
filebas64=encoded;
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("Error",e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("Error",e.toString());
}
}

Paytm Sdk Version 2 - Paytm integration in Android App throwing OOPS error in doInBackground

I am integrating Paytm SDK in my Android Application. I have to POST ORDER ID and callbackurl along with other paytm credentials. All values are passing correctly. But OOPS error is displaying.
Code
public class Paytmgateway extends Activity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchantapp);
context = this;
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
// This is to refresh the order id: Only for the Sample App’s purpose.
#Override
protected void onStart() {
super.onStart();
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
public void onStartTransaction(View view) throws InterruptedException, ExecutionException {
String myorder = "ORDER7999883";
String mycallback= "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID="+myorder;
PostAsync postAsync= new PostAsync();
postAsync.execute(myorder,mycallback);
}
class PostAsync extends AsyncTask<String, String, JSONObject> {
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String LOGIN_URL = "http://192.168.1.4/paytmtest/generateChecksum.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> para = new HashMap<>();
para.put("myorder", args[0]);
para.put("mycallback", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", para);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
PaytmPGService Service = PaytmPGService.getProductionService();
if (json != null) {
Toast.makeText(Paytmgateway.this,"Server Response"+json.toString(), Toast.LENGTH_LONG).show();
String finalresult=json.toString();
try {
JSONObject mJsonObject=new JSONObject(finalresult);
Map paramMap = new HashMap();
System.out.println("Hi");
paramMap.put("MID", mJsonObject.getString("MID"));
System.out.println(mJsonObject.getString("MID"));
// paramMap.put(“ORDER_ID”, order_id);
paramMap.put("ORDER_ID", mJsonObject.getString("ORDER_ID"));
System.out.println(mJsonObject.getString("ORDER_ID"));
// paramMap.put(“CUST_ID”, cust_id);
paramMap.put("CUST_ID",mJsonObject.getString("CUST_ID"));
System.out.println(mJsonObject.getString("CUST_ID"));
// paramMap.put(“INDUSTRY_TYPE_ID”,industry_type);
paramMap.put("INDUSTRY_TYPE_ID",mJsonObject.getString("INDUSTRY_TYPE_ID"));
System.out.println(mJsonObject.getString("INDUSTRY_TYPE_ID"));
// paramMap.put(“CHANNEL_ID”, “WAP”);
paramMap.put("CHANNEL_ID", mJsonObject.getString("CHANNEL_ID"));
System.out.println(mJsonObject.getString("CHANNEL_ID"));
// paramMap.put(“TXN_AMOUNT”,txn_amount);
paramMap.put("TXN_AMOUNT", "1");
System.out.println(mJsonObject.getString("TXN_AMOUNT"));
// paramMap.put(“WEBSITE”, “APP_STAGING”);
paramMap.put("WEBSITE" , mJsonObject.getString("WEBSITE"));
System.out.println(mJsonObject.getString("WEBSITE"));
// paramMap.put(“CALLBACK_URL”,callback);
paramMap.put("CALLBACK_URL" , mJsonObject.getString("CALLBACK_URL"));
System.out.println(mJsonObject.getString("CALLBACK_URL"));
// paramMap.put(“CHECKSUMHASH”,checksum);
paramMap.put("CHECKSUMHASH",mJsonObject.getString("CHECKSUMHASH"));
System.out.println("MYCHECK"+mJsonObject.getString("CHECKSUMHASH"));
PaytmOrder Order = new PaytmOrder(paramMap);
System.out.println("sumithra"+paramMap);
Service.initialize(Order, null);
Service.startPaymentTransaction(Paytmgateway.this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
Toast.makeText(getApplicationContext(),"UI Error" , Toast.LENGTH_LONG).show();
}
#Override
public void onTransactionResponse(Bundle inResponse) {
// Log.d(“LOG”, “Payment Transaction : ” + inResponse);
Log.d("LOG", "Payment Transaction : "+inResponse);
Toast.makeText(getApplicationContext(),"Payment Transaction Response" + inResponse.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void networkNotAvailable() {
Toast.makeText(getApplicationContext(),"No Network Available" , Toast.LENGTH_LONG).show();
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
Toast.makeText(getApplicationContext(),"Client Authentication Failed" , Toast.LENGTH_LONG).show();
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
Toast.makeText(getApplicationContext(),"Error Loading Webpage" , Toast.LENGTH_LONG).show();
}
// had to be added: NOTE
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
#Override
public void onTransactionCancel(String inErrorMessage,
Bundle inResponse) {
Log.d("LOG", "Payment Transaction Failed" + inErrorMessage);
Toast.makeText(getBaseContext(),"Payment Transaction Failed", Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
My Android Studio Monitor output of
System.out.println(paramMap);
is
05-22 15:43:33.801 15328-15328/com.example.merchantapp I/System.out: {MID=Bigfix12826731009600, CALLBACK_URL=https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=ORDER7999883, TXN_AMOUNT=1.00, ORDER_ID=ORDER7999883, WEBSITE=BigfixGadgetWAP, INDUSTRY_TYPE_ID=Retail109, CHECKSUMHASH=HxSimAQAYRsDhJ7XX6JXT+cilxFNdSc4Pb3jr5AE5dddSavv6UD3DJffBHtcHVwQbBMYYHc850/OdZretSWIeo3m/uC0/FUA9wpO1Hgs/jY=, CHANNEL_ID=WAP, CUST_ID=25654}
Which means the two parameter values are posting successfully and i can be able to GET them also. But the following error is displaying
enter image description here
But if if i use the below code , It is working successfully
public class Paytm extends Activity {
String callback,website;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchantapp);
context = this;
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
// This is to refresh the order id: Only for the Sample App’s purpose.
#Override
protected void onStart() {
super.onStart();
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
public void onStartTransaction(View view) throws InterruptedException, ExecutionException {
PaytmPGService Service = PaytmPGService.getProductionService();
Map paramMap = new HashMap();
String mid="",order_id="",cust_id="",industry_type="",txn_amount="",checksum="";
Log.d("before request", "some");
JSONObject mJsonObject = null;
// String url="http://paytmtest.azurewebsites.net/APP/generateChecksum.php";
String url="http://192.168.1.4/paytmtest/generateChecksum.php";
MyAsyncTask myAsyncTask=new MyAsyncTask();
// String json = myAsyncTask.execute(url).get();
String json = (String) myAsyncTask.execute(url).get();
try {
mJsonObject=new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
try {
//mid = mJsonObject.getString("MID");
mid="Bigfix12826731009600";
// order_id=mJsonObject.getString(“ORDER_ID”);
order_id=mJsonObject.getString("ORDER_ID");
// cust_id = mJsonObject.getString(“CUST_ID”);
cust_id=mJsonObject.getString("CUST_ID");
//callback = mJsonObject.getString("CALLBACK_URL");
callback= "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID="+order_id;
//website = mJsonObject.getString("WEBSITE");
website="BigfixGadgetWAP";
//industry_type = mJsonObject.getString("INDUSTRY_TYPE_ID");
industry_type="Retail109";
txn_amount = mJsonObject .getString("TXN_AMOUNT");
// checksum = mJsonObject.getString(“CHECKSUMHASH”);
checksum = mJsonObject.getString("CHECKSUMHASH");
} catch (JSONException e) {
e.printStackTrace();
}
// Log.d(“after request”, “some”);
Log.d("after request", "some");
// paramMap.put(“MID”, mid);
paramMap.put("MID", mid);
// paramMap.put(“ORDER_ID”, order_id);
paramMap.put("ORDER_ID", order_id);
// paramMap.put(“CUST_ID”, cust_id);
paramMap.put("CUST_ID",cust_id);
// paramMap.put(“INDUSTRY_TYPE_ID”,industry_type);
paramMap.put("INDUSTRY_TYPE_ID",industry_type);
// paramMap.put(“CHANNEL_ID”, “WAP”);
paramMap.put("CHANNEL_ID", "WAP");
// paramMap.put(“TXN_AMOUNT”,txn_amount);
paramMap.put("TXN_AMOUNT", txn_amount);
// paramMap.put(“WEBSITE”, “APP_STAGING”);
paramMap.put("WEBSITE" , website);
// paramMap.put(“CALLBACK_URL”,callback);
paramMap.put("CALLBACK_URL" , callback);
// paramMap.put(“CHECKSUMHASH”,checksum);
paramMap.put("CHECKSUMHASH",checksum);
System.out.println("sumithra"+paramMap);
PaytmOrder Order = new PaytmOrder(paramMap);
Service.initialize(Order, null);
Service.startPaymentTransaction(this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
}
#Override
public void onTransactionResponse(Bundle inResponse) {
// Log.d(“LOG”, “Payment Transaction : ” + inResponse);
Log.d("LOG", "Payment Transaction : "+inResponse);
Toast.makeText(getApplicationContext(),"Payment Transaction Response" + inResponse.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void networkNotAvailable() {
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
}
// had to be added: NOTE
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
#Override
public void onTransactionCancel(String inErrorMessage,
Bundle inResponse) {
Log.d("LOG", "Payment Transaction Failed" + inErrorMessage);
Toast.makeText(getBaseContext(),"Payment Transaction Failed", Toast.LENGTH_LONG).show();
}
});
}
class MyAsyncTask extends AsyncTask {
#Override
protected String doInBackground(Object[] params) {
URL url = null;
try {
url = new URL((String) params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection httpConn = null;
try {
httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream is = httpConn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
} catch (Exception e) {
}
Log.d("Response", result);
}
}
}
[enter image description here][2]
I just used the second code to test the trasaction. But i have to use the first posted code because i have to post the ORDERID and CALLBACKURL from android application to server . Any help would be appreciable.
**Here is the solution for all :**
Be sure to send equal number of parameters to your server (For checksum generator) And then to paytm server for payment.
**For example:**
If you are sending 6 params for checksum generator, then send these 6 same parameters including Checksum to Paytm...
It will resolve your problem.
**CODE EXAMPLE :**
**Generate checksum.php**
$paramList = array();
$paramList["MID"] = 'Provided by Paytm'; //Provided by Paytm
$paramList["ORDER_ID"] = 'hIquwhzvzTG7gvT'; //unique OrderId for every request
$paramList["CUST_ID"] = 'CUST0001453'; // unique customer identifier
$paramList["INDUSTRY_TYPE_ID"] = 'Retail'; //Provided by Paytm
$paramList["CHANNEL_ID"] = 'WAP'; //Provided by Paytm
$paramList["TXN_AMOUNT"] = '10.00'; // transaction amount
$paramList["WEBSITE"] = 'APP_STAGING';//Provided by Paytm
$paramList["CALLBACK_URL"] = 'https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp';
**Android Activity.java**
paramMap.put("MID" , "#########");
paramMap.put( "ORDER_ID" , "hIquwhzvzTG7gvT");
paramMap.put( "CUST_ID" , "CUST0001453");
paramMap.put( "CHANNEL_ID" , "WAP");
paramMap.put( "TXN_AMOUNT" , "10.00");
paramMap.put( "WEBSITE" , "APP_STAGING");
paramMap.put( "CALLBACK_URL" , "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp");
paramMap.put( "CHECKSUMHASH" , "dR5OtEkuNkgamHTZDCHmF+CF3j9RdG1520mlHEb85oSZP1CaxVUsRY2sYric90HLm/vElaPZKoQ7b5/SyFpi3oBWXf2BQNy+r6iiBwg4AH4=");
paramMap.put("INDUSTRY_TYPE_ID" , "Retail");
**NOTE : Please keep in mind to send paytm server exact parameters plus one checksum.....**

how share image on face book in android

Here is the code from which i am able to share data as text format on Share i want share image.
Suppose i have image on sd card please help me how i will share image on face book.
How can i do this ?
Here is my Code :
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String title = "This is facebook Data";
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://m.facebook.com/sharer.php?u="
+ "www.facebook.com" + "&t=" + title + "&_rdr"));
startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
});
try this please:
private void fbImageSubmit(Facebook fb, String imageurl, String caption, String description, String name, String linkurl)
{
if(fb != null)
{
if(fb.isSessionValid())
{
Bundle b = new Bundle();
b.putString("picture", imageurl);
b.putString("caption",caption);
b.putString("description",description );
b.putString("name",name);
b.putString("link",linkurl);
try {
String strRet = "";
strRet = fb.request("/me/feed",b,"POST");
JSONObject json;
try {
json = Util.parseJson(strRet);
if(!json.isNull("id"))
{
Log.i("Facebook", "Image link submitted.");
}
else
{
Log.e("Facebook","Error: " + strRet);
}
} catch (FacebookError e) {
Log.e("Facebook","Error: " + e.getMessage());
}
} catch (Exception e) {
Log.e("Facebook", "Error: " + e.getMessage());
}
}
}
}
Try this..
facebook.authorize(FbdemoActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
#Override
public void onComplete(Bundle values) {
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
public void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile("/sdcard/viewitems.png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, facebook.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: (executed in background thread)
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
// then post the processed result back to the UI thread
// if we do not do this, an runtime exception will be generated
// e.g. "CalledFromWrongThreadException: Only the original
// thread that created a view hierarchy can touch its views."
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
And go throuh these Link also:
The easiest way for you is to use the existing SDK, something like that:
http://github.com/facebook/facebook-android-sdk/
http://code.google.com/p/fbconnect-android/
http://wiki.developers.facebook.com/index.php/User:Android
The more flexible way is to implement the API yourself, here are the docs that will be useful:
http://developers.facebook.com/docs/

Post Only text message on facebook from android application

sorry for the duplicate question may be but i am really faced problem with Facebook in android application , i want post only message on Facebook wall , i am able to post image with text but i want to post only text please tell me where i am wrong here is my code
This is working code for Image +Text
public void postImageonWall() {
Log.i("Alok", "Test");
Bundle params = new Bundle();
// Inflate Edit text for Facebook Message
params.putString("method", "photos.upload");
params.putString("app_id", mAPP_ID); // I've tried with/without this,
// same result
String message1 = "Test here ";
params.putString("message", message1);
// int r = jj - 1;
//
// Bitmap b = BitmapFactory.decodeFile("/sdcard/D&P post/postimage" + r
// + ".jpg");
// Get image from drawable
Bitmap b = BitmapFactory
.decodeResource(getResources(), R.drawable.test);
Log.i("Bitmap Image is here", "Bitmap" + b);
if (b != null) {
Log.i("Bitmap", "value");
} else {
Log.i("Bitmap", "null");
}
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
if (data != null) {
params.putByteArray("picture", data);
Log.i("final", "value" + message);
params.putString("caption", message);
Log.e("PHOTOUPLOAD", "Attemping an upload...");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST",
new SampleUploadListener(), null);
Log.e("PHOTOUPLOAD", "Attemping an upload...");
}
}
Here is Simple click listner :-
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
public void onComplete(String response) {
// TODO Auto-generated method stub
}
public void onIOException(IOException e) {
// TODO Auto-generated method stub
}
public void onFileNotFoundException(FileNotFoundException e) {
// TODO Auto-generated method stub
}
public void onMalformedURLException(MalformedURLException e) {
// TODO Auto-generated method stub
}
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
}
please some one tell me where i made change according to requirement .
Try something like the following.It worked for all my projects,
private void postToFacebook(String review) {
mProgress.setMessage("Posting ...");
mProgress.show();
AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);
Bundle params = new Bundle();
params.putString("name", title);
params.putString("link", link);
mAsyncFbRunner.request("me/feed", params, "POST",
new WallPostListener());
}
private Handler mRunOnUi = new Handler();
private final class WallPostListener extends BaseRequestListener {
public void onComplete(final String response) {
mRunOnUi.post(new Runnable() {
public void run() {
mProgress.cancel();
Toast.makeText(SVG_View.this,
"Posted to Facebook", Toast.LENGTH_SHORT).show();
}
});
}
}
Try this Method
public void postToWall(String message) {
Bundle params = new Bundle();
params.putString("message", message);
// Uses the Facebook Graph API
try {
facebook.request("/me/feed", params, "POST");
this.finish();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

android: I am implement photo post on wall for facebook.when run in Emulator it works fine but not work in device?

I am implement photo post on wall for facebook.when run in Emulator it works fine but not work in device?
Its show on device ERROR: Invalid android_key parameter.The key 3x3UBQp16... does not match any allowed key.Configure your app Key hashes at http://developers.facebook.com/apps/47775390...
I am try to another device but it not work.
Here is my code...
// Facebook
'
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 32665:
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
public void onComplete(Bundle values) {
}
public void onFacebookError(FacebookError e) {
}
public void onError(DialogError e) {
}
public void onCancel() {
}
public class StartFBupdateStatus extends AsyncTask<Void, Void, String> {
private String mFacebookToken;
public StartFBupdateStatus(String mFacebookToken) {
this.mFacebookToken = mFacebookToken;
}
#Override
protected void onPreExecute() {
// super.onPreExecute();
pDialog = ProgressDialog.show(getParent(), "Please wait...",
"Photo Uploading on Wall", true, true,
new OnCancelListener() {
public void onCancel(DialogInterface pd) {
try {
pDialog.dismiss();
pDialog = null;
taskFBupdateStatus.cancel(true);
} catch (Exception e) {
Log.e("Exception Cought in onCancel:- ",
e.toString());
}
}
});
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(Void... params) {
String response = null;
try {
Bundle bundle = new Bundle();
bundle.putString(Facebook.TOKEN, this.mFacebookToken);
// String url = "https://graph.facebook.com/me/photos";
// String url = "https://graph.facebook.com/me/";
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inSampleSize = 1;
// ByteArrayOutputStream baos = new ByteArrayOutputStream(
// 32 * 1024);
if (pDetails.image_path != null) {
// byte[] data = null;
// Bitmap bmImg;
// URL myFileUrl = null;
try {
// myFileUrl = new URL(product.image);
// HttpURLConnection conn = (HttpURLConnection)
// myFileUrl
// .openConnection();
// conn.setDoInput(true);
// conn.connect();
// InputStream is = conn.getInputStream();
//
// bmImg = BitmapFactory.decodeStream(is);
//
// bmImg.compress(Bitmap.CompressFormat.PNG, 100, baos);
// data = baos.toByteArray();
// Log.v("SATERRA-FACEBOOK",
// "IMAGE Byte ARRAY SIZE::"+data.length);
bundle.putString("name", product.title);
bundle.putString("picture", pDetails.image_path);
// bundle.putString("message", "icon please");
// bundle.putString("link", "http://www.saterra.com");
// bundle.putString("description",
// product.short_description);
response = facebook.request("me/feed", bundle, "POST");
Log.d("UPDATE RESPONSE", "" + response);
} catch (Exception e) {
e.printStackTrace();
}
} else {
}
// ********* Over Changes *********
// try {
// baos.close();
// } catch (IOException e1) {
// Log.d("baos error", e1.toString());
// }
if (connMgr.getActiveNetworkInfo() != null
&& connMgr.getActiveNetworkInfo().isAvailable()
&& connMgr.getActiveNetworkInfo().isConnected()) {
try {
// response = Util.openUrl(url, "POST", bundle);
JSONObject json = Util.parseJson(response);
Log.e("Response Photo String", " " + response);
handler.post(new Runnable() {
public void run() {
Toast.makeText(getParent(),
"Photo Uploaded...", Toast.LENGTH_LONG)
.show();
}
});
} catch (Exception e) {
Log.d("Some problem Please try again", e.toString());
}
} else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(getParent(),
"InternetConnectionNotAvailable",
Toast.LENGTH_LONG).show();
}
});
}
} catch (Exception e) {
// Log.e("ProductsDetailActivity",e.getMessage());
Log.e("ProductsDetailActivity", e.toString());
response = null;
}
// String s = facebook.getAccessToken()+"\n";
// s += String.valueOf(facebook.getAccessExpires())+"\n";
// s += "Now:"+String.valueOf(System.currentTimeMillis())+"\n";
return response;
}
#Override
protected void onPostExecute(String result) {
if (result == null) {
Toast toast = Toast.makeText(getParent(), "Facebook Error...",
Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
} else if (result.indexOf("Duplicate status message") > -1) {
Toast toast = Toast.makeText(getParent(),
"You already said that..", Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
} else if (result.indexOf("OAuthException") > -1) {
Toast toast = Toast.makeText(getParent(), "Facebook Error...",
Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
} else {
Toast toast = Toast.makeText(getParent(),
"Facebook update sent", Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
}
pDialog.dismiss();
}
}
private void fbAuthAndPost() {
facebook.authorize(getParent(), new String[] { "publish_stream" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {
Log.d(this.getClass().getName(),
"Facebook.authorize Complete: ");
saveFBToken(facebook.getAccessToken(),
facebook.getAccessExpires());
mFacebookToken = facebook.getAccessToken();
// updateStatus(values.getString(Facebook.TOKEN),
// message);
StartFBupdateStatus taskFBupdateStatus = new StartFBupdateStatus(
mFacebookToken);
taskFBupdateStatus.execute();
}
#Override
public void onFacebookError(FacebookError error) {
Log.d(this.getClass().getName(),
"Facebook.authorize Error: " + error.toString());
}
#Override
public void onError(DialogError e) {
Log.d(this.getClass().getName(),
"Facebook.authorize DialogError: "
+ e.toString());
}
#Override
public void onCancel() {
Log.d(this.getClass().getName(),
"Facebook authorization canceled");
}
});
}
private void saveFBToken(String token, long tokenExpires) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
prefs.edit().putString("FacebookToken", token).commit();
}

Categories

Resources