Updating Nickname field in Android Contact DB - java

I am trying to update nickname of a contact but not able to do so.
Below is the code which I have written
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<android.content.ContentProviderOperation>();
String selectArgs1 = Data.CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ? ";
String[] selectArgs2 = new String[]{ContactId, "vnd.android.cursor.item/nickname"};
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(selectArgs1, selectArgs2)
.withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname)
.build());
ContentProviderResult [] cpResArr = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
int j=cpResArr.length;
System.out.println(j);
Toast.makeText(getApplicationContext(), "value is updated", Toast.LENGTH_LONG).show();**

I got it worked, below is the piece of code which worked for me.
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValue(Data.RAW_CONTACT_ID, ContactId)
.withValue(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE)
.withValue(Nickname.NAME, "Sister")
.withValue(Nickname.TYPE, Nickname.TYPE_CUSTOM)
.withValue(Nickname.LABEL, "Sister")
.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
We need to obtain builder object and than add it to arraylist before calling applybatch.
Refer the following link for further info: http://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.Nickname.html

Related

NumberFormatException: null

I am getting this error:NumberFormatException: null when I am trying to add score/points to my app.
I created separated table for this because I need multiple tables .
I have no clue what the problem is so thanks to you all.
if(count==4) {
my_db=new DBHelper(this);
sqdb = my_db.getWritableDatabase();
Cursor c_oldPoints= sqdb.query(DBHelper.TABLE_NAME2,null,DBHelper.NICKNAME+"=?",new String[]{Username},null,null,null);
int col_Points=c_oldPoints.getColumnIndex(DBHelper.POINTS);
c_oldPoints.moveToFirst();
while (!c_oldPoints.isAfterLast())
{
OldPoints=c_oldPoints.getString(col_Points);
c_oldPoints.moveToNext();
}
sqdb.close();
int OldP = Integer.parseInt(OldPoints);
OldP+=countPoints;
String SoldP = Integer.toString(OldP);
my_db=new DBHelper(this);
sqdb = my_db.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(my_db.POINTS,SoldP);
Cursor c = sqdb.query(DBHelper.TABLE_NAME2,null,DBHelper.NICKNAME+"=?",new String[]{Username},null,null,null);
c.moveToFirst();
while (!c.isAfterLast())
{
sqdb.update(DBHelper.TABLE_NAME2,cv, DBHelper.POINTS+"=?",new String[]{OldPoints});
c.moveToNext();
}
sqdb.close();
countPoints=0;
}
This is the logcat :-
2019-05-15 18:18:14.101 8513-8513/com.example.user.soundsequ E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.soundsequ, PID: 8513
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:483)
at java.lang.Integer.parseInt(Integer.java:556)
at com.example.user.soundsequ.Game.onClick(Game.java:353)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
The error appears to be in this line
int OldP = Integer.parseInt(OldPoints);
The error is saying that the value of OldPoints is not a string that can be converted to an integer e.g. if it were A or null;
As such either a value extracted from the POINTS column is not a numeric or the value of Username does not match the column NICKNAME in a row. In which case OldPoints will be whatever value it has been set to before the loop.
As the data itself is not available you need to ascertain which of the two situations is causing the issue.
I'd suggest adding some Logging in to determine which.
e.g. by using something like :-
OldPoints = "my debugging value";
Log.d("MYDEBUGGING","OldPoints, before doing anything is " + OldPoints);
Cursor c_oldPoints= sqdb.query(DBHelper.TABLE_NAME2,null,DBHelper.NICKNAME+"=?",new String[]{Username},null,null,null);
int col_Points=c_oldPoints.getColumnIndex(DBHelper.POINTS);
c_oldPoints.moveToFirst();
while (!c_oldPoints.isAfterLast())
{
OldPoints=c_oldPoints.getString(col_Points);
c_oldPoints.moveToNext();
Log.d("MYDEBUGGING","Extracted the value " + OldPoints + " from position + String.valueOf(c_oldPoints.getPosition());
}
sqdb.close();
Log.d("MYDEBUGGING","Trying to convert the value " + OldPoints + " to an integer");
int OldP = Integer.parseInt(OldPoints);
You could also not make the above changes and add a breakpoint (on the line initially indicated) and then use Run/Debug App and inspect the variables (or use multiple breakpoints at suitable places). You may find this useful in regard to debugging Debug your app.
The following code protects against the exception and also protects against an attempt being made to update a non-existent user :-
if (count == 4) {
SQLiteDatabase sqdb = my_db.getWritableDatabase();
Cursor c_oldPoints= sqdb.query(
DBHelper.TABLE_NAME2,null,
DBHelper.NICKNAME+"=?",
new String[]{Username},
null,null,null
);
int col_Points=c_oldPoints.getColumnIndex(DBHelper.POINTS);
if (c_oldPoints.moveToFirst()) {
Oldpoints = c_oldPoints.getString(col_Points);
//Oldpoints = "oops";
int OldP = 0;
boolean can_convert_to_int = true;
try {
OldP = Integer.parseInt(Oldpoints) + countPoints;
can_convert_to_int = true;
} catch (NumberFormatException e) {
e.printStackTrace(); //TODO not necessary probably remove. just for checking the log
}
if (can_convert_to_int) {
ContentValues cv = new ContentValues();
cv.put(DBHelper.POINTS,OldP);
sqdb.update(DBHelper.TABLE_NAME2,cv, DBHelper.NICKNAME + "=?", new String[]{Username});
}
} else {
Log.d("NICKNAMENOTFOUND","No row was found when attemtping to get the old score for User " + Username);
}
}
However
I would suggest that you add a couple of methods to your DBHelper class, these being :-
public int increasePoints(String user, int points_to_add) {
SQLiteDatabase db = this.getWritableDatabase();
SQLiteStatement sql = db.compileStatement(
"UPDATE " + TABLE_NAME2 +
" SET " + POINTS + "=" + POINTS + " +? " +
"WHERE "+ NICKNAME + "=?"
);
sql.bindLong(1,points_to_add);
sql.bindString(2,user);
return sql.executeUpdateDelete();
}
public int getPoints(String user) {
SQLiteDatabase db = this.getWritableDatabase();
int rv = -1;
String whereclause = NICKNAME + "=?";
String[] whereargs = new String[]{user};
Cursor csr = db.query(TABLE_NAME2,new String[]{POINTS},whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(POINTS));
}
csr.close();
return rv;
}
The first method increasePoints performs the change to the points via an UPDATE sql statement and does away for the need to convert the points extracted as a string to an integer. It returns the number of rows that have been updated (1 if the NICKNAME column is always a unique value, 0 if nothing was updated).
The second method getPoints does as it says, it gets the points for the given user, if the user doesn't exist it will return -1.
Your code could then be :-
if (count == 4) {
boolean updated = false; //TODO remove when happy
int old_points = my_db.getPoints(Username); //TODO remove when happy
if (my_db.increasePoints(Username,countPoints) > 0) {
updated = true;
}
int new_points = my_db.getPoints(Username); //TODO remove when happy
//TODO remove following code when happy
String result = "The result of the attempt to update the points for user " + Username;
if (updated) {
result = result + " was successful. ";
} else {
result = result + " was unsuccessful.";
}
Log.d("POINTSINCREASE",result +
" Points were " + String.valueOf(old_points) + " points are now " + String.valueOf(new_points));
}
Note where //TODO remove when happy is coded the lines are just for testing, so the above could be :-
if (count == 4) {
my_db.increasePoints(Username,countPoints);
}

