Result code for sharing intent for instagram android - android-sharing

Result code always gives 0 if i successfully shared an image with instagram via intent. Please help. Thanks in advance.
I have tried a lot.
This is my code :
File imageFileToShare = new File(filePath);
Uri uri = Uri.fromFile(imageFileToShare);
Intent shareInstagramIntent = new Intent(Intent.ACTION_SEND);
shareInstagramIntent.setPackage("com.instagram.android");
shareInstagramIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareInstagramIntent.setType("image/*");
shareInstagramIntent.putExtra(Intent.EXTRA_TEXT, text);
startActivityForResult(shareInstagramIntent, INSTAGRAM);
This is my onActivityResult :
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case INSTAGRAM:
logI("Request e: " + resultCode);
if (resultCode == thisActivity.RESULT_OK) {
Utilities.showAlert(thisActivity, "Image shared with instagram successfully");
new PostPointsTask("instagram").execute("");
} else {
Utilities.showAlert(thisActivity, "Image shared with instagram was cancelled");
}
}
}

There is no callback from instagram for share intent ,better use instagram sdk to share your message.

Related

Xamarin - IOS - Video assets in Photo library - Find By name

I'm new in Xamarin development.
I build my app, where user can clicks on DOWNLOAD button.
This button download video from the server and save to Photo library.
Here is how I implement this (maybe its incorrect way??)
public bool SaveVideo(byte[] videoData, int id)
{
try
{
CreateCustomAlbum();
// Save file to applicaiton folder
string local_path = SaveFileToApplicationFolder(videoData);
_lib.WriteVideoToSavedPhotosAlbum(new Foundation.NSUrl(local_path), (t, u) =>
{
DeleteLocalFile(local_path); // HERE I DELETE FILE FOR NOT INCREASE SIZE OF APPLICATION
_local_file_path = t.AbsoluteUrl.ToString(); // global variable
_lib.Enumerate(ALAssetsGroupType.Album, HandleALAssetsLibraryGroupsEnumerationResultsDelegate, (obj) => { });
});
return true;
}
catch (Exception ex)
{
return false;
}
}
void DeleteLocalFile(string local_path)
{
try
{
if (File.Exists(local_path))
{
File.Delete(local_path);
if (!File.Exists(local_path))
{
Console.WriteLine("Deleted");
}
}
}
catch (Exception ex)
{
}
}
string SaveFileToApplicationFolder(byte[] videoData)
{
try
{
string file_path = String.Empty;
var doc = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filename = "MY-APP-" + id + ".mp4"; // id global variable
file_path = Path.Combine(doc, filename); // global variable
File.WriteAllBytes(file_path, videoData);
return file_path;
}
catch (Exception ex)
{
return String.Empty;
}
}
void HandleALAssetsLibraryGroupsEnumerationResultsDelegate(ALAssetsGroup group, ref bool stop)
{
try
{
if (group == null)
{
stop = true;
return;
}
if (group.Name == "MY-APP-ALBUM-NAME")
{
stop = true;
_current_album = group;
SaveFileToCustomAlbum();
}
}
catch (Exception ex)
{
}
}
void SaveFileToCustomAlbum()
{
try
{
if (_current_album != null && !String.IsNullOrEmpty(_local_file_path))
{
_lib.AssetForUrl(new Foundation.NSUrl(_local_file_path), delegate (ALAsset asset)
{
if (asset != null)
{
_current_album.AddAsset(asset);
}
else
{
Console.WriteLine("ASSET == NULL.");
}
}, delegate (NSError assetError)
{
Console.WriteLine(assetError.ToString());
});
}
}
catch (Exception ex)
{
}
}
So this code do:
1) Save video to local folder my video - Method SaveFileToApplicationFolder
2) Then Save video file to Photo library - Method SaveVideo
3) Then Delete file from app folder (in purpose not increase application folder size (app size) --- IF ITS CORRECT logic??
4) Then put assets to Custom Album for my App
SO everything here works well for me......BUT!
I need overtime when user open item - check if he already has video for this item in photos library or not?
And here I'm stack....i just don't understand how i can to check if user has specific video?? I don't find hot to set NAME for ASSETS and hot looking for assets by name...so don't know hot to find this assets....METADATA?? Key_VALUE of object??
Refer to Obj-C Check if image already exists in Photos gallery
In short:
Store assetUrl when saving video with NSUserDefaults
Check if the video exists in Photo library with assetUrl when next time to open it .
You may just want to use xam.plugin.media nuget package. It makes it very easy to take and store videos as well as access the default video picker for selecting existing videos

Remove password and connect with new password wifi android

