I am using the Fabric of the Twitter for sharing the video.I am not able to share the video on the twitter and yet now i am sharing the images only by the help of Fabric
Below is my lines of code for the fabric integration
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "xxxxxxx";
private static final String TWITTER_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxx";
private TwitterAuthClient authclient;
private TwitterLoginButton loginButton;
private String selectedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
setContentView(R.layout.activity_main);
authclient = new TwitterAuthClient();
loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// The TwitterSession is also available through:
// Twitter.getInstance().core.getSessionManager().getActiveSession()
TwitterSession session = result.data;
// TODO: Remove toast and use the TwitterSession's userID
// with your app's user model
String msg = "#" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void failure(TwitterException exception) {
Log.d("TwitterKit", "Login with Twitter failure", exception);
}
});
Button share_btn = (Button)findViewById(R.id.share_btn);
share_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
intent.setType("video/*");
startActivityForResult(intent, 3);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
if (requestCode == 3) {
Uri selectedImageUri = data.getData();
// OI FILE Manager
selectedImagePath = selectedImageUri.getPath();
// MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
System.out.println("Here is the data ==>> " + selectedImagePath+" ");
TweetComposer.Builder builder = new TweetComposer.Builder(MainActivity.this)
.text("")
.image(Uri.parse(selectedImagePath));
builder.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
I have got the solution for uploading the video using Twitter's Fabrics
Here is the below lines of code to upload the video on Twitter , using the Fabric
File myVideoFile = new File("HERE_IS_YOURS_SD_CARD_VIDEO_PATH");
Uri myVideoUri = Uri.fromFile(myVideoFile);
TweetComposer.Builder builder = new TweetComposer.Builder(MainActivity.this)
.text("YOUR_TEXT_MESSAGE") //Here is yours message which you want to send..If u does not require than remove this method
.image(myVideoUri );
builder.show();
Related
I am trying to post image and text to my facebook wall from my own android app. I need to select the image from mobile gallery, but its not working. i am not getting what is the issue in this code. Can anyone please help me??
public class PostFacebook extends Activity{
private Facebook mFacebook;
private CheckBox mFacebookCb;
private ProgressDialog mProgress;
private static final int SELECT_PICTURE = 100;
byte[] inputData;
Uri selectedImageUri;
String imgString;
ImageView image;
private Handler mRunOnUi = new Handler();
private static final String APP_ID = "7************";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fbpost);
final EditText reviewEdit = (EditText) findViewById(R.id.revieew);
image = (ImageView) findViewById(R.id.imageView1);
mFacebookCb = (CheckBox) findViewById(R.id.cb_facebook);
mProgress = new ProgressDialog(this);
mFacebook = new Facebook(APP_ID);
SessionStore.restore(mFacebook, this);
if (mFacebook.isSessionValid()) {
mFacebookCb.setChecked(true);
String name = SessionStore.getName(this);
name = (name.equals("")) ? "Unknown" : name;
mFacebookCb.setText(" Facebook (" + name + ")");
}
((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String review = reviewEdit.getText().toString();
try {
InputStream iStream = getContentResolver().openInputStream(selectedImageUri);
inputData = GetImage.getBytes(iStream);
imgString = Base64.encodeToString(inputData, Base64.DEFAULT);
Log.v("image_check", imgString);
Toast.makeText(PostFacebook.this, imgString, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (review.equals(""))
return;
if (mFacebookCb.isChecked()) postToFacebook(review, imgString);
}
});
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
});
}
private void postToFacebook(String review, String image) {
mProgress.setMessage("Posting ...");
mProgress.show();
AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);
Bundle params = new Bundle();
params.putString("message", review);
params.putString("picture", image);
params.putString("name", "Hira Ghaffar");
params.putString("caption", "Innovent.net");
params.putString("description", "Innovent is an android app developed by iFish Technologies");
mAsyncFbRunner.request("me/feed", params, "POST", new WallPostListener());
}
private final class WallPostListener extends BaseRequestListener {
public void onComplete(final String response) {
mRunOnUi.post(new Runnable() {
#Override
public void run() {
mProgress.cancel();
Toast.makeText(PostFacebook.this, "Posted to Facebook", Toast.LENGTH_SHORT).show();
}
});
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
selectedImageUri = data.getData();
if (null != selectedImageUri) {
image.setImageURI(selectedImageUri);
}
}
}
}
}
Here, The complete example of share image on facebook wall.
http://simpledeveloper.com/how-to-share-an-image-on-facebook-in-android/
I am making a edit profile page , in which i display profile picture of the user the user can edit the profile picture . before clicking submit the i want to save the final updated url of profile picture . The problem is that if i change the profile picture and and instantly click on submit the value of variable storing the url doen not change but if i wait for few seconds it changes is there a way to get the value updated instantly.
**My edit profile class**
public class DocEditProfileInfo extends DocBaseActivity {
private static final String TAG =
private String profilePicUrl;
public String profilepicUrlComplete;
ArrayList<String> mImagesString = new ArrayList<>();
private ProgressBar imageProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
imageProgressBar = (ProgressBar) findViewById(R.id.progress);
setUpRestAdapter();
setSalutation();
setDocPersonalDetails();
ImageView iv = (ImageView) findViewById(R.id.camera_new);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDialogForImage();
}
});
docSubmitInfo.setOnClickListener(this);
}
private void setDialogForImage() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_select_from_source);
Button btnCamera = (Button) dialog.findViewById(R.id.btnCamera);
Button btnDocs = (Button) dialog.findViewById(R.id.btnDoc);
btnDocs.setVisibility(View.INVISIBLE);
Button btnGallery = (Button) dialog.findViewById(R.id.btnGallery);
dialog.show();
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
dialog.cancel();
}
});
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
dialog.cancel();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri mImageCaptureUri;
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 0 && resultCode == RESULT_OK) {
Bitmap bp = (Bitmap) data.getExtras().get("data");
// Uri selectedImageUri = data.getData();
// Glide.with(this).load(selectedImageUri).fitCenter().into(personImage);
personImage.setImageBitmap(getRoundedShape(bp));
// personImage.setImageBitmap(bp);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), bp);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File filePath = new File(getRealPathFromURI(tempUri));
sendImagesToServerFromCamera(filePath.getPath());
} else if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
/* Uri selectedImageUri = data.getData();
Log.e(TAG, "onActivityResult: URI " + selectedImageUri);
Glide.with(this).load(selectedImageUri).into(personImage);*/
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
personImage.setImageBitmap(getRoundedShape(BitmapFactory
.decodeFile(imgDecodableString)));
sendImagesToServerFromCamera(imgDecodableString);
}
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
*******
}
private String getRealPathFromURI(Uri tempUri) {
********
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
*********
}
private void sendImagesToServerFromCamera(String path) {
File imgPath = new File(path);
Log.e(TAG, "PATH " + path);
RequestBody requestFile =
RequestBody.create(MediaType.parse("image/jpg"), imgPath);
//For sending all types of images , presently only jpg allowed
// RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), imgPath);
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", imgPath.getName(), requestFile);
/* MultipartBody.Part body =
MultipartBody.Part.createFormData("file", imgPath.getName(), fbody);*/
Call<ProfilePicture> call = ProfilePicAdapter.sendProfilePic(body);
call.enqueue(new Callback<ProfilePicture>() {
#Override
public void onResponse(Call<ProfilePicture> call, Response<ProfilePicture> response) {
if (response.isSuccessful()) {
profilePicUrl = response.body().getUrl();
// profilepicUrlComplete = BASE_URL_FOR_IMAGE + profilePicUrl;
// String profilePicUrl = BASE_URL_FOR_IMAGE + profilePicUrl;
if (response.body().getUrl() != null) {
profilePicUrl = response.body().getUrl();
String profilePictureUrlComplete = BASE_URL_FOR_IMAGE + profilePicUrl;
setProfilePicURL(profilePictureUrlComplete);
}
} else {
Log.e(TAG, "UNSUCCESSFUL RESPONSE " + response.errorBody() + "*" + response.code());
}
}
#Override
public void onFailure(Call<ProfilePicture> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.toString());
}
});
}
private void setProfilePicURL(String profilePictureUrlComplete) {
profilepicUrlComplete = profilePictureUrlComplete;
Log.e(TAG, "setProfilePicURL: " + profilePictureUrlComplete);
}
private void setDocPersonalDetails() {
*********
}
#Override
public void onClick(View v) {
if (isEditProfileValid()) {
Log.e(TAG, "onClick: PROFILE URL " + profilepicUrlComplete);
***docPersonalDetailsUpdate.setProfilePic(profilepicUrlComplete);***
Call<DoctorProfile> call = docPersonalDetailsUpdateAdapter.docEditPersonalDetails(docPersonalDetailsUpdate);
if (NetworkUtils.isNetworkConnected(this)) {
call.enqueue(new Callback<DoctorProfile>() {
#Override
public void onResponse(Call<DoctorProfile> call, Response<DoctorProfile> response) {
if (response.isSuccessful()) {
finish();
}
}
#Override
public void onFailure(Call<DoctorProfile> call, Throwable t) {
Log.e(TAG, "onFailure: ");
}
});
} else {
SnakBarUtils.networkConnected(this);
}
}
I am using fabric to integrate Twitter in Android application.
public class MainActivity extends AppCompatActivity {
private static final String TWITTER_KEY = "";
private static final String TWITTER_SECRET = "";
private TwitterLoginButton loginButton;
private Button btnPostTweet;
private static final int TWEET_COMPOSER_REQUEST_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
setContentView(R.layout.activity_main);
loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
btnPostTweet = (Button) findViewById(R.id.btn_post_tweet);
btnPostTweet.setOnClickListener(onClickListener);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
Twitter.getInstance().core.getSessionManager().getActiveSession()
TwitterSession session = result.data;
String msg = "#" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void failure(TwitterException exception) {
Log.d("TwitterKit", "Login with Twitter failure", exception);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Make sure that the loginButton hears the result from any
// Activity that it triggered.
if (requestCode == TWEET_COMPOSER_REQUEST_CODE && resultCode == RESULT_OK)
Toast.makeText(MainActivity.this, "Updated tweet using composer", Toast.LENGTH_SHORT).show();
else
loginButton.onActivityResult(requestCode, resultCode, data);
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_post_tweet:
postTweet();
// postTweetManually();
break;
default:
break;
}
}
};
private void postTweet() {
/* TweetComposer.Builder builder = new TweetComposer.Builder(this)
.text("just setting up my Fabric.");
Intent twitterIntent = builder.createIntent();
startActivityForResult(twitterIntent, REQUEST_TWEET_POST);*/
Intent intent = null;
try {
intent = new TweetComposer.Builder(this)
.text("Tweet from Fabric!")
.url(new URL("http://www.twitter.com"))
.createIntent();
} catch (MalformedURLException e) {
e.printStackTrace();
}
startActivityForResult(intent, TWEET_COMPOSER_REQUEST_CODE);
}
private void postTweetManually() {
TwitterSession twitterSession = Twitter.getSessionManager().getActiveSession();
StatusesService statusesService = Twitter.getApiClient(twitterSession).getStatusesService();
String username = Twitter.getSessionManager().getActiveSession().getUserName();
statusesService.update("#" + username + "Manually update on twitter1", 1L, true, 0.0d, 0.0d, "", true, true, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
Toast.makeText(MainActivity.this, "Tweet Updated", Toast.LENGTH_LONG).show();
Log.d("Tweet Updated", result.data.user.name);
}
#Override
public void failure(TwitterException e) {
Log.d("Tweet Update Failed", e.getMessage());
}
});
}
}
I have not installed Twitter application in my device.
So TwitterComposer is opening WebBroswer.
After posted tweet I am getting screen like below which does not redirect to app.
Note : While login it works perfect..
Thanks.
Not sure if you have the same issue I had but in my case I was getting the onActivityResult() callback but the resulCode was not RESULT_OK although the tweet had been successfully posted
I use Fabric SDK to send tweets from my application.
I build a share dialog and send tweet from activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(CONSUMER_KEY, CONSUMER_SECRET);
Fabric.with(this, new TwitterCore(authConfig), new TweetComposer());
Bundle bundle = getIntent().getExtras().getBundle(SHARE_DATA);
String description = bundle.getString(SHARE_DESCRIPTION);
String title = bundle.getString(SHARE_TITLE);
String picture = bundle.getString(SHARE_PICTURE_LINK);
String link = bundle.getString(SHARE_LINK);
TweetComposer.Builder builder = null;
try {
InputStream in = new java.net.URL(picture).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Uri yourUri = getImageUri(this,bitmap);
builder = new TweetComposer.Builder(this)
.text(title + "\n" + description)
.url(new URL(link))
.image(yourUri);
//??? IS THERE ANY LISTENER ???
builder.show();
} catch (IOException e1) {
e1.printStackTrace();
}
}
I want to know status of sharing, like an success or not, but i can't find any listener for this action. I missed something?
Instead of use builder.show(), you should use builder.createIntent() :
Intent intent = new TweetComposer.Builder(getActivity())
.text("TEXT")
.url("URL")
.createIntent();
startActivityForResult(intent, TWEET_COMPOSER_REQUEST_CODE);
To get the result feedback in onActivityResult() :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TWEET_COMPOSER_REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
onTwitterSuccess();
} else if(resultCode == Activity.RESULT_CANCELED) {
onTwitterCancel();
}
}
}
use below method to twitt via rest service and pass media id as null.i m successfully posting tweets from my app
public void postToTwitter(ArrayList<String>mediaIds) {
String message;
if(Validator.isNotNull(preferences.getFbShareMessage())){
message=preferences.getFbShareMessage()+" "+com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId();
}
else {
message = getString(R.string.google_status, HWUtil.getFullName(preferences.getUserInfo().getFirstName(), preferences.getUserInfo().getLastName()), userHistory.getSportName(), HWUtil.secondToTime(userHistory.getDuration()))+" "+com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId();
}
String mediaId;
if (Validator.isNotNull(mediaIds) && mediaIds.size() > 0) {
mediaId="";
for (int i = 0; i < mediaIds.size(); i++) {
if (i == 0) {
mediaId = mediaIds.get(i);
} else {
mediaId += "," + mediaIds.get(i);
}
}
}
else {
mediaId=null;
}
StatusesService statusesService = twitterApiClient.getStatusesService();
statusesService.update(message, null, null, null, null, null, null, null, mediaId, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
dismissProgressDialog();
if(Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
com.aimdek.healthwel.network.Request.getRequest().sendRequest(com.aimdek.healthwel.network.Request.SHARE_USER_HISTORY, TwitterIntegration.this, TwitterIntegration.this, RequestParameterBuilder.buildMapForShareUserHistory(userHistory.getId(), TwitterIntegration.this));
}
#Override
public void failure(TwitterException exception) {
if(Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
dismissProgressDialog();
finish();
HWUtil.showToast(TwitterIntegration.this,exception.getMessage());
}
});
}
I have included Twitter Fabric SDK in my android application and can post tweets from it. I would like to post images as well though but that doesn't seem possible through the StatusesService that is used to post text-only tweets.
Is it not possible to do this through the SDK? Do I have to do an explicit http post for this?
According to the Fabric SDK, yes you can embed media in your Tweet through TweetUI.
Sample Code
Initialize with Fabric
Fabric.with(this, new TweetComposer());
Tweet Code
TweetComposer.Builder builder = new TweetComposer.Builder(this)
.text("just setting up my Fabric.")
.image(myImageUri);
builder.show();
File myImageFile = new File("/path/to/image");
Uri myImageUri = Uri.fromFile(myImageFile);
Remember
In the event that the Twitter app is not installed, TweetComposer will
create an intent to interact with the Twitter.com in a browser. The
browser ignores a specified image.
package ...
public class StatusFragment extends Fragment {
Button btn_select, btn_post_image;
EditText edt_status;
String status;
ImageView img_status;
private static final int RESULT_LOAD_IMAGE = 1;
SharedPreferences mSharedPreferences;
String selectedImagePath;
Uri selectedImage;
TypedFile typedFile;
private static final String IMAGE_DIRECTORY_NAME = "Hello Twitter";
String mCurrentPhotoPath;
File mFile;
ProgressDialog pDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_status, container, false);
btn_post_image = (Button) rootView.findViewById(R.id.btn_post_image);
btn_select = (Button) rootView.findViewById(R.id.btn_select);
edt_status = (EditText) rootView.findViewById(R.id.edt_status);
img_status = (ImageView) rootView.findViewById(R.id.img_status);
btn_post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (StatusFragment.CheckNetwork.isInternetAvailable(getActivity())) //if connection available
{
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Uploading......");
pDialog.show();
final TwitterSession session = Twitter.getSessionManager().getActiveSession();
mFile = new File(getRealPathFromURI(selectedImage));
TypedFile typedFile = new TypedFile("application/octet-stream", mFile);
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(session);
MediaService ms = twitterApiClient.getMediaService();
ms.upload(typedFile, null, null, new Callback<Media>() {
#Override
public void success(Result<Media> mediaResult) {
// show on User Timeline
// StatusesService statusesService = TwitterCore.getInstance().getApiClient(session).getStatusesService();
// statusesService.update(edt_status.getText().toString(), null, false, null, null, null, true, false, mediaResult.data.mediaIdString, new Callback<Tweet>() {
// #Override
// public void success(Result<Tweet> tweetResult) {
// //...
// Toast.makeText(getActivity(), "Upload Complete", Toast.LENGTH_SHORT).show();
// pDialog.dismiss();
// }
//
// #Override
// public void failure(TwitterException e) {
// //...
// Toast.makeText(getActivity(), "Upload Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
// pDialog.dismiss();
// }
//
// });
// Show on Home Timeline
StatusesService statusesService = TwitterCore.getInstance().getApiClient(session).getStatusesService();
statusesService.update( " content: " + edt_status.getText().toString(), null, false, null, null, null, true, false, mediaResult.data.mediaIdString, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> tweetResult) {
pDialog.dismiss();
Toast.makeText(getActivity(), "Upload Completed", Toast.LENGTH_SHORT).show();
}
#Override
public void failure(TwitterException e) {
//...
pDialog.dismiss();
Toast.makeText(getActivity(), "Upload Error"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void failure(TwitterException e) {
//...
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else{
Toast.makeText(getActivity(), "Network error", Toast.LENGTH_SHORT).show();
}
}
});
btn_select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK) {
selectedImage = data.getData();
img_status.setImageURI(selectedImage);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri contentUri) {
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
return contentUri.getPath();
}
}
public static class CheckNetwork {
static String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context) {
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null) {
Log.d(TAG, "no internet connection");
return false;
} else {
if (info.isConnected()) {
Log.d(TAG, " internet connection available...");
return true;
} else {
Log.d(TAG, " internet connection");
return true;
}
}
}
}
public class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public UploadMediaService getUploadMediaService() {
return getService(UploadMediaService.class);
}
}
interface UploadMediaService {
#Multipart
#POST("1.1/media/upload.json")
void upload(#Part("media") TypedFile file, #Part("additional_owners") String owners, Callback<MediaEntity> cb);
}
public void openPath(Uri uri) {
InputStream is = null;
try {
is = getActivity().getContentResolver().openInputStream(uri);
//Convert your stream to data here
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try it!