I am creating a hybrid mobile app, using Xamarin.Forms.
I want the user to click a button and the contact in the app gets inserted into the phone's contacts, including the profile picture.
So far, everything on the iOS side is working. I successfully insert the profile picture.
I can't get it to work on Android though. I've already tried looking on here but all solutions use Java. Inserting the name, number and e-mail works perfectly.
Here is my code so far:
public void SaveContacts(string name, string number, string email, string job, string company, byte[] imageData)
{
try
{
var intent = new Intent(Intent.ActionInsert);
intent.SetType(ContactsContract.Contacts.ContentType);
if (!string.IsNullOrWhiteSpace(name))
intent.PutExtra(ContactsContract.Intents.Insert.Name, name);
if (!string.IsNullOrWhiteSpace(number))
intent.PutExtra(ContactsContract.Intents.Insert.Phone, number);
if (!string.IsNullOrWhiteSpace(email))
intent.PutExtra(ContactsContract.Intents.Insert.Email, email);
if (imageData.Length != 0)
{
// INSERT PROFILE PICTURE HERE
}
Platform.CurrentActivity.StartActivity(intent);
}
catch (Exception ex)
{
DependencyService.Get<ILogger>()?.Error(ex);
}
}
How do I add the profile picture to the contact?
According to this case which is about Insert Contact (ContactsContract) via Intent with Image (Photo), you need to use the intent.putParcelableArrayListExtra(Insert.DATA, data) method to add the photo to the new contact.
But I have create a sample to test it. This method have a bug. I use the following code:
List<ContentValues> data = new List<ContentValues>();
ContentValues row1 = new ContentValues();
Intent intent = new Intent(Intent.ActionInsert);
intent.SetType(ContactsContract.Contacts.Photo);
intent.PutParcelableArrayListExtra(ContactsContract.Intents.Insert.Data, data);
But it will show the type convert error. Even though the class ContentValues is inherited from the IParcelable interface. The error still show. You can report it to the xamarin on the github.
In addition, I also try to use the method about using the content provider to insert a contact. But the RawContacts doesn't have ACCOUNT_TYPE property.
So for the bug, it seems you can't add profile picture to contacts with the native api.
Related
I want to know can ı search youtube or another application on my application.
String s=" hi ";
Intent intent= new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/results?search_query=" + s));
startActivity(intent);
I can search using this code for youtube web site but I want to search in youtube android application (com.google.android.youtube ) . I will use below code for voice search .
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
String text =mVoiceInputTv.getText().toString();
String filename = text; // full file name
String[] parts = filename.split("\\ "); // String array, each element is text between spaces
String beforeFirstSpace = parts[0]; // Text before the first space
if(beforeFirstSpace.equalsIgnoreCase("Youtube")) {
Intent intent = new Intent(getPackageManager().getLaunchIntentForPackage("com.google.android.youtube"));
intent.setAction(Intent.ACTION_SEARCH);
intent.putExtra(SearchManager.QUERY,text);
startActivity(intent);
finish(); System.exit(0);
}
With this code I open the youtube application but I can't search in application.
You can't do it easily since other apps may (and most likely) offer another API that is different than youtube.
For example:
youtube search API:
https://www.youtube.com/results?search_query=facebook
facebook search API:
http://www.facebook.com/search/web/direct_search.php?q=%gmail
gmail search API:
Gmail: http://mail.google.com/mail/?search=query&view=tl&start=0&init=1&fs=1&q=%youtube
You see there is a different pattern. Thus, you need to implement it manually, 1 by 1, and according to the search API offered by every single app.
I am using the Salesforce SDK (4.1.x) in a native Android app. I use the RestClient.sendAsync method to post my form data to a custom object. That part is working fine. Now I need to upload and attach a photo that was taken by the mobile user. I see that RestClient has an uploadFile method. Is this the correct method? If so then how do I connect the uploaded file to the custom form data?
Ok. I figured this out. First, create the parent object (the main form data) using the following.
request = RestRequest.getRequestForCreate(apiVersion, objectType, fields);
client.sendAsync(restRequest, new RestClient.AsyncRequestCallback() {...
In the onSuccess method you will get the id of the new object from the response. There are plenty of examples that show how to get the JSON object and the id. Armed with this parentId we can now create the attachment. The code looks something like this.
private void postImageAsAttachment(String parentId, String title) {
Map<String, Object> fields = new HashMap<String, Object>();
fields.put("Name", title);
fields.put("ParentId", parentId);
fields.put("Body", ImageHelper.getBase64FromImage(mCurrentPhotoPath));
RestRequest request = null;
try {
request = RestRequest.getRequestForCreate(apiVersion, "Attachment", fields);
} catch (Exception ex) {
Log.d(TAG, "sendRequest: ", ex);
Toast.makeText(MainActivity.this, "The file upload failed: " + ex.toString(), Toast.LENGTH_LONG).show();
}
client.sendAsync(request, new RestClient.AsyncRequestCallback() {...
I'm using a simple class called ImageHelper that simply loads the image file, performs image compression (if necessary), and base64 encodes the image data. The result is that an "Attachment" object is created as a child of the parent object.
I hope this helps the next person.
I am integrating dropbox to my android app its working fine but, i am facing the one problem .I am insert the one record programatically record inserted dropbox its worked fine .
How to update data in dropbox.
I am using the following code to insert dropbox
DbxFields taskFields = new DbxFields();
taskFields.set("completed", false);
taskFields .set("taskname", taskName);
taskFields.set("taskaddress", taskaddress);
taskFields.set("taskphone", taskPhone);
taskFields.set("created", new Date());
mTable.insert(taskFields);
mDatastore.sync();
i dn't know how to update the above inserted record.please guide me anyone know.Adavance thanks to all
Let's take the following example and let's assume that you want to change the completed-value of the task with the name XYZ to true.
DbxTable mTable = store.getTable("YOUR_TABLE_NAME");
DbxFields mQueryFields = new DbxFields();
mQueryFields.set("taskname", "XYZ");
try {
QueryResult mResults = mTable.query(mQueryFields);
Iterator<DbxRecord> iter = mResults.iterator();
while (iter.hasNext()) {
DbxRecord record = iter.next();
DbxFields mUpdateFields = new DbxFields();
mUpdateFields.set("completed", true);
record.setAll(mUpdateFields);
}
} catch (DbxException e) {
e.printStackTrace();
}
store.sync();
Note: Since I'm using a while-loop this code would change the completed-value of all tasks named "XYZ"
Edit
If you try to edit only one property there's actually no need to create sa new DbxFieldsobject, just call this:
record.set(PROPERTY, VALUE);
story.sync();
I have made a lot of combinations to get this working but I'm always getting an empty json, however in the Graph API Explorer it works very well, I'm using this statement to get the id of the albums from a X user:
SELECT aid from album WHERE owner = XXXXXXXXXX
it is returning (for example):
{
"data": [
{
"aid": "xxxxxxx_xxxx"
},
{
"aid": "xxxxxxxx_xxx"
}
]
}
in the drop down menu (where normally is Graph Api explorer selected) I have changed for my app, also I'm using the button "get access token" and selecting: "user_photos","friends_photos","user_friends" permissions,
but in my android app only I retrieve an empty json, (note: I have used another statement to recover user data (such as birthday) with this code, and works fine so code is correct, note2: I'm using the "user_photos","friends_photos","user_friends" permissions inside the app).
the code of the app (the fragment) is:
mynewbutton = (Button) view.findViewById(R.id.mynewbutton);
mynewbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
String fqlQuery = "SELECT aid from album WHERE owner = XXXXXXXXX";
Bundle params = new Bundle();
params.putString("q", fqlQuery);
Session session = Session.getActiveSession();
// params.putString("access_token", session.getAccessToken());
Request request = new Request(session,
"/fql",
params,
HttpMethod.GET,
new Request.Callback(){
public void onCompleted(Response response) {
//Log.i(TAG, "Result: " + response.toString());
}
});
Request.executeBatchAsync(request);
}
});
Possible the reason is cuz I'm not getting the "valid access_token" inside the app.
So it came some questions in mind:
1.-How do I get the access_token?
2.-Do I need to use the method getAccessToken()?
3.-If so, How do I integrate in my code?
4.-Is it necessary to change something in the Graph Api Explorer in order to get working well in the app?
5.- Am I missing something (a step or a piece of code for example)?
6.-In general, How do I get the aid from album inside my app just like in the Graph Api Explorer? thanks.
I am currently developing an Android application using Flex 4.5.1 and I am having an issue when trying to pass data that I have stored in a SharedObject array to my Web Service for a Database query. the code below shows how I am storing the data in the SharedObject:
var so:SharedObject = SharedObject.getLocal("app");
public var prefsArray:ArrayCollection = new ArrayCollection(so.data.prefs);
protected function prefs_btn_click(event:MouseEvent):void
{
prefsArray.source.push(getFrsByIDResult.lastResult.id);
so.data.prefs = [prefsArray];
var flushStatus:String = so.flush();
if (flushStatus != null) {
switch(flushStatus) {
case SharedObjectFlushStatus.PENDING:
so.addEventListener(NetStatusEvent.NET_STATUS,
onFlushStatus);
break;
case SharedObjectFlushStatus.FLUSHED:
trace("success");
break;
}
}
}
protected function onFlushStatus(event:NetStatusEvent):void
{
trace(event.info.code);
}
I have tested the SharedObject to see if the information is being entered into it correctly and all seems fine. Now I have used the code below in order to retrieve the data from the SharedObject and try and send it to the PHP web Service to run the DB query.
var so:SharedObject = SharedObject.getLocal("app");
var arrCol:ArrayCollection = new ArrayCollection(so.data.prefs);
var str:String = new String(arrCol.toString());
protected function list_creationCompleteHandler(event:FlexEvent):void
{
getPrefsByprefIdsResult.token = prefsService.getPrefsByPrefIds(so.data.prefs);
}
I have tested the Webservice in Flex and have it configured to recieve an Array of Ints (int[]) and it works when i run a test operation on it with two dummy values. However when I try to use the code above to pass the Web Service the Shared Object data I get this error:
TypeError: Error #1034: Type Coercion failed: cannot convert []#97e97e1 to mx.collections.ArrayCollection.
at views::**************/list_creationCompleteHandler()[C:\Users\Jack\Adobe Flash Builder 4.5\****************\src\views\*******************.mxml:25]
at views::*********************/__list_creationComplete()[C:\Users\Jack\Adobe Flash Builder 4.5\****************\src\views\***************.mxml:94]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.core::UIComponent/dispatchEvent()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:13128]
at mx.core::UIComponent/set initialized()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:1818]
at mx.managers::LayoutManager/validateClient()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:1090]
at mx.core::UIComponent/validateNow()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:8067]
at spark.components::ViewNavigator/commitNavigatorAction()[E:\dev\4.5.1\frameworks\projects\mobilecomponents\src\spark\components\ViewNavigator.as:1878]
at spark.components::ViewNavigator/commitProperties()[E:\dev\4.5.1\frameworks\projects\mobilecomponents\src\spark\components\ViewNavigator.as:1236]
at mx.core::UIComponent/validateProperties()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:8209]
at mx.managers::LayoutManager/validateProperties()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:597]
at mx.managers::LayoutManager/doPhasedInstantiation()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:783]
at mx.managers::LayoutManager/doPhasedInstantiationCallback()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:1180]
I have replaced certain filenames and locations with *'s to protect the work i am doing, but can someone please help me with this issues as I believe it has to be something simple???
Thanks
ok so let me explain in more detail. This is being designed for an Android app like I said, but image what I am trying to do is to store Bookmarks persistently using the Local Shared Object.
The first chunck of code you see above is designed to create the LSO attribute for the bookmark i want to create and imagine that there can be more than one bookmark set at different times like in a web browser. The only way i could find to do this was to store these items/details in an array which I retrieve and then update before saving back to the LSO and saving.
The second piece of code related to imagine a "Bookmarks Page" with a list of all the content that I have bookmarked. Now what I wanted to happen was thta I would be able to call up the LSO attribute which held the id's of the bookmarks and then load up thier details in a list format.
I have managed to create the LSO and store the bookmark deatils in and allow them to be updated and entries added. Also I have made sure that the PHP code that I have pulls back all the database objects relating to the array of id's and this has been tested using flex. The only thing that I cant seem to do is to pass the id's to the PHP web service file. The code in the Web Service file is below if that helps:
public function getPrefsByPrefIds($PrefIds) {
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE $this->tablename.id IN(" .implode(",", $PrefIds). ")");
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$rows = array();
mysqli_stmt_bind_result($stmt, $row->id, $row->name, $row->desc);
while (mysqli_stmt_fetch($stmt)) {
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->id, $row->name, $row->desc);
}
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
return $rows;
}
Yes I had already tried that but thanks. I have made some more progress on my own as I have been experimenting with the different types of objects that can be stored in SharedObjects. I have managed to get the solution part working with this code:
This code is designed to capture the boomark info and store it in an arrayCollection before transferring it to a bytesArray and saving
var so:SharedObject = SharedObject.getLocal("app");
public var prefArray:ArrayCollection = new ArrayCollection(so.data.prefs);
protected function prefs_btn_click(event:MouseEvent):void
{
prefArray.source.push(getCompaniesByIDResult.lastResult.id);
so.data.prefs = [prefArray];
var bytes:ByteArray = new ByteArray();
bytes.writeObject(prefArray);
so.data.ac = bytes;
var flushStatus:String = so.flush();
if (flushStatus != null) {
switch(flushStatus) {
case SharedObjectFlushStatus.PENDING:
so.addEventListener(NetStatusEvent.NET_STATUS,
onFlushStatus);
break;
case SharedObjectFlushStatus.FLUSHED:
trace("success");
break;
}
}
}
protected function onFlushStatus(event:NetStatusEvent):void
{
trace(event.info.code);
}
This next code is the designed to retrieve that information from the SahredObjects bytesArray and put it back into an Array Collection
var so:SharedObject = SharedObject.getLocal("app");
var ba:ByteArray = so.data.ac as ByteArray;
var ac:ArrayCollection;
protected function list_creationCompleteHandler(event:FlexEvent):void
{
ba.position = 0;
ac = ba.readObject() as ArrayCollection;
getPrefsByPrefIdsResult.token = prefsService.getPrefsByPrefIds(ac);
}
however as I have said this works in a small way only as if I store only one Bookmark (id) for an item and then go to the bookmarks list the details for that bookark are successfully retrieved, however if I save more than one Bookmark(2 or more id's) the page will not load the details, i do not get an error but I believe it is hanging because it is looking for say id's "1,2" instead of "1" and "2" but i dont know why this is or how to resolve this. I appreciate the advice I have been given but am finding it hard there is no one who can help me with this issue and I am having to do various experiemnts with the code. Can someone please help me with this I would really appreciate it :-) Thanks