i would like to ask your help, this is my code :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==REQUEST_CODE_INPUT){
switch (resultCode){
case RESULT_CODE_PASS:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager wifiManager= (WifiManager) getSystemService(Context.WIFI_SERVICE);
pass=data.getStringExtra("passWord");
nameWifi=data.getStringExtra("nameWifi");
WifiConfiguration conf=new WifiConfiguration();
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
List<ScanResult> networkList=wifiManager.getScanResults();
if(networkList !=null){
for(ScanResult network : networkList){
if(network.SSID.startsWith("\"")){
network.SSID=network.SSID.substring(1, network.SSID.length() - 1);
}
if(nameWifi.equals(network.SSID)){
String Capabilities=network.capabilities;
if(Capabilities.contains("WPA2")){
conf.preSharedKey="\""+pass+"\"";
}else if(Capabilities.contains("WEP")){
conf.wepKeys[0]="\""+pass+"\"";
conf.wepTxKeyIndex=0;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
}
break;
}
}
}
wifiManager.addNetwork(conf);
List<WifiConfiguration> list=wifiManager.getConfiguredNetworks();
for(WifiConfiguration i: list){
if(i.SSID!=null && i.SSID.equals("\""+nameWifi+"\"")){
wifiManager.disconnect();
showWaiting();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
if(networkInfo.isConnected()){
dismissWaiting();
}else{
AlertDialog.Builder alert=new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Wrong Password")
.setMessage("Please try again")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.create().show();
}
}
}
break;
}
}
}
i have 2 Activities (MainActivity and ShareWifi), i create Sharewifi with purpose: users input wifi SSID and password then press Enter, both of them will send to MainActivity--> disable current wifi and reconnect with new password but it still uses old password to reconnect. I write this code follow this link : How do I connect to a specific Wi-Fi network in Android programmatically?
Please help me to resolve this problem. Thank you very much.
Resolved: add saveConfiguration and it works
wifiManager.addNetwork(conf);
wifiManager.saveConfiguration();

Jira rest api, add attachment with transition

In jira rest api, we are working with transition api.
By posting on /rest/api/2/issue/{issueIdOrKey}/transitions url with transition id and comments and other fields, we are able to post comments and other fields with state transition.
{
"fields" : {"summary": "Test update 5"},
"transition": { "id": "4"},
"update": {
"comment": [
{
"add": {
"body": "It is time to finish this task"
}
}
]
}
}
Recently we came to know that jira has validation for attachments as well. Means I need to add attachment if I do transition. We are in search of how to add attachment during transition using rest api.
Any help would be really appreciated.
Thanks in advance.
Not sure if it would work during transitions, but here's how to add attachments.
https://docs.atlassian.com/jira/REST/latest/#d2e88
I had to make 2 calls -- first to create the issue and then another POST call to update it with the screenshot as there is no way to add attachments in the create call at all.
I am Not sure about adding attachements with transition(I had never done), but I think can be clubbed. Here is the code to just add an attachment to JIRA, You can use Transition API of JRJC and apply/add some logic in below code to get work done.
Follow link [Listing All JIRA Transitions via API
for updating status based on transition, Hope you may get something from here too.
public void addAttachment(IssueRestClient issueRestClient,
VersionOne versionOne, Issue issue, Epics epic) {
try {
URI attachmentsUri = new URI(
applicationProperties.get(Constants.JIRAURL)
+ "/rest/api/2/issue/" + issue.getKey()
+ "/attachments");
Iterable<Attachment> attachments = issue.getAttachments();
Set<String> existingAttachments = new TreeSet<String>();
String _jiraUser = applicationProperties.get(Constants.JIRAUSER);
String _jiraPwd = applicationProperties.get(Constants.JIRAPWD);
String auth = new String(Base64.encode(_jiraUser + ":" + _jiraPwd));
Set<String> files = new TreeSet<String>();
for (Attachment attachment : attachments) {
for (VAttachements vAttachement : epic
.getAttachement()) {
files.add(vAttachement.getFileName());
}
existingAttachments.add(attachment.getFilename());
}
for (VAttachements vAttachement : epic.getvAttachement()) {
if (!(existingAttachments.contains(vAttachement.getFileName()))) {
Promise<Void> attachmentResult = issueRestClient
.addAttachment(attachmentsUri,
vAttachement.getInputStream(),
vAttachement.getFileName());
attachmentResult.claim();
Constants.REPORT.info(attachmentResult.isDone());
}
}
for (Attachment attachment : attachments) {
for (String checkAttachment : existingAttachments) {
if (!files.contains(checkAttachment))
deleteJiraAttachment(attachment, auth, issue,
checkAttachment);
}
}
} catch (Exception e) {
Constants.ERROR.info(Level.INFO, e);
}
}
-Here Epics is a POJO class which contains attachments to be added in Jira, through getter/ setter method.
private void deleteJiraAttachment(Attachment attachment, String auth,
Issue issue, String jiraFilename) {
URI attachmentURL = attachment.getSelf();
int status;
try {
if (jiraFilename.equalsIgnoreCase(attachment.getFilename())) {
status = invokeDeleteMethod(auth, String.valueOf(attachmentURL));
if (status == 204) {
Constants.REPORT.info("Attachment deleted from Issue"
+ issue.getKey());
} else if (status == 403) {
System.out
.println("attachments for Issue\t "
+ issue.getKey()
+ " is disabled or you don't have permission to remove");
} else if (status == 404) {
Constants.REPORT.info("No attachment is not found for"
+ issue.getKey());
}
}
} catch (AuthenticationException | ClientHandlerException e) {
Constants.ERROR.info(Level.INFO, e);
}
}
private static int invokeDeleteMethod(String auth, String url)
throws AuthenticationException, ClientHandlerException {
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource
.header("Authorization", "Basic " + auth)
.type("application/json").accept("application/json")
.delete(ClientResponse.class);
int statusCode = response.getStatus();
if (statusCode == 401) {
throw new AuthenticationException("Invalid Username or Password");
}
return statusCode;

MonoDroid Get Full Image Path, OnActivityResult

Using OnActivityResult, how do I get the full path of an image? I am using OnActivityResult and I get get a Bitmap. Can I load that info a file somehow? Here is my code:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
try
{
base.OnActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case REQUEST_IMAGE:
if (resultCode == Result.Ok)
{
//Bitmap thumbnail = (Bitmap)data.Extras.Get("data");
//imagePicture.SetImageBitmap(thumbnail);
}
break;
default:
break;
}
}
catch (System.Exception ex)
{
}
}
You could do something like this to write the image out to a file:
var bitmap = (Android.Graphics.Bitmap)data.Extras.Get("data");
using (var stream = File.Create("/path/to/file"))
{
bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, stream);
}

