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/
Related
I want to make a voice-text bot using DialogFlow to return an Activity.
The bot works well in terms of voice-text mode .. but I want the bot to answer the user by an Activity as the user ask him !
Like an example : I want "Messi goals in world cup 2018".
Result will be the activity that i will add in Android Studio and that will include Messi pictures with his goals and so on ..
my code :
public class MainActivity extends AppCompatActivity {
private final int REQ_CODE_SPEECH_INPUT = 100;
ImageButton btnSpeak;
TextView txtSpeechInput, outputText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSpeak = findViewById(R.id.btnSpeak);
txtSpeechInput = findViewById(R.id.txtSpeechInput);
outputText = findViewById(R.id.outputTex);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
*/
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Say Something");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"orry! Your device doesn\\'t support speech input",
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String userQuery = result.get(0);
txtSpeechInput.setText(userQuery);
RetrieveFeedTask task=new RetrieveFeedTask();
task.execute(userQuery);
}
break;
}
}
}
// Create GetText Metod
public String GetText(String query) throws UnsupportedEncodingException {
String text = "";
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL("my url");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Authorization", "Bearer client access token code");
conn.setRequestProperty("Content-Type", "application/json");
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
JSONArray queryArray = new JSONArray();
queryArray.put(query);
jsonParam.put("query", queryArray);
//jsonParam.put("name", "order a medium pizza");
jsonParam.put("lang", "en");
jsonParam.put("sessionId", "1234567890");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
Log.d("karma", "after conversion is " + jsonParam.toString());
wr.write(jsonParam.toString());
wr.flush();
Log.d("karma", "json is " + jsonParam);
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
JSONObject object1 = new JSONObject(text);
JSONObject object = object1.getJSONObject("result");
JSONObject fulfillment = null;
String speech = null;
//if (object.has("fulfillment")) {
fulfillment = object.getJSONObject("fulfillment");
//if (fulfillment.has("speech")) {
speech = fulfillment.optString("speech");
// }
// }
Log.d("karma ", "response is " + text);
return speech;
} catch (Exception ex) {
Log.d("karma", "exception at last " + ex);
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return null;}
class RetrieveFeedTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... voids) {
String s = null;
try {
s = GetText(voids[0]);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.d("karma", "Exception occurred " + e);
}
return s;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
outputText.setText(s);
}
}
}
You may use the Android library for Dialogflow and based on the response coming switch between different Activities or Fragments. It would be better to have one central activity for Dialogflow communication and switch between fragments or views.
I'm trying to integrate PayUBiz in my Android Application. It is working fine in test environment.
What I'm using is like below.
Test Merchant Key / Salt : gtKFFx / eCwWELxi
Our server URL for generating hash: http://xx.xxx.xx.xx/payment/getPaymentData
Success URL - Failure URL: https://payu.herokuapp.com/success - https://payu.herokuapp.com/failure
I'm passing orderId and userId in our server URL for generating hash.
I can go to the screen where I can enter test card details. But after entering card details I'm getting "Error Reason: Transaction failed due to incorrectly calculated hash parameter"
Whole error screen-shots are below.
What I done in code is like below.
ActivityConfirmOrder.java
private String merchantKey = "gtKFFx";
private String merchantSalt = "eCwWELxi";
private String userCredentials = merchantKey + ":" + "maulik#techniche.co";
private PayuConfig payuConfig;
private PaymentParams mPaymentParams;
In onCreate I put
// PayUBiz initialisation
Payu.setInstance(this);
Below methods are not in onCreate method.
private void makePayment() {
int environment = PayuConstants.STAGING_ENV;
sharedPref = new UserSharedPref(this);
mPaymentParams = new PaymentParams();
mPaymentParams.setKey(merchantKey);
mPaymentParams.setAmount(String.valueOf(totalPrice));
mPaymentParams.setProductInfo("product_info");
mPaymentParams.setFirstName("Maulik");
mPaymentParams.setEmail("maulik#techniche.co");
mPaymentParams.setTxnId(OrderNumber);
mPaymentParams.setSurl("https://payu.herokuapp.com/success");
mPaymentParams.setFurl("https://payu.herokuapp.com/failure");
mPaymentParams.setUdf1("");
mPaymentParams.setUdf2("");
mPaymentParams.setUdf3("");
mPaymentParams.setUdf4("");
mPaymentParams.setUdf5("");
mPaymentParams.setUserCredentials(userCredentials);
payuConfig = new PayuConfig();
payuConfig.setEnvironment(environment);
generatePayUHashFromServer(mPaymentParams);
}
private void generatePayUHashFromServer(PaymentParams mPaymentParams) {
StringBuffer postParamsBuffer = new StringBuffer();
postParamsBuffer.append(concatParams(PayuConstants.KEY, mPaymentParams.getKey()));
postParamsBuffer.append(concatParams(PayuConstants.AMOUNT, mPaymentParams.getAmount()));
postParamsBuffer.append(concatParams(PayuConstants.TXNID, mPaymentParams.getTxnId()));
postParamsBuffer.append(concatParams(PayuConstants.EMAIL, null == mPaymentParams.getEmail() ? "" : mPaymentParams.getEmail()));
postParamsBuffer.append(concatParams(PayuConstants.PRODUCT_INFO, mPaymentParams.getProductInfo()));
postParamsBuffer.append(concatParams(PayuConstants.FIRST_NAME, null == mPaymentParams.getFirstName() ? "" : mPaymentParams.getFirstName()));
postParamsBuffer.append(concatParams(PayuConstants.UDF1, mPaymentParams.getUdf1() == null ? "" : mPaymentParams.getUdf1()));
postParamsBuffer.append(concatParams(PayuConstants.UDF2, mPaymentParams.getUdf2() == null ? "" : mPaymentParams.getUdf2()));
postParamsBuffer.append(concatParams(PayuConstants.UDF3, mPaymentParams.getUdf3() == null ? "" : mPaymentParams.getUdf3()));
postParamsBuffer.append(concatParams(PayuConstants.UDF4, mPaymentParams.getUdf4() == null ? "" : mPaymentParams.getUdf4()));
postParamsBuffer.append(concatParams(PayuConstants.UDF5, mPaymentParams.getUdf5() == null ? "" : mPaymentParams.getUdf5()));
postParamsBuffer.append(concatParams(PayuConstants.USER_CREDENTIALS, mPaymentParams.getUserCredentials() == null ? PayuConstants.DEFAULT : mPaymentParams.getUserCredentials()));
if (null != mPaymentParams.getOfferKey())
postParamsBuffer.append(concatParams(PayuConstants.OFFER_KEY, mPaymentParams.getOfferKey()));
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("orderId", orderId);
jsonObject.put("userId", sharedPref.getUserId());
} catch (JSONException e) {
e.printStackTrace();
}
// String postParams = jsonObject.toString();
// String postParams = postParamsBuffer.charAt(postParamsBuffer.length() - 1) == '&' ? postParamsBuffer.substring(0, postParamsBuffer.length() - 1).toString() : postParamsBuffer.toString();
GetHashesFromServerTask getHashesFromServerTask = new GetHashesFromServerTask();
getHashesFromServerTask.execute(jsonObject);
}
protected String concatParams(String key, String value) {
return key + "=" + value + "&";
}
private class GetHashesFromServerTask extends AsyncTask<JSONObject, String, PayuHashes> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(ActivityConfirmOrder.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected PayuHashes doInBackground(JSONObject... postParams) {
PayuHashes payuHashes = new PayuHashes();
try {
URL url = new URL(AppConstant.BASE_URL + "/payment/getPaymentData");
String postParam = postParams[0].toString();
byte[] postParamsByte = postParam.getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Length", String.valueOf(postParamsByte.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postParamsByte);
InputStream responseInputStream = conn.getInputStream();
StringBuffer responseStringBuffer = new StringBuffer();
byte[] byteContainer = new byte[1024];
for (int i; (i = responseInputStream.read(byteContainer)) != -1; ) {
responseStringBuffer.append(new String(byteContainer, 0, i));
}
JSONObject response = new JSONObject(responseStringBuffer.toString());
Iterator<String> payuHashIterator = response.keys();
while (payuHashIterator.hasNext()) {
String key = payuHashIterator.next();
switch (key) {
case "payment_hash":
payuHashes.setPaymentHash(response.getString(key));
break;
case "vas_for_mobile_sdk_hash":
payuHashes.setVasForMobileSdkHash(response.getString(key));
break;
case "payment_related_details_for_mobile_sdk_hash":
payuHashes.setPaymentRelatedDetailsForMobileSdkHash(response.getString(key));
break;
case "delete_user_card_hash":
payuHashes.setDeleteCardHash(response.getString(key));
break;
case "get_user_cards_hash":
payuHashes.setStoredCardsHash(response.getString(key));
break;
case "edit_user_card_hash":
payuHashes.setEditCardHash(response.getString(key));
break;
case "save_user_card_hash":
payuHashes.setSaveCardHash(response.getString(key));
break;
case "check_offer_status_hash":
payuHashes.setCheckOfferStatusHash(response.getString(key));
break;
default:
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return payuHashes;
}
#Override
protected void onPostExecute(PayuHashes payuHashes) {
super.onPostExecute(payuHashes);
progressDialog.dismiss();
launchSdkUI(payuHashes);
}
}
public void launchSdkUI(PayuHashes payuHashes) {
Intent intent = new Intent(ActivityConfirmOrder.this, PayUBaseActivity.class);
intent.putExtra(PayuConstants.PAYU_CONFIG, payuConfig);
intent.putExtra(PayuConstants.PAYMENT_PARAMS, mPaymentParams);
intent.putExtra(PayuConstants.PAYU_HASHES, payuHashes);
intent.putExtra(PayuConstants.SALT, merchantSalt);
intent.putExtra("PaymentType", "PAYU");
startActivityForResult(intent, PayuConstants.PAYU_REQUEST_CODE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PayuConstants.PAYU_REQUEST_CODE) {
if (data != null) {
Log.e("PayuResponse", data.getStringExtra("payu_response"));
if (!data.getStringExtra("payu_response").equals("")) {
PayUSuccessRequest request = new PayUSuccessRequest(ActivityConfirmOrder.this);
try {
JSONObject paySuccessRes = new JSONObject(data.getStringExtra("payu_response"));
request.setPayUSuccessResJsonObject(paySuccessRes);
} catch (JSONException e) {
e.printStackTrace();
}
new AsyncTaskExecutor<A2BRequest, Void, A2BResponse>().execute(
new RequestProcessor(ActivityConfirmOrder.this, ActivityConfirmOrder.this, true), request);
}
try {
JSONObject responseObject = new JSONObject(data.getStringExtra("payu_response"));
if (responseObject != null) {
if (responseObject.optString("status").equalsIgnoreCase("failure")) {
Toast.makeText(mContext, "Failure..", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ActivityConfirmOrder.this, ActivityOrderFailure.class);
ActivityConfirmOrder.this.startActivity(intent);
} else {
//Toast.makeText(getActivity(), getString(R.string.could_not_receive_data), Toast.LENGTH_LONG).show();
}
} else {
//Toast.makeText(getActivity(), getString(R.string.could_not_receive_data), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
//Toast.makeText(getActivity(), getString(R.string.could_not_receive_data), Toast.LENGTH_LONG).show();
}
} else {
//Toast.makeText(getActivity(), getString(R.string.could_not_receive_data), Toast.LENGTH_LONG).show();
}
} else {
Log.e("Log MSg", "No Payu SDK Request Code");
}
}
I found the solution but I haven't applied yet.
I emailed to customer support of PayUBiz and they responded well.
Email IDs: tech#payu.in / mobile-integration#payu.in
As I mentioned in question I was using TEST ENVIRONMENT and TEST CREDENTIALS and OUR SERVER URL for generating hash, this is the place where I was wrong. It won't work if you are using TEST CREDENTIALS and YOUR SERVER URL for hash.
In TEST ENVIRONMENT use all TESTING RELATED stuff and for LIVE ENVIRONMENT use all LIVE RELATED stuff.
I replaced OUR SERVER URL with PayUBiz's TEST URL https://payu.herokuapp.com/get_hash and it's working.
So far I have done this much. Will you please help me what to do next to load an image in a listview. I have parsed url using xml parsing. I just want to load an image in a listview. Please help me experts!!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
Bundle b = getIntent().getExtras();
m_brandName = b.getString("Brand_Name");
m_modelName = b.getString("Model_Name");
m_categoryName = b.getString("Category_Name");
actAppChartCatList = this;
//String url = "http://www.bitstechnologies.in/HellaWebserviceV2/Service1.asmx/populateBrandModelCategory?brandName=\" + m_brandName + \"&\" + \"modelName=\" + m_modelName + \"&\" + \"categoryName=\" + m_categoryName";
String url = "http://www.bitstechnologies.in/HellaWebserviceV2/Service1.asmx/populateBrandModelCategory?brandName=" + m_brandName + "&modelName=" + m_modelName + "&categoryName=" + m_categoryName;
String urlFinal = "";
if (url.contains(" "))
urlFinal = url.replace(" ", "%20");
else
urlFinal = url;
//new DownloadTaskCV().execute("http://www.bitstechnologies.in/HellaWebserviceV2/Service1.asmx/populateBrandModelCategory?brandName=" + m_brandName + "&" + "modelName=" + m_modelName + "&" + "categoryName=" + m_categoryName);
new DownloadTaskCV().execute(urlFinal);
pdGettingProducts = ProgressDialog.show(ActivityAppChartToCategoryList.this, "", "Getting Products.......");
setContentView(R.layout.activity_activity_app_chart_to_category_list);
mListView = (ListView) findViewById(R.id.showProductLists);
}
public static ActivityAppChartToCategoryList getInstance() {
return actAppChartCatList;
}
public void progDialogDownloadingDismiss() {
if (pdGettingProducts != null) {
pdGettingProducts.dismiss();
}
}
public void showEmptyMessage() {
progDialogDownloadingDismiss();
adb = new AlertDialog.Builder(this);
adb.setTitle("");
adb.setMessage("No products");
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
onBackPressed();
}
});
adb.show();
}
/*
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
Log.e("Response code : ", "" + urlConnection.getResponseCode());
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
iStream.close();
}
//pdDownloadingList.dismiss();
return data;
}
private class DownloadTaskCV extends AsyncTask<String, Integer, String> {
String data = null;
Product product = null;
ArrayList<Product> productslist = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
//super.onPostExecute(result);
try {
if ((result.equalsIgnoreCase("[]")) || (result == null)) {
showEmptyMessage();
this.cancel(true);
}
parseXmlResponse(result);
} catch (Exception e) {
showEmptyMessage();
this.cancel(true);
}
}
private String parseXmlResponse(String xmlResponse) {
if (xmlResponse != null) {
XmlPullParser myParser;
XmlPullParserFactory xmlFactoryObject;
try {
xmlFactoryObject = XmlPullParserFactory.newInstance();
myParser = xmlFactoryObject.newPullParser();
myParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
int event;
String text = null;
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
if (name.equalsIgnoreCase("ProductList")) {
// instantiate Arraylist of "Products"
productslist = new ArrayList<>();
}
if (name.equalsIgnoreCase("Product_Name")) {
// instantiate object of Product
product = new Product();
}
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if (name.equalsIgnoreCase("Product_Name")) {
// prodObj.setProductName(text)
product.setProducts_name(text);
}
if (name.equalsIgnoreCase("Product_Image_Left")) {
// prodObj.setProductImageLeft(text)
product.setProducts_image(text);
// add the product object to the array List
productslist.add(product);
}
break;
default:
break;
} // end of switch
event = myParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return xmlResponse;
}
}
you can also use the open resource Universal Image Loader.UIL aims to provide a powerful, flexible and highly customizable instrument for image loading, caching and displaying. It provides a lot of configuration options and good control over the image loading and caching process.
just like this(use it so easy) :
ktvIconImg = (RoundImageView) convertView
.findViewById(R.id.ktv_icon_img);
ImageLoader.getInstance().displayImage(url, ktvIconImg, mOptions,new ImageLoadingListener() {
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}});
Add this in your gradle
compile "com.squareup.picasso:picasso:2.4.0"
IN your Adapter or activty
Picasso.with(this)
.load("YOUR IMAGE URL HERE")
.placeholder(R.drawable.ic_placeholder) // optional
.error(R.drawable.ic_error_fallback) // optional
.resize(250, 200) // optional
.rotate(90) // optional
.into(imageView);
I would recommend you to use the Picasso library. It is very simple to use.
Picasso.
with(YourActivityName).
load("Your image url").
into(YourImageView);
Here is a very good article about it.
https://www.bignerdranch.com/blog/solving-the-android-image-loading-problem-volley-vs-picasso/
Reference:
Why use Android Picasso library to download images?
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/
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/