I am able to retrieve the access token of google account.But I am unable to get the userprofile info.I am getting null pointer exception.Why i cant understand.
Below I have provided two methods using which we get access token and also gets the userprofile info.
It would be great if you help me.
MainActivity.java
private void tryAuthenticate() {
if (isFinishing()) {
return;
}
mToken = null;
setProgressBarIndeterminateVisibility(true);
AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
try {
mToken =
GoogleAuthUtil.getToken(MainActivity.this, mChosenAccountName, "oauth2:"
+ Scopes.PLUS_LOGIN + " " + "https://www.googleapis.com/auth/plus.login" + " "+" https://www.googleapis.com/auth/plus.profile.agerange.read"+" " +YouTubeScopes.YOUTUBE + " "
+ YouTubeScopes.YOUTUBE_UPLOAD);
} catch (GooglePlayServicesAvailabilityException playEx) {
GooglePlayServicesUtil.getErrorDialog(playEx.getConnectionStatusCode(),
MainActivity.this, REQUEST_GMS_ERROR_DIALOG).show();
} catch (UserRecoverableAuthException userAuthEx) {
// Start the user recoverable action using the intent
// returned by
// getIntent()
startActivityForResult(userAuthEx.getIntent(), REQUEST_AUTHENTICATE);
return false;
} catch (IOException transientEx) {
// TODO: backoff
Log.e(this.getClass().getSimpleName(), transientEx.getMessage());
} catch (GoogleAuthException authEx) {
Log.e(this.getClass().getSimpleName(), authEx.getMessage());
}
return true;
}
#Override
protected void onPostExecute(Boolean hideProgressBar) {
invalidateOptionsMenu();
if (hideProgressBar) {
setProgressBarIndeterminateVisibility(false);
}
if (mToken != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
saveAccount();
}
});
}
loadData();
}
};
task.execute((Void) null);
}
private void loadProfile() {
new AsyncTask<Void, Void, Person>() {
#Override
protected Person doInBackground(Void... voids) {
GoogleCredential credential = new GoogleCredential();
credential.setAccessToken(mToken);
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
Plus plus =
new Plus.Builder(httpTransport, jsonFactory, credential).setApplicationName(
Constants.APP_NAME).build();
try {
return plus.people().get("me").execute(); //here am getting null pointer exception
} catch (final GoogleJsonResponseException e) {
if (401 == e.getDetails().getCode()) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
GoogleAuthUtil.invalidateToken(MainActivity.this, mToken);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
tryAuthenticate();
}
}, mCurrentBackoff * 1000);
mCurrentBackoff *= 2;
if (mCurrentBackoff == 0) {
mCurrentBackoff = 1;
}
}
} catch (final IOException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Person me) {
mUploadsListFragment.setProfileInfo(me);
}
}.execute((Void) null);
}
It seems as if you have mixed and matched a lot of things all together. The line at which you are getting a Null Pointer is because the me is not defined anywhere else in the program and hence when the get method is called it is not able to find the value.
Secondly, you can separate out the code in two different files if you want to perform a set of two different operations. If you just want to retrieve the information regarding the profile information of a Google+ User account please follow the tutorial.
Related
I'm using the following:
GoogleApiClient mApiClient = new GoogleApiClient.Builder(this)
.addApi( Wearable.API )
...
Since Wearable.API is deprecated? What is the appropriate replacement?
I found something nice which is helpful
private class StartWearableActivityTask extends AsyncTask<Void, Void, Void> {
final String key;
public StartWearableActivityTask(String msg){
key = msg;
}
#Override
protected Void doInBackground(Void... args) {
Collection<String> nodes = getNodes();
for (String node : nodes) {
sendStartActivityMessage(node,key);
}
return null;
}
}
#WorkerThread
private Collection<String> getNodes() {
HashSet<String> results = new HashSet<>();
Task<List<Node>> nodeListTask =
Wearable.getNodeClient(getApplicationContext()).getConnectedNodes();
try {
// Block on a task and get the result synchronously (because this is on a background
// thread).
List<Node> nodes = Tasks.await(nodeListTask);
for (Node node : nodes) {
results.add(node.getId());
}
} catch (ExecutionException exception) {
Log.e(TAG, "Task failed: " + exception);
} catch (InterruptedException exception) {
Log.e(TAG, "Interrupt occurred: " + exception);
}
return results;
}
#WorkerThread
private void sendStartActivityMessage(String node,String event) {
Task<Integer> sendMessageTask =
Wearable.getMessageClient(this).sendMessage(node, event, new byte[0]);
try {
// Block on a task and get the result synchronously (because this is on a background
// thread).
Integer result = Tasks.await(sendMessageTask);
} catch (ExecutionException exception) {
Log.e(TAG, "Task failed: " + exception);
} catch (InterruptedException exception) {
Log.e(TAG, "Interrupt occurred: " + exception);
}
}
I found answer here:
https://developer.android.com/training/wearables/data-layer/migrate-to-googleapi
Migrate Wear apps to GoogleApi
Starting with version 11.8.0 of Google Play services, Wear OS apps should migrate away from the GoogleApiClient class and instead use client objects that are based on the GoogleApi class.
Use of GoogleApi makes it easier to set up asynchronous operations. For example, as described in the introduction to the Tasks API, you can obtain a Task object instead of a PendingResult object.
new AsyncTask<Ticket, Void, List<TPVLine>>() {
#Override
protected List<TPVLine> doInBackground(Ticket... params) {
List<TPVLine> lines;
while (true){
Log.d(TAG, "Waiting for data base response");
try {
lines = params[0].getLines();
Log.d(TAG, "Data base response completed");
break;
}catch (SQLiteException | NullPointerException ex){
ActiveAndroid.clearCache();
Log.d(TAG, "Cleaning cache");
Log.wtf(TAG, ex.toString());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return lines;
}
#Override
protected void onPostExecute(List<TPVLine> aVoid) {
super.onPostExecute(aVoid);
linesTPV = new ArrayList<TPVLine>();
if (aVoid != null){
linesTPV = aVoid;
}
linesTPV.addAll(noSavedLines);
mainActivity.getTpvFragment().resetPrice();
notifyDataSetChanged();
if (linesTPV.size() == 0){
mainActivity.getTpvFragment().getListContainer().setVisibility(View.INVISIBLE);
mainActivity.getTpvFragment().getMessageContainer().setVisibility(View.VISIBLE);
}else {
mainActivity.getTpvFragment().getListContainer().setVisibility(View.VISIBLE);
mainActivity.getTpvFragment().getMessageContainer().setVisibility(View.INVISIBLE);
}
notifyDataSetChanged();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mainActivity.getCurrentTicket());
This are the calls, first in Ticket.java
public List<TPVLine> getLines() {
return new Select().from(TPVLine.class).where("Ticket = ?", this.getId()).execute();
}
The second is in TPVLine.java
public static List<TPVLine> getLines(Ticket ticket){
return new Select().from(TPVLine.class).where("Ticket = ?", ticket.getId()).orderBy("Id ASC").execute();
}
The issue is caused when i call TPVLine.class, i make sure first that Ticket != null. I'm using ActiveAndroid to manage the database
you are returning null instead of lines in your asynctask doInBackground event.
return lines;
I'm using azure sdk for android and follow the tutorial https://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-android-get-started-data/.
When I'm trying to connect and insert data to mobile service table all is ok, but when I query the table in activity my app gets stuck, though there are only several entries in the table and execute method successfully returns Future.
public static MobileServiceClient mClient;
public static void connect(Context context) {
try {
mClient = new MobileServiceClient(storageLink, key, context);
} catch (MalformedURLException e) {
Log.e("AzureService.connect", "Storage access failed" + storageLink);
}
}
public static InstallationData get(final String deviceId) {
MobileServiceTable<InstallationData> table= mClient.getTable(InstallationData.class);
final MobileServiceList<InstallationData> result;
try {
result = table.where().field("deviceid").eq(deviceId).execute().get();
for (InstallationData item : result) {
return item;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
public static void store(final InstallationData item) {
mClient.getTable(InstallationData.class).insert(item, new TableOperationCallback<InstallationData>() {
public void onCompleted(InstallationData entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
Log.d("AzureService.store()", "Data about " + item.getDeviceid() + "" + "is successfully updated");
} else {
exception.printStackTrace();
Log.e("AzureService.store()", "Data about " + item.getDeviceid() + "" + "is failed to update");
}
}
});
}
Thank you in advance!
How can I get a list of videos available from a particular YouTube channel, using the API?
Basically every youtube channels has three section: Uploads, Playlist, Liked Videos. Had done some work with the playlist of a channels. Used youtube api version 3.Sharing my code:
First get the Playlists from a channel:
private void getPlayList() {
YouTube.Playlists.List playLists;
try {
playLists = youtube.playlists().list("id,status,snippet");//youtube is the Youtube object, already initialised
playLists.setChannelId(channelID);//channelID is the channel id which you want to fetch
playLists.setFields("items(id,status/privacyStatus,snippet(title,thumbnails/default/url))");
playLists.setMaxResults((long) 50);
AsynRequestClass asynRequestClass = new AsynRequestClass();
asynRequestClass.execute(playLists);
} catch (IOException e) {
e.printStackTrace();
Log.e(null, "Error occur " + e.toString());
}
}
private class AsynRequestClass extends AsyncTask<YouTube.Playlists.List, Void, PlaylistListResponse> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialogWithTitle("Loading PlayList");
}
#Override
protected PlaylistListResponse doInBackground(YouTube.Playlists.List... params) {
PlaylistListResponse playlistListResponse = null;
try {
Log.d(null, "PlayListList: " + params[0]);
playlistListResponse = params[0].execute();
Log.d(null,"PlayListResponse: "+playlistListResponse);
for (int i=0;i<playlistListResponse.getItems().size();i++){
//PlayListIdentifier,PlayListTitle,PlayListThumbnails are ArrayList<String>, already allocated and initialised
PlayListTitles.add(playlistListResponse.getItems().get(i).getSnippet().getTitle());
PlayListThumbnails.add(playlistListResponse.getItems().get(i).getSnippet().getThumbnails().getDefault().getUrl());
PlayListIdentifier.add(playlistListResponse.getItems().get(i).getId());
}
}catch (UserRecoverableAuthIOException e){
startActivityForResult(e.getIntent(),REQUEST_AUTHORIZATION);
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(PlaylistListResponse playlistListResponse){
super.onPostExecute(playlistListResponse);
hideProgressDialog();
PlayListDataAdapter.notifyDataSetChanged();//PlayListDataAdapter is the data adapter
}
}
Then get the playListItem or Videos:
private void loadPlayListItem(){
YouTube.PlaylistItems.List playListItemList = null;
try {
playListItemList =youtube.playlistItems().list("id,contentDetails,snippet,status");
playListItemList.setPlaylistId(playListID);
playListItemList.setFields("items(id,status/privacyStatus,snippet(title,thumbnails/default/url),contentDetails/regionRestriction)");
playListItemList.setMaxResults((long) 50);
AsyncRequestClass asyncRequestClass = new AsyncRequestClass();
asyncRequestClass.execute(playListItemList);
} catch (IOException e) {
e.printStackTrace();
}
}
//Class for asynchronous task
private class AsyncRequestClass extends AsyncTask<YouTube.PlaylistItems.List, Void, PlaylistItemListResponse> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialogWithTitle("Loading Video");
}
#Override
protected PlaylistItemListResponse doInBackground(YouTube.PlaylistItems.List... params) {
PlaylistItemListResponse playlistItemListResponse = null;
try {
Log.d(null, "PlayListListItem: " + params[0]);
playlistItemListResponse = params[0].execute();
Log.d(null,"PlayListItemListResponse: "+playlistItemListResponse);
int size = playlistItemListResponse.getItems().size();
for (int i=0;i<size;i++){
if (!playlistItemListResponse.getItems().get(i).getStatus().getPrivacyStatus().equals("private")){
//videoListIdentifier,videoListTitle,videoListThumbnails are ArrayList<String>, already allocated and initialised
videoTitles.add(playlistItemListResponse.getItems().get(i).getSnippet().getTitle());
videoThumbnails.add(playlistItemListResponse.getItems().get(i).getSnippet().getThumbnails().getDefault().getUrl());
videoIdentifier.add(playlistItemListResponse.getItems().get(i).getContentDetails().getVideoId());
}
}
}catch (UserRecoverableAuthIOException e){
startActivityForResult(e.getIntent(),REQUEST_AUTHORIZATION);
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(PlaylistItemListResponse playlistItemListResponse) {
super.onPostExecute(playlistItemListResponse);
hideProgressDialog();
videoListDataAdapter.notifyDataSetChanged();//videoListDataAdapter is the data adapter
}
}
Hadn't worked with the other two(Uploads,Liked videos), but think it can be possible in a similar manner.
Goodmorning,
I have a button on my android app that launches a search on the web (through google endpoints) through an AsyncTask. My problem is that the button does not "unclick" until the AsyncTask is completed, which may take several seconds. When the internet connection is slow, this even makes the application crash, in any case the application is completely stuck until the AsyncTask is completed. Now the reason for using AsyncTask was exactly to eliminate this problem, so I don't really get what happens!
Here is the OnClickListener:
SearchListener = new OnClickListener() {
#Override
public void onClick(View v) {
String cname=TextCourse.getText().toString();
if (!cname.isEmpty()){
try {
CollectionResponseWine listavini= new QueryWinesTask(messageEndpoint,cname,5).execute().get();
} catch (InterruptedException e) {
showDialog("Errore ricerca");
e.printStackTrace();
} catch (ExecutionException e) {
showDialog("Errore ricerca");
e.printStackTrace();
}
} else{
showDialog("Inserisci un piatto");
}
}
};
and here is the AsyncTask that is being called:
private class QueryWinesTask
extends AsyncTask<Void, Void, CollectionResponseWine> {
Exception exceptionThrown = null;
MessageEndpoint messageEndpoint;
String cname;
Integer limit;
public QueryWinesTask(MessageEndpoint messageEndpoint, String cname, Integer limit) {
this.messageEndpoint = messageEndpoint;
this.cname=cname;
this.limit=limit;
}
#Override
protected CollectionResponseWine doInBackground(Void... params) {
try {
CollectionResponseWine wines = messageEndpoint.listwines().setCoursename(cname).setLimit(limit).execute();
return wines;
} catch (IOException e) {
exceptionThrown = e;
return null;
//Handle exception in PostExecute
}
}
protected void onPostExecute(CollectionResponseWine wines) {
// Check if exception was thrown
if (exceptionThrown != null) {
Log.e(RegisterActivity.class.getName(),
"Exception when listing Messages", exceptionThrown);
showDialog("Non ci sono vini associati al tuo piatto. Aggiungine uno!");
}
else {
messageView.setText("Vini piu' votati per " +
cname + ":\n\n");
for(Wine wine : wines.getItems()) {
messageView.append(wine.getName() + " (" + wine.getScore() + ")\n");
}
}
}
}
...execute().get() is blocking. It makes UI thread wait for Task to complete.
Don't do get(). Use onPostExecute() to get the result (wines) of task and update the UI.