I have a test case in rally. I want to get the name of test folder in which test case exist using java API

I tried getting the test case as json object. It will have Test folder information as a uri. How can I get the name of that test folder without hitting this uri again.
When I hit the URI it gives me the TFxxx, This is what I need directly..
I tried getting as jsonObj.get("TestFolder.Name").toString(); which simply returns null.
Any help?
In the code below I query for a TestCase that happens to be in a TestFolder, and then traverse to the folder like this:
testCaseJsonObject.get("TestFolder").getAsJsonObject().get("Name")
Here is a full example that returns TestFolder's name:
public class GetTestFolder {
public static void main(String[] args) throws Exception {
String host = "https://rally1.rallydev.com";
String applicationName = "Example: get Folder of TestCase";
String projectRef = "/project/12352608219";
String apiKey = "_abc123";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setProject(projectRef);
testCaseRequest.setFetch(new Fetch(new String[] {"FormattedID","Name","TestFolder"}));
testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", "TC47"));
testCaseRequest.setScopedDown(false);
testCaseRequest.setScopedUp(false);
QueryResponse testCaseResponse = restApi.query(testCaseRequest);
System.out.println("Successful: " + testCaseResponse.wasSuccessful());
for (int i=0; i<testCaseResponse.getResults().size();i++){
JsonObject testCaseJsonObject = testCaseResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + testCaseJsonObject.get("Name") + " FormattedID: " + testCaseJsonObject.get("FormattedID") + " TestFolder: " + testCaseJsonObject.get("TestFolder").getAsJsonObject().get("Name"));
}
} finally {
if (restApi != null) {
restApi.close();
}
}
}
}

