how to fetch image and display in image view from facebook - android

loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
Bitmap bitmap1 = getFacebookProfilePicture(user.getId());
imgview.setImageBitmap(bitmap1);
} else {
userName.setText("You are not logged");
}
}
});
public Bitmap getFacebookProfilePicture(String userID) {
try {
URL imageURL = new URL("https://graph.facebook.com/" + userID
+ "/picture?type=large");
bitmap = BitmapFactory.decodeStream(imageURL.openConnection()
.getInputStream());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
This is my code i am trying to get Profile pic from Facebook and display it on image-view in my app i am able to get name from Facebook but when i put code for get Profile pic then i am unable to get image in android please tell me where am doing wrong give me solution how to set this code .

Use this method to get Bitmap from Url.
/**
* Download image from server url and return bitmap
*
* #param stringUrl Imaage download url
* #return Bitmap receieved from server
*/
private Bitmap downloadImage(String stringUrl) {
URL url;
Bitmap bm = null;
try {
url = new URL(stringUrl);
URLConnection ucon = url.openConnection();
InputStream is;
if (ucon instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection) ucon;
int statusCode = httpConn.getResponseCode();
if (statusCode == 200) {
is = httpConn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
BufferedInputStream bis = new BufferedInputStream(is, 8192);
ByteArrayBuffer baf = new ByteArrayBuffer(1024);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
byte[] rawImage = baf.toByteArray();
bm = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
bis.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return bm;
}
Pass Facebook Profile pic url to this method like this and set downloaded bitmap to imageview.
URL imageURL = new URL("https://graph.facebook.com/" + userID
+ "/picture?type=large");
imgview.setImageBitmap(downloadImage(imageURL));
I hope it helps!

Use callbacks, they are much easier.
Create a callback as follows;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
if(jsonObject != null){
try {
String name = jsonObject.getString("name");
String email = jsonObject.getString("email");
String id = jsonObject.getString("id");
saveCurrentProfileInfo(id, name, email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, email, name");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
createSnackBar("Facebook login cancelled");
}
#Override
public void onError(FacebookException e) {
createSnackBar("Error logging in to Facebook");
}
};
Then on your oncreate method, initialize a CallbackManager
CallbackManager callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, callback);
You can then use the id retrieved to get the profile picture like you did.

Assuming you got the right access tokens, The updated API shows picture field in JSON like this:
{
"id": "8169595750129122",
"name": "A user name",
"picture": {
"data": {
"is_silhouette": false,
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xtp1/v/t1.0-1/p50x50/11150668_881451758563505_2749775492727269008_n.jpg?oh=35239d96bf3a6d34bd455c51218412d9&oe=56487861&__gda__=1446869670_cd2511b71fc9b8809d6b52bdbb451ff0"
}
}
}
If you want to get the picture url for example after logging in
LoginButton login_button = (LoginButton) view.findViewById(R.id.login_button);
callbackManager = CallbackManager.Factory.create();
login_button.setFragment(this);
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
//THIS CONTAINS the URL String displaying it is up to you
String PROFPIC_URL = object.getJSONObject("picture").getJSONObject("data").getString("url");
String FIRSTNAME = object.getString("first_name");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,picture,last_name,first_name");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
textview.setText("Facebook Login Cancelled");
}
#Override
public void onError(FacebookException exception) {
textview.setText("Facebook Login Error");
}
});
You can do values experiments in here https://developers.facebook.com/tools/explorer/

Related

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.....**

Asyntask not executing onPostExecute()

This is my Asyntask code which is not firing the onPostExecute() Any one has any idea why this might be happening???
EDIT: The Asyntask is called this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
.
.
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUp.class);
startActivity(intent);
}
});
textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Feedback.class);
startActivity(intent);
}
});
fbLoginButton = (LoginButton) findViewById(R.id.login_button);
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
token=loginResult.getAccessToken().getToken().toString();
Log.v("tag", "Token:\n" + token);
try {
get_profile();
}catch (Exception ex) {
String error = ex.getMessage();
}
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
#Override
public void onError(FacebookException e) {
Toast.makeText(MainActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
});
}
The get_profile(); method is defined like this
//Method to get profile details
public void get_profile() throws UnsupportedEncodingException {
try {
// Calling async task to get json
new FetchOperation().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
This is inside the Main class too
//Asynctask to get Getting fb profile details
private class FetchOperation extends AsyncTask<Void, Void, String> {
String fb_token;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
fb_token = token;
}
#Override
protected String doInBackground(Void... params) {
String response = "";
String Urls = "https://graph.facebook.com/me?access_token=";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(Urls +token);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("Response", "Hi From e1 : " + e.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Log.v("Response", "Hi From 2 : "+response.toString());
return response;
} catch (IOException e) {
e.printStackTrace();
Log.v("Response", "Hi From e2 : " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
Log.v("tag", "Result:" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String email = jsonObj.getString("email");
String firstName = jsonObj.getString("first_name");
String lastName = jsonObj.getString("last_name");
String gender = jsonObj.getString("gender");
String country = jsonObj.getString("locale");
id = jsonObj.getString("id");
user = firstName.concat(" ");
user = user.concat(lastName);
image = "http://graph.facebook.com/" + id + "/picture?type=large";
Log.v("Fb name", "Bla bla Name : " + user);
new UploadOperation().execute();
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
This is the last lines of the logcat
06-29 14:30:49.927 2091-2091/com.example.kmi_dev.fbloginsample V/tag﹕ Token:
CA****************************************************************xr
06-29 14:30:50.697 2091-2135/com.example.kmi_dev.fbloginsample V/Response﹕ Hi From 2 : {"id":"910***********6","first_name":"Shivanshu","gender":"male","last_name":"Verma","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/910***********6\/","locale":"en_GB","name":"Shivanshu Verma","timezone":5.5,"updated_time":"2015-06-22T04:17:39+0000","verified":true}
06-29 14:31:23.827 2091-2098/com.example.kmi_dev.fbloginsample W/art﹕ Suspending all threads took: 10ms
I intend to fire another asyntask which will then save the data fetched by this asyntask into the database.
Make these changes, it will work -
private class FetchOperation extends AsyncTask<Void, Void, String>
change to - private class FetchOperation extends AsyncTask<Void, String, String> , because, you are trying to return String.
response = EntityUtils.toString(httpEntity);
change to - response = EntityUtils.toString(httpEntity).toString();
at the next line of this you have actually done it.
At the very end of doInBackground method where return null;
change to - return response;
4.No need to call super in onPostExecute()
5.Inside onPostExecute() check jsonStr is null or not and do whatever you want to do if null and if contains json data.
Your JSONObject does not contain a JSONString "email", so it is falling over at line
String email = jsonObj.getString("email");
and going straight to catch block.

Using RequestToken for second time in twitter integration shows popup "You don't have access to appname"

Requesting access to token for second time doesn't work thats why we need to store the token for first time to use it in future reference.Thats what i am trying to do here in Twitter integration using SharedPreference while posting tweet.It works fine for the first time while posting tweet but shows popup in second time showing "You don't have access to appname.Please return to appname to continue signup process".
private class TokenGet extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
try {
if(requestTokenFirstTime) {
requestToken = twitter.getOAuthRequestToken();
oauth_url = requestToken.getAuthorizationURL();
// requestTokenFirstTime = false;
// }
SharedPreferences.Editor edit = pref.edit();
edit.putString("Request_TOKEN", requestToken.getToken());
edit.putString("Request_TOKEN_SECRET", requestToken.getTokenSecret());
edit.putString("OAUTH_URLT", oauth_url);
edit.commit();
requestTokenFirstTime = false;
}
else {
requestToken = new RequestToken(pref.getString("Request_TOKEN", ""), pref.getString("Request_TOKEN_SECRET", ""));
oauth_url = pref.getString("OAUTH_URLT", "null");
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return oauth_url;
}
Below is my complete code for TwitterFragment.java
TwitterFragment.java
public class TwitterFragment extends ListFragment {
final static String ScreenName = "IBL_Official";
final static String LOG_TAG = "rnc";
private FragmentActivity myContext;
private ListFragment activity;
private ListView listView;
public static EditText tx1;
private ProgressBar mDialog;
private QuickReturnFrameLayout searchLayout;
Button login;
boolean requestTokenFirstTime = true;
twitter4j.Twitter twitter;
RequestToken requestToken = null;
//static RequestToken requestToken ;
twitter4j.auth.AccessToken accessToken;
String oauth_url,oauth_verifier,profile_url;
Dialog auth_dialog;
WebView web;
SharedPreferences pref;
ProgressDialog progress;
Bitmap bitmap;
#Override
public void onAttach(Activity activity) {
if (activity instanceof FragmentActivity) {
myContext = (FragmentActivity) activity;
}
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activity = this;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
downloadTweets();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.twit_list, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
tx1=(EditText)rootView.findViewById(R.id.postcomment);
mDialog = (ProgressBar) rootView.findViewById(R.id.progress_bar);
searchLayout = (QuickReturnFrameLayout) rootView.findViewById(R.id.search_layout);
listView.setVerticalScrollBarEnabled(false);
((QuickReturnFrameLayout) rootView.findViewById(R.id.search_layout)).attach(listView);
rootView.setVerticalScrollBarEnabled(false);
login = (Button)rootView.findViewById(R.id.postbutton);
pref = getActivity().getPreferences(0);
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(pref.getString("CONSUMER_KEY", ""), pref.getString("CONSUMER_SECRET", ""));
login.setOnClickListener(new LoginProcess());
return rootView;
}
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) myContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
public class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final static String CONSUMER_KEY = "AuSSA6AHeCv9gskRhGQjSymCO";
final static String CONSUMER_SECRET = "eyRoYBONVh45V185TBYbbb3i9BpWmmaiv4wLbBYXd7UcZGGaDw";
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
#Override
public String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
#Override
public void onPreExecute() {
}
#Override
public void onPostExecute(String result) {
mDialog.setVisibility(View.GONE);
searchLayout.setVisibility(View.VISIBLE);
listView.setVisibility(View.VISIBLE);
Twitte twits = jsonToTwitter(result);
System.out.println(result);
ArrayList<String> data = new ArrayList<String>();
ArrayList<String> link = new ArrayList<String>();
ArrayList<String> time = new ArrayList<String>();
String logoimage = "";
String name = "";
String officialname = "";
for (Tweet tweet : twits) {
String[] splitted = tweet.getText().split("http://");
Log.d("splitted", String.valueOf(splitted.length));
data.add(splitted[0]);
if (splitted.length > 1) {
link.add("http://" + splitted[1]);
} else {
link.add("");
}
logoimage = tweet.getUser().getProfileImageUrl();
name = tweet.getUser().getName();
officialname = "# " + tweet.getUser().getScreenName();
time.add(tweet.getDateCreated());
}
//
Bitmap image = null;
try {
URL url = new URL(logoimage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
image = getRoundedShape(image);
} catch (Exception e) {
Log.d("error in image", e.toString());
Log.d("image", logoimage);
}
try {
TwitterAdapter adapter = new TwitterAdapter(getActivity(), data, link, image, time, name, officialname);
listView.setAdapter(adapter);
} catch (Exception e) {
System.out.println("error");
}
}
public Twitte jsonToTwitter(String result) {
Twitte twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitte.class);
} catch (IllegalStateException ex) {
}
}
return twits;
}
public Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
}
}
return auth;
}
public String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
inputStream.close();
} else {
sb.append(reason);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
public String getTwitterStream(String screenName) {
String results = null;
try {
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
String combined = urlApiKey + ":" + urlApiSecret;
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
if (auth != null && auth.token_type.equals("bearer")) {
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 50;
int targetHeight = 50;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW
);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), null
);
return targetBitmap;
}
}
private class LoginProcess implements OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new TokenGet().execute();
}}
private class TokenGet extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
try {
if(requestTokenFirstTime) {
requestToken = twitter.getOAuthRequestToken();
oauth_url = requestToken.getAuthorizationURL();
// requestTokenFirstTime = false;
// }
SharedPreferences.Editor edit = pref.edit();
edit.putString("Request_TOKEN", requestToken.getToken());
edit.putString("Request_TOKEN_SECRET", requestToken.getTokenSecret());
edit.putString("OAUTH_URLT", oauth_url);
edit.commit();
requestTokenFirstTime = false;
}
else {
requestToken = new RequestToken(pref.getString("Request_TOKEN", ""), pref.getString("Request_TOKEN_SECRET", ""));
oauth_url = pref.getString("OAUTH_URLT", "null");
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return oauth_url;
}
#Override
protected void onPostExecute(String oauth_url) {
if(oauth_url != null){
Log.e("URL", oauth_url);
auth_dialog = new Dialog(getActivity());
auth_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(oauth_url);
web.setWebViewClient(new WebViewClient() {
boolean authComplete = false;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains("oauth_verifier") && authComplete == false){
authComplete = true;
Log.e("Url",url);
Uri uri = Uri.parse(url);
oauth_verifier = uri.getQueryParameter("oauth_verifier");
auth_dialog.dismiss();
new AccessTokenGet().execute();
}else if(url.contains("denied")){
auth_dialog.dismiss();
Toast.makeText(getActivity(), "Sorry !, Permission Denied", Toast.LENGTH_SHORT).show();
}
}
});
auth_dialog.show();
auth_dialog.setCancelable(true);
}else{
Toast.makeText(getActivity(), "Sorry !, Network Error or Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}
}
private class AccessTokenGet extends AsyncTask<String, String, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Data ...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
}
#Override
protected Boolean doInBackground(String... args) {
try {
accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);
SharedPreferences.Editor edit = pref.edit();
edit.putString("ACCESS_TOKEN", accessToken.getToken());
edit.putString("ACCESS_TOKEN_SECRET", accessToken.getTokenSecret());
User user = twitter.showUser(accessToken.getUserId());
profile_url = user.getOriginalProfileImageURL();
edit.putString("NAME", user.getName());
edit.putString("IMAGE_URL", user.getOriginalProfileImageURL());
edit.commit();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean response) {
if(response){
progress.hide();
// progress.dismiss();
Fragment profile = new ProfileFragment();
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, profile);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
else{
auth_dialog.dismiss();
}
}
}
}
I think you may simply want to hang on to the oauth access token after the first attempt (or ask for it by calling twitter.getOAuthAccessToken() ) and reuse it for the second time.
I ran into a similar experience and I found that the twitter4j.Twitter twitter; instance already had an access token associated with this instance from my first attempt. So when I asked for the authentication url from the request token ( oauth_url = requestToken.getAuthorizationURL(); ) and opened it in a webpage I got a message similar to your problem description ( "You don't have access to Please return to to continue the signup process." ).
I think if you wanted to you could also start over by recreating the twitter4j.Twitter instance and the related instance variables (like the RequestToken ). However this would also require you to then do the whole authentication process again with would be repeating the same work you did on the first attempt.