problems in silverlight 4 when using Action callbacks to check for successful file upload

So the async requirement for silverlight ends up in some really convoluted code!!
Im uploading a file just exactly like this answer suggests.
The difference is Im posting the file to an MVC action method. Everything works file except, like I commented on the bottom of that answer, I don't get any callback for when the file DOES NOT successfully upload.
So I created another action method in my mvc app (Services/CheckForFile/{id}) and it returns a string depending on whether the file is found.
Now, how and when do I call this mvc action method is the problem:
void DoUpload() { //Gets call on BtnUpload.Click
//opn is an OpenFileDialog
up.UploadFile(_filename, opn.File.OpenRead(),
e =>
{
//do some ui stuff here.
BeginCheck();// calling this causes PROBLEMS!
});
}
private void BeginCheck()
{
Uploader up = new Uploader();
up.CheckForFile(_filename, success =>
{
if (!success)
{
MessageBox.Show("There was problem uploading the file. Please try again", "Error", MessageBoxButton.OK);
}
});
}
Here is the problem:
When the BeginCheck() function runs, the file, for some reason, NEVER uploads! If I comment it out it does!? It seems like The BeginCheck() runs during the upload or something? Shouldn't it run after!?
How/where would I call BeginCheck() after the upload, to ensure the file has been uploaded?
Here is how I defined the Uploader class:
public class Uploader
{
public void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/UploadFile/" + fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); //this does not block.
callback(null);//this ALWAYS hits!
}
catch (Exception err)
{
if (callback != null)
{
callback(err);
}
}
};
c.OpenWriteAsync(ub.Uri);
}
public void CheckForFile(string filename, Action<bool> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/CheckForFile/" + fileName);
WebClient c = new WebClient();
c.OpenReadCompleted += (sender, e) =>
{
using (StreamReader sw = new StreamReader(e.Result))
{
if (sw.ReadToEnd().Equals("Found", StringComparison.InvariantCultureIgnoreCase))
{
callback(true);
}
else
{
callback(false);
}
}
};
c.OpenReadAsync(ub.Uri);
}
private void PushData(Stream input, Stream output)
{//4KB is not a limitation. We only copy 4Kb at a time from in to out stream
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
I'm embarrased to say that the original answer of mine to which you refer isn't entirely accurate. It seems to work for what the OP wanted but in fact the code doesn't block at the point that I thought it did. In reality what you are actually looking for is the WriteStreamClosed event, its here that you can discover any failure of the request.
Here is an ammended version that works the way you are expecting:-
public void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/UploadFile/" + fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); //this does not block.
}
catch (Exception err)
{
if (callback != null)
callback(err);
}
};
c.WriteStreamClosed += (sender, e) =>
{
if (callback != null)
callback(e.Error);
}
c.OpenWriteAsync(ub.Uri);
}
Now your BeginCheck will only run after the server has responded to the file upload.

Resources