Pass field/attributes values from java to RTC using JAZZ API's

I am trying to create work item in RTC through java application using the jazz api's.
My connection to the repository is successful. Now i need to set all the required fields through java code in order to save/run the workitem. Really dont know how to set those values in below codes.
String repositoryURI= args[0];
String userId= args[1];
String password= args[2];
String projectAreaName= args[3];
String typeIdentifier= args[4];
String summary= args[5];
String categoryName= args[6];
ITeamRepository teamRepository= TeamPlatform.getTeamRepositoryService().getTeamRepository(repositoryURI);
teamRepository.registerLoginHandler(new LoginHandler(userId, password));
teamRepository.login(null);
IProcessClientService processClient= (IProcessClientService) teamRepository.getClientLibrary(IProcessClientService.class);
IAuditableClient auditableClient= (IAuditableClient) teamRepository.getClientLibrary(IAuditableClient.class);
IWorkItemClient workItemClient= (IWorkItemClient) teamRepository.getClientLibrary(IWorkItemClient.class);
URI uri= URI.create(projectAreaName.replaceAll(" ", "%20"));
IProjectAreaHandle projectArea= (IProjectAreaHandle) processClient.findProcessArea(uri, null, null);
//IProjectAreaHandle projectArea = teamArea.getProjectArea();
if (projectArea == null) {
System.out.println("Project area not found.");
return false;
}
//IWorkItemType workItemType = service.findWorkItemType(projectArea, "defect", monitor);
IWorkItemType workItemType= workItemClient.findWorkItemType((IProjectAreaHandle) projectArea, typeIdentifier, null);
// findWorkItemType(projectArea, typeIdentifier, null);
if (workItemType == null) {
System.out.println("Work item type not found.");
return false;
}
System.out.println("Category not found.: " + categoryName );
List path= Arrays.asList(categoryName.split("/"));
System.out.println("Category not found.: " + path );
ICategoryHandle category= workItemClient.findCategoryByNamePath((IProjectAreaHandle) projectArea, path, null);
//ICategoryHandle category=
if (category == null) {
System.out.println("Category not found.: " + category );
return false;
}
WorkItemInitialization operation= new WorkItemInitialization(summary, category);
IWorkItemHandle handle= operation.run(workItemType, null);
IWorkItem workItem= auditableClient.resolveAuditable(handle, IWorkItem.FULL_PROFILE, null);
System.out.println("Created work item " + workItem.getId() + ".");
teamRepository.logout();
While running the codes i am receiving the below errors. Because of mandatory fields are not assigned. Can any one help me to pass the attribute values (Contact Phone) from java to jazz.
ERROR received:
Severity: ERROR
Summary: Attribute 'Contact Phone #' not set
Description: The 'Contact Phone #' attribute needs to be set (work item <09:13:03>).

Not able to fetch all data from facebook access token in java servlet