Not able to retrieve profile pic with fb login

I followed the tutorial of facebook on their official page:
Facebook Login tutorial
However, after I finished this I do can login, but it doesn't retrieve my profile picture. Anyone else experienced this or has an idea what might cause this? I am getting no errors whatsoever..
I think you are clear upto getting facebook useUserId and FacebookToken.
Profile picture get can be done in two ways:
1: Facebook has provided you a view for profile picture `ie ProfilePictureView
in place of imageview in xml layout file take this view.
At the time of loadng image in this view simply do
ProfilePictureView profilePictureView;
profilePictureView = (ProfilePictureView) findViewById(R.id.friendProfilePicture);
profilePictureView.setCropped(true);
profilePictureView.setProfileId(USER_ID);
2: Another Option is get profile picture with the help of facebook token
ImageView imgProfilePic12=(ImageView)findViewById(R.id.imgProfilePic);
new LoadProfileImage(imgProfilePic12)
.execute("https://graph.facebook.com/me/picture?type=normal&method=GET&access_token="
+ Faceboo_Access_Token);
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
have you successfully logged in Facebook ?
if yes then
try {
JSONObject fbResObj = new JSONObject(fbUser
.getInnerJSONObject().toString());
String id = fbResObj.getString("id");
url = new URL("http://graph.facebook.com/" + id
+ "/picture?style=small");
Log.v(TAG, url.toString());
bmp = BitmapFactory.decodeStream(url
.openConnection().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
try this , where fbUser is the object of GraphUser which u get on executing GraphUserCallBack,
private void getUserDetail() {
String fqlQuery = "SELECT name,uid,pic FROM user WHERE uid in (SELECT uid1 FROM friend WHERE uid1=me())";
Bundle _params = new Bundle();
_params.putString("q", fqlQuery);
Session _session = Session.getActiveSession();
Request _request = new Request(_session, "/fql", _params, HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
if (graphObject != null) {
if (graphObject.getProperty("data") != null) {
try {
String _arry = graphObject.getProperty("data").toString();
JSONArray _jsonArray = new JSONArray(_arry);
if(_jsonArray.length()==1)
{
//here u will get your user's userId and Profile Picture and Name
String _uid = _jsonObject.getString("uid");
String _Name = _jsonObject.getString("name");
String _ImagePath = _jsonObject.getString("pic");
}
}
} catch (JSONException ex) {
if (ex != null) {
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
}
});
Request.executeBatchAsync(_request);
}
If you have Facebook id of user to get image use this link
https://graph.facebook.com/FACEBOOK_USER_ID/picture?type=large";
for small image use type = small

upload video to facebook in android

Problem:
My video isn't being uploaded to Facebook.
Question:
How can I upload a video to Facebook?
Note:
I can upload a picture from my gallery.
There are no Exceptions being thrown. I think there is a problem in the line
params.putString("filename", <selectedviedoPath> )
AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);
Bundle params = new Bundle();
//convert to byte stream
**FileInputStream is = new FileInputStream(new File(selectedviedoPath));**
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int data = 0;
while((data = is.read()) != -1)
bs.write(data);
is.close();
byte[] raw = bs.toByteArray();
bs.close();
params.putByteArray("video", raw);
params.putString("filename", <selectedviedoPath> );
mAsyncFbRunner.request("me/videos", params, "POST", new WallPostListener());
Below is what i have done and now Works Perfect to Post Video on Facebook.
FacebookVideoPostActivity.java
public class FacebookVideoPostActivity extends Activity {
/** Called when the activity is first created. */
private static Facebook facebook = new Facebook("YOUR_APP_ID"); // App ID For the App
private String permissions[] = {""};
private String statusString = "";
private Button btn1;
private String PATH = "/sdcard/test1.3gp"; // Put Your Video Link Here
private ProgressDialog mDialog ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.button1);
mDialog = new ProgressDialog(FacebookVideoPostActivity.this);
mDialog.setMessage("Posting video...");
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
facebook.authorize(FacebookVideoPostActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
#Override
public void onComplete(Bundle values) {
postVideoonWall();
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
});
}
public void postVideoonWall() {
mDialog.setMessage("Posting ...");
mDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
byte[] data = null;
InputStream is = null;
String dataMsg = "This video is posted from bla bla bla App";
Bundle param;
try {
is = new FileInputStream(PATH);
data = readBytes(is);
param = new Bundle();
param.putString("message", dataMsg);
param.putString("filename", "test1.mp4");
//param.putString("method", "video.upload");
param.putByteArray("video", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me/videos", param, "POST", new SampleUploadListener(), null);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private Handler mPostHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mDialog.dismiss();
if(msg.what==0){
Toast.makeText(getApplicationContext(), "Image Posted on Facebook.", Toast.LENGTH_SHORT).show();
}
else if(msg.what==1) {
Toast.makeText(getApplicationContext(), "Responce error.", Toast.LENGTH_SHORT).show();
}else if(msg.what==2){
Toast.makeText(getApplicationContext(), "Facebook error.", Toast.LENGTH_SHORT).show();
}
}
};
public byte[] readBytes(InputStream inputStream) throws IOException {
// This dynamically extends to take the bytes you read.
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// This is storage overwritten on each iteration with bytes.
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// We need to know how may bytes were read to write them to the byteBuffer.
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// And then we can return your byte array.
return byteBuffer.toByteArray();
}
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);
mPostHandler.sendEmptyMessage(0);
// 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) {
mPostHandler.sendEmptyMessage(1);
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
mPostHandler.sendEmptyMessage(2);
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
}
Now, Integrate Facebook SDK in your project and do changes as below:
Change Util.java from facebook sdk as below
public static String openUrl(String url, String method, Bundle params)
throws MalformedURLException, IOException {
// random string as boundary for multi-part http post
String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
String endLine = "\r\n";
OutputStream os;
// ADDED By Shreyash For Publish Video
// sbmmahajan#gmail.com
// Mo. 919825056129
// Try to get filename key
String filename = params.getString("filename");
// If found
if (filename != null) {
// Remove from params
params.remove("filename");
}
//===================================================
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
}
Util.logd("Facebook-Util", method + " URL: " + url);
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("User-Agent", System.getProperties().
getProperty("http.agent") + " FacebookAndroidSDK");
if (!method.equals("GET")) {
Bundle dataparams = new Bundle();
for (String key : params.keySet()) {
Object parameter = params.get(key);
if (parameter instanceof byte[]) {
dataparams.putByteArray(key, (byte[])parameter);
}
}
// use method override
if (!params.containsKey("method")) {
params.putString("method", method);
}
if (params.containsKey("access_token")) {
String decoded_token =
URLDecoder.decode(params.getString("access_token"));
params.putString("access_token", decoded_token);
}
conn.setRequestMethod("POST");
conn.setRequestProperty(
"Content-Type",
"multipart/form-data;boundary="+strBoundary);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
os = new BufferedOutputStream(conn.getOutputStream());
os.write(("--" + strBoundary +endLine).getBytes());
os.write((encodePostBody(params, strBoundary)).getBytes());
os.write((endLine + "--" + strBoundary + endLine).getBytes());
if (!dataparams.isEmpty()) {
for (String key: dataparams.keySet()){
// ADDED By Shreyash For Publish Video
// sbmmahajan#gmail.com
// Mo. 919825056129
// os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
os.write(("Content-Disposition: form-data; filename=\"" + ((filename) != null ? filename : key) + "\"" + endLine).getBytes());
os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
os.write(dataparams.getByteArray(key));
os.write((endLine + "--" + strBoundary + endLine).getBytes());
}
}
os.flush();
}
String response = "";
try {
response = read(conn.getInputStream());
} catch (FileNotFoundException e) {
// Error Stream contains JSON that we can parse to a FB error
response = read(conn.getErrorStream());
}
return response;
}
Put above function in that Util.Java and comment the same function available in it.
Now run the project.
If is there any query then let me know.
Enjoy :)
The API call for uploading videos is different to normal Graph API queries. See the facebook tutorial here: https://developers.facebook.com/blog/post/493/

Categories

Resources