ImageView.setImageURI method does not shown image on android - android-imageview

I am listing contacts with photo but i could not shown the photos of contacts. I get the photo uri as following:
ContentResolver cr = getContentResolver();
// Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null,null );
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
photo_id = cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
Log.e("name", name);
Log.e("Photo_id", ""+photo_id);
photo = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, photo_id);
Log.e("URI", ""+photo);
image.setImageURI(photo); // Does not shown image.
...
}
}
A sample uri(printed in Log):
content://com.android.contacts/contacts/52
i do not know the reason why uri is not shown the images. please help me.

i have solved my problem using bitmap. the imageView.setImageURI is not used for me. so that is use the following code instead of setImageURI.
private Bitmap loadContactPhoto(ContentResolver cr, int id) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
Here id is the contact id , not photo id of the contact.

Related

Cannot add row without complete selection of batch/serial numbers

ERROR: (-4014) Cannot add row without complete selection of batch/serial numbers.
The default function of DI API SaveDraftToDocument() is working fine on MS SQL Database but not SAP HANA.
I am posting the Delivery document with Serial Numbers.
SAPbobsCOM.Documents oDrafts;
oDrafts = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);
oDrafts.GetByKey(Convert.ToInt32(EditText27.Value));
var count = oDrafts.Lines.Count;
var linenum = oDrafts.Lines.LineNum;
//Validation
#region
var RsRecordCount = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
var sQryRecordCount = String.Format("Select * from \"SANTEXDBADDON\".\"#TEMPITEMDETAILS\" where \"U_DraftNo\" = '{0}'", EditText27.Value);
RsRecordCount.DoQuery(sQryRecordCount);
#endregion
if (count == RsRecordCount.RecordCount)
{
//LINES
string ItemCode = "", WhsCode = ""; double Quantity = 0; int index = 0;
for (int i = 0; i < oDrafts.Lines.Count; i++)
{
oDrafts.Lines.SetCurrentLine(index);
ItemCode = oDrafts.Lines.ItemCode;
//SERIAL NUMBERS
var RsSerial = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
string table = "\"#TEMPSERIALS\"";
var sQrySerial = String.Format(
"Select \"U_ItemCode\" , \"U_DistNumber\" from \"SANTEXDBADDON\".\"#TEMPSERIALS\" where " +
"\"U_DraftNo\" = '{0}' and \"U_ItemCode\" = '{1}'", EditText27.Value, ItemCode);
RsSerial.DoQuery(sQrySerial);
int serialindex = 1, lineindex = 0;
#region
if (RsSerial.RecordCount > 0)
{
while (!RsSerial.EoF)
{
//OSRN SERIALS
var RsSerialOSRN = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
var sQrySerialOSRN = String.Format(
"Select * from OSRN where \"DistNumber\" = '{0}' and \"ItemCode\" = '{1}'"
, RsSerial.Fields.Item("U_DistNumber").Value.ToString(), ItemCode);
RsSerialOSRN.DoQuery(sQrySerialOSRN);
oDrafts.Lines.SerialNumbers.SetCurrentLine(0);
oDrafts.Lines.SerialNumbers.BaseLineNumber = oDrafts.Lines.LineNum;
oDrafts.Lines.SerialNumbers.SystemSerialNumber =
Convert.ToInt32(RsSerialOSRN.Fields.Item("SysNumber").Value.ToString());
oDrafts.Lines.SerialNumbers.ManufacturerSerialNumber =
RsSerialOSRN.Fields.Item("DistNumber").Value.ToString();
oDrafts.Lines.SerialNumbers.InternalSerialNumber =
RsSerialOSRN.Fields.Item("DistNumber").Value.ToString();
oDrafts.Lines.SerialNumbers.Quantity = 1;
if (RsSerial.RecordCount != serialindex)
{
Application.SBO_Application.StatusBar.SetText("INTERNAL NO " + oDrafts.Lines.SerialNumbers.InternalSerialNumber, SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
oDrafts.Lines.SerialNumbers.Add();
serialindex++;
lineindex++;
}
RsSerial.MoveNext();
}
}
#endregion
index++;
}
var status = oDrafts.SaveDraftToDocument();
if (status == 0)
{
oDrafts.Remove();
Application.SBO_Application.StatusBar.SetText("Delivery Posted Successfully !", SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
}
else
{
int code = 0; string message = "";
oCompany.GetLastError(out code, out message);
Application.SBO_Application.SetStatusBarMessage(message, SAPbouiCOM.BoMessageTime.bmt_Medium, true);
}
}`
The error you have posted explains the problem. You are trying to deliver products but have not included all of the serial/batch numbers.
I don't think there's enough information to be sure where this problem happens, but here are some pointers:
You are reading the serial numbers from a custom table. Are the values you are reading valid? For example, could another user have added them to a different order? Could the values be for a different product?
Are you specifying the correct quantity of serial numbers? Is it possible that the item quantity on the line is more than the number of serial numbers you are adding?
Believe the error message until you can prove it's wrong. It doesn't seem like this is a HANA issue (we use HANA extensively) it's a logical problem with the data you are providing.
You may want to capture more debugging information to help you if you can't easily identify where the problem is.

How to create a apex test class for my apex class

It is my first apex class and i don't really know how to implement a proper test class.
My goal is to achieve test coverage of 75%.
I updated based on the comments but i managed to achieve only 70 %. I don't have other idea how to improve this more.
Here is what i did :
Apex class:
public with sharing class AccountController {
#AuraEnabled
public static List<Account> findAll() {
User userDetails =[SELECT Id, Name, Email, Profile.Name, UserRole.Name FROM User
where Id=:userinfo.getUserId() ];
// Theme4t is theme that is used by mobille app for android or iphone
if(((userDetails.UserRole.Name).equals('yon')|| (userDetails.UserRole.Name).equals('bon')|| (userDetails.UserRole.Name).contains('non')
|| (userDetails.UserRole.Name).contains('go')) && UserInfo.getUiTheme() != 'Theme4t'){
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity
FROM Account
WHERE ShippingLatitude != NULL AND ShippingLongitude != NULL
LIMIT:22000];
}else {
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity
FROM Account
WHERE OwnerId =: UserInfo.getUserId() AND ShippingLatitude != NULL AND ShippingLongitude != NULL
LIMIT:5000];
}
}
Apex test class:
#isTest
public class AccountControllerTest
{
static testMethod void testMethod1()
{
Account acc = new Account();
acc.Name='Test';
insert acc;
User userDetails =[SELECT Id, Name, Email, Profile.Name, UserRole.Name FROM User
where Id=:userinfo.getUserId() ];
List<Account> lstAcc = AccountController.findAll();
UserRole ur =new UserRole();
userDetails.UserRoleId=[select Id from UserRole where Name='yon'].Id;
System.runAs(userDetails){
List<Account> lstAcc1 = AccountController.findAll();
}
userDetails.UserRoleId=[select Id from UserRole where Name='bon'].Id;
System.runAs(userDetails){
List<Account> lstAcc2 = AccountController.findAll();
}
userDetails.UserRoleId=[select Id from UserRole where Name='non'].Id;
System.runAs(userDetails){
List<Account> lstAcc3 = AccountController.findAll();
}
userDetails.UserRoleId=[select Id from UserRole where Name='go'].Id;
System.runAs(userDetails){
List<Account> lstAcc4 = AccountController.findAll();
}
}
Please complete the below trailhead to learn the unit test in Salesforce.
https://trailhead.salesforce.com/en/content/learn/modules/apex_testing/apex_testing_intro
And also as you are trying to create a user after account insertion it will throw Mixed DML error. you need to use system.runAs() method. follow the below URL for using the method.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_runas.htm
Let me know if still, you need any help on this.
Here is the code for your class and test class. Please follow the best practices from http://blog.shivanathd.com/2013/11/Best-Practices-Test-Class-in-Salesforce.html
This time I am providing the code to you to understand how to create a test class, but next time onwards please follow the steps and documents I have shared.
public with sharing class AccountController {
//using a test visible variable for setting the ui theme check.
#TestVisible static Boolean isTheme4t = UserInfo.getUiThemeDisplayed() == 'Theme4t';
#AuraEnabled
public static List<Account> findAll() {
User userDetails =[SELECT Id, Name, Email, Profile.Name, UserRole.Name FROM User where Id=:userinfo.getUserId()];
// Theme4t is theme that is used by mobille app for android or iphone
if(((userDetails.UserRole.Name).equals('yon')|| (userDetails.UserRole.Name).equals('bon')|| (userDetails.UserRole.Name).contains('non') || (userDetails.UserRole.Name).contains('go')) && !isTheme4t){
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity FROM Account WHERE ShippingLatitude != NULL AND ShippingLongitude != NULL LIMIT 22000];
}else {
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity FROM Account WHERE OwnerId =: UserInfo.getUserId() AND ShippingLatitude != NULL AND ShippingLongitude != NULL LIMIT 5000];
}
}
}
#isTest
public class AccountControllerTest
{
//Use setup data method to create data and query it in testmethod
#testSetup static void setup() {
UserRole r = new UserRole(DeveloperName = 'yon', Name = 'yon');
insert r;
User u = new User(
ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
LastName = 'last',
Email = 'puser000#amamama.com',
Username = 'puser000#amamama.com' + System.currentTimeMillis(),
CompanyName = 'TEST',
Title = 'title',
Alias = 'alias',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
UserRoleId = r.Id
);
insert u;
System.runAs(u){
Account acc = new Account();
acc.Name = 'Test Account';
acc.ShippingLatitude = 75.46;
acc.ShippingLongitude = 45.46;
acc.AccountStatus__c = 'test';
insert acc;
}
}
static testMethod void testMethod1(){
user u = [select Id from User where email = 'puser000#amamama.com' limit 1];
system.runAs(u){
Test.startTest();
List<Account> acc = [select Id,AccountStatus__c,ShippingLatitude,ShippingLongitude from Account where Name = 'Test Account'];
List<Account> lstAcc4 = AccountController.findAll();
system.assert(lstAcc4.size()>0);
Test.stopTest();
}
}
static testMethod void testMethod2(){
user u = [select Id from User where email = 'puser000#amamama.com' limit 1];
system.runAs(u){
AccountController.isTheme4t = true;
Test.startTest();
List<Account> acc = [select Id,AccountStatus__c,ShippingLatitude,ShippingLongitude from Account where Name = 'Test Account'];
List<Account> lstAcc4 = AccountController.findAll();
system.assert(lstAcc4.size()>0);
Test.stopTest();
}
}
}

ASP.net Entity Framework Check if exists in database

I have VS2015, entity framework 6. I have a database with one table (Logins)
FirstName, lastName, Birthdate, email, password
I also have a textbox(s), button
tbEmail tbpass and btnLogin
How do I check if the users email in the textbox matches one in the database?
So far I have:
protected void btnLogin_Click(object sender, EventArgs e)
{
Logins Log = new Logins();
using (LoginDataEntities lg = new LoginDataEntities())
{
string #email = tbUsernameL.Text;
string #password = tbPassL.Text;
var logged = from L in lg.Logins
where L.Username == #email
&& L.Pass == #password
select L.Username;
if (logged != null)
{
lblSuccess.Visible = true;
}
else
{
lblFail.Visible = true;
}
}
}
However, its not working and always enables the success label. How do I fix this?
Try it once with the following snippet:
using (LoginDataEntities lg = new LoginDataEntities())
{
string #email = tbUsernameL.Text;
string #password = tbPassL.Text;
var logged = lg.Logins
.SingleOrDefault(l=> l.Username == #email && l.Pass == #password);
if (logged != null) // update
{
lblSuccess.Visible = true;
}
else
{
lblFail.Visible = true;
}
}
Alternatively, can you also look at the following example again:
http://www.c-sharpcorner.com/uploadfile/b19d5a/custom-user-login-and-registration-page-in-Asp-Net-mvc3-with-razor-and-entity-framework/
Or you refactorisiers the VS template with Individual User Accounts

G+ Domain API Google Apps Script Public Posts Scan

I'm running a script that scans our domain users G+ posts and flags any post shared publicly and then sends an email notification with a link to the post to the end user. The script was written by someone else who is no longer with the company. I want to change the script so that it will flag any post that does not have "domainRestricted";True.
Here's an output of a scanned post with the type of access associated "domainRestricted":True. This post is shared within the domain.
{
"description":"Shared privately",
"domainRestricted":true,
"kind":"plus#acl"
}
Here's an output example of a scanned post without domainRestricted access. This post is shared with a Circle containing users outside of the domain, essentially Public.
{
"description":"Shared privately",
"kind":"plus#acl"
}
Here's an output example of a scanned post with Public as the access. This post was explicitly shared publicly.
{
"items":[{"type":"public"}],
"description":"Public",
"kind":"plus#acl"
}
I want to change this code, to scan for any posts that does not contain the access "domainRestricted":True.
function checkPublicPosts( userId ) {
var publicPosts = Array();
var pageToken;
try {
do {
Logger.log( 'Scanning posts by ' + userId );
// Search for all Google Plus posts by userId
posts = PlusDomains.Activities.list( userId, 'user', {
maxResults: 100,
pageToken: pageToken
});
// If posts are found, check to see if they are public
if( posts.items ) {
for( var i = 0; i < posts.items.length; i++ ) {
var post = posts.items[i];
var public = false;
if( !post.access.domainRestricted && ( typeof( post.access.items ) != 'undefined' ) ) {
for( var j = 0; j < post.access.items.length; j++ ) {
if( post.access.items[j].type = 'public' ) {
public = true;
j = post.access.items.length;
}
}
}
// If a post is public, add it to the list of public posts for userId
if( public ) publicPosts.push( post );
}
}
// If user has more than 100 posts, continue with the analysis of subsequent batches of 100
pageToken = posts.nextPageToken;
} while (pageToken);
} catch( err ) {
// The code above sometimes fails for unexpected reasons. We
// log this error.
Logger.log( 'Failed on ' + userId + ' with error ' + err );
}
return publicPosts;
}
Can anyone help me?

WCF method's breakpoint not being hit

I am new to WCF and I am building a service to do CRUD operations. I have created a new void method that takes two parameters. I have set a breakpoint and in debugging mode I have pasted this URL:
http://localhost:55152/WcfDataService.svc/AddNewNote()?ParamNoteTitle='dfdfdf'&ParamNoteText='dfdfdfdf'
This is my code:
[WebGet]
public void AddNewNote(string ParamNoteTitle, string ParamNoteText)
{
//My hardcoded values for now...
int ParentID = 8879;
int JobID = 1000088150;
int ContactID = 309;
Guid UserID = Guid.NewGuid();
string RelatedType = "Advertiser Contact";
bool IsShared = true;
tblNote N = new tblNote
{
NotesTitle = ParamNoteTitle,
NotesText = ParamNoteText,
ParentID = ParentID,
ContactID = ContactID,
JobID = JobID,
UserID = UserID,
GroupID = null,
RelatedType = RelatedType,
IsShared = IsShared
};
this.CurrentDataSource.tblNotes.Add(N);
this.CurrentDataSource.SaveChanges();
}
I am getting a 404 error. Is there a problem with my query string/URL?
First of all, check if the service itself is running correctly by pasting this URL in your browser:
http://localhost:55152/WcfDataService.svc
If so, I would recommend you to have a look at this similar SO question.
Hope that helps!
I ended up changing my method type to IQueryable and calling a method to retrieve the new row with my ID after the insert. I originally wanted to return an integer or bool so in my Javascript I can handle success or failure by looking at the return value.
[WebGet]
public IQueryable<vw_Note> AddNewNote(string ParamNoteTitle, string ParamNoteText)
{
//My hardcoded values for now...
int ParentID = 8879;
int JobID = 1000088150;
int ContactID = 309;
Guid UserID = new Guid("8b0e303a-68aa-49a5-af95-d994e2bdd5ac");
Guid NoteID = Guid.NewGuid();
string RelatedType = "Advertiser Contact";
bool IsShared = true;
tblNote N = new tblNote
{
NotesID = NoteID,
NotesTitle = ParamNoteTitle,
NotesText = ParamNoteText,
ParentID = ParentID,
ContactID = ContactID,
JobID = JobID,
UserID = UserID,
GroupID = null,
RelatedType = RelatedType,
IsShared = IsShared
};
try
{
this.CurrentDataSource.tblNotes.Add(N);
this.CurrentDataSource.SaveChanges();
return GetNoteByID(NoteID);
}
catch (Exception ex)
{
return GetNoteByID(NoteID);
}
}
As you can see it will return a set of data. I was stuck on how to handle inserting data using WCF and then responding to a client request but I managed to solve it. Thanks anyway!