I am trying to fetch fb user's "friend list" and his/her "about" but when i do i am getting null value of certain field like i comment below.
System.out.println(loginUser.getId()); //show id
System.out.println(loginUser.getName()); //Show Name
System.out.println(loginUser.getFirstName()); //show null
System.out.println(loginUser.getGender()); //show null
System.out.println(loginUser.getAbout()); //show null
I've been trying the graph-api explorer to see what I'm getting for gender
Its shows here
Code:
String code = request.getParameter("code");
String URLEncodedRedirectURI = URLEncoder.encode("http://localhost:8080/bitspedia-fetchfbfriends/FriendsListServlet");
String MY_ACCESS_TOKEN = "";
String authURL = "https://graph.facebook.com/oauth/access_token?" +
"client_id=" + FriendsListServlet.APP_ID + "&" +
"redirect_uri=" + URLEncodedRedirectURI + "&" +
"client_secret=" + FriendsListServlet.APP_SECRET + "&" +
"code=" + code;
URL url = new URL(authURL);
String result = readURL(url);
String[] pairs = result.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
if (kv[0].equals("access_token")) {
MY_ACCESS_TOKEN = kv[1];
}
}
FacebookClient facebookClient = new DefaultFacebookClient(MY_ACCESS_TOKEN, FriendsListServlet.APP_SECRET);
Connection<User> friends = null;
try {
User loginUser = facebookClient.fetchObject("me", User.class);
request.setAttribute("loginUser", loginUser);
friends = facebookClient.fetchConnection("/me/friends", User.class);
System.out.println(loginUser.getId()); //shows id
System.out.println(loginUser.getName()); //Shows name
System.out.println(loginUser.getFirstName()); //shows null
System.out.println(loginUser.getWebsite()); //shows null
System.out.println(loginUser.getAbout()); //shows null
} catch (FacebookException e) {
e.printStackTrace();
}
List<User> friendsList = friends.getData();
It has very small issue, you didn't provide parameter of null showing value so doing small changes it works fine.
User loginUser = facebookClient.fetchObject("me", `Parameter.with("fields","first_name,last_name,posts")););`

How to fetch child user stories with Java client using Rally API?

How do I fetch child user stories with Java client using Rally API?
Using Chrome's Postman client with URL https://us1.rallydev.com/slm/webservice/v2.0/HierarchicalRequirement/ObjectId/Children, I am able to fetch the children user stories.
But when I try with a Java client, like this:
QueryRequest request = new QueryRequest("/HierarchicalRequirement/ObjectId/Children");
it doesn't work.
Any pointer would be helpful.
It will take fetching "Children" collection on user stories and then hydrating it in a separate request. Here is an example based on latest version of Rally toolkit for Java:
public class GetChildStories {
public static void main(String[] args) throws Exception {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String applicationName = "Find Child Stories of Epics filtered by Tag";
String workspaceRef = "/workspace/12352608129";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(new URI(host),apiKey);
QueryRequest storyRequest = new QueryRequest("HierarchicalRequirement");
storyRequest.setWorkspace(workspaceRef);
restApi.setApplicationName(applicationName);
storyRequest.setFetch(new Fetch(new String[] {"Name", "FormattedID", "Tags", "Children"}));
storyRequest.setLimit(1000);
storyRequest.setScopedDown(false);
storyRequest.setScopedUp(false);
storyRequest.setQueryFilter((new QueryFilter("Tags.Name", "contains", "\"tag1\"")).and(new QueryFilter("DirectChildrenCount", ">", "0")));
QueryResponse storyQueryResponse = restApi.query(storyRequest);
System.out.println("Successful: " + storyQueryResponse.wasSuccessful());
System.out.println("Size: " + storyQueryResponse.getTotalResultCount());
for (int i=0; i<storyQueryResponse.getTotalResultCount();i++){
JsonObject storyJsonObject = storyQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + storyJsonObject.get("Name") + " FormattedID: " + storyJsonObject.get("FormattedID"));
QueryRequest childrenRequest = new QueryRequest(storyJsonObject.getAsJsonObject("Children"));
childrenRequest.setFetch(new Fetch("Name","FormattedID"));
int numberOfChildren = storyJsonObject.get("DirectChildrenCount").getAsInt();
System.out.println(numberOfChildren);
//load the collection
JsonArray children = restApi.query(childrenRequest).getResults();
for (int j=0;j<numberOfChildren;j++){
System.out.println("Name: " + children.get(j).getAsJsonObject().get("Name") + children.get(j).getAsJsonObject().get("FormattedID").getAsString());
System.out.println("Name: " + children.get(0).getAsJsonObject().get("Name") + children.get(0).getAsJsonObject().get("FormattedID").getAsString());
}
}
} finally {
if (restApi != null) {
restApi.close();
}
}
}
}

Categories

Resources