android-market retrieve empty results - java

I wanted to harvest some data on specific apps in
Google play marketplace.
I have used this unofficial API:
https://code.google.com/p/android-market-api/
Here is my code, that basically gets list of apps' names
and try to fetch other data on each app:
public void printAllAppsData(ArrayList<AppHarvestedData> dataWithAppsNamesOnly)
{
MarketSession session = new MarketSession();
session.login("[myGamil]","[myPassword]");
session.getContext().setAndroidId("dead00beef");
final ArrayList<AppHarvestedData> finalResults = new ArrayList<AppHarvestedData>();
for (AppHarvestedData r : dataWithAppsNamesOnly)
{
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setQuery(query)
.setStartIndex(0).setEntriesCount(10)
//.setCategoryId("SOCIAL")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
for(AppHarvestedData res : finalResults)
{
System.out.println(res.toString());
}
}
}
Should I realyy call session.flush(); at this point?
all my quesries return empty collection as a result,
even though I see there are some names as input.
It works fine when I send only one hard coded app name as a query.

session.flush() close you session
you should open session for each query. pay attention the user can be locked for few minutes so you should have many users to to those queries.
if you have the AppId you should use that query:
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setAppId("com.example.android")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
if you want to download also screenshoot or images you should call this query:
GetImageRequest? imgReq; imgReq = GetImageRequest?.newBuilder().setAppId(appId).setImageUsage(AppImageUsage?.SCREENSHOT).setImageId("0").build();
session.append(imgReq, new Callback<GetImageResponse>() {
#Override public void onResult(ResponseContext? context, GetImageResponse? response) {
Log.d(tag, "------------------> Images response <----------------"); if(response != null) {
try {
//imageDownloader.download(image, holder.image, holder.imageLoader);
Log.d(tag, "Finished downloading screenshot 1...");
} catch(Exception ex) {
ex.printStackTrace();
}
} else {
Log.e(tag, "Response was null");
} Log.d(tag, "------------> End of Images response <------------");
}
});

Related

Google API v3 checking exist folder by passing folder name

I'm using google API v3 for check exist folder. If folder does not exist, then create the new folder. This is my code for creating folder
private void createFolderInDrive() throws IOException {
boolean existed = checkExistedFolder("MyFolder");
if (existed = false) {
File fileMetadata = new File();
fileMetadata.setName("MyFolder");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = mService.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + file.getId());
Log.e(this.toString(), "Folder Created with ID:" + file.getId());
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Folder is existed already", Toast.LENGTH_SHORT).show();
}
}
and here is the code for checking exist file
private boolean checkExistedFolder(String folderName) {
//File file = null;
boolean existedFolder = true;
// check if the folder exists already
try {
//String query = "mimeType='application/vnd.google-apps.folder' and trashed=false and title='" + "Evacuation Kit" + "'";
String query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='Evacuation Kit'";
// add parent param to the query if needed
//if (parentId != null) {
//query = query + " and '" + parentId + "' in parents";
// }
Drive.Files.List request = mService.files().list().setQ(query);
FileList fileList = request.execute();
if (fileList.getFiles().size() == 0 ) {
// file = fileList.getFiles().get(0);
existedFolder = false;
}
} catch (IOException e) {
e.printStackTrace();
}
return existedFolder;
fileList.getFiles().size() keep returning 3, even there is no folder on g drive. Can you guys tell me where am I doing wrong?
In the code you show, checkExistedFolder is always looking for the name "Evacuation Kit" and not using the argument folderName. Maybe this is the main reason you're always getting 3 from fileList.getFiles().size().
Also there's an assignment in if (existed = false), you should use if ( false == existed ) -using the static value in the left side of the comparison helps avoiding such mistakes-, or if (!existed). Note that it's important to check the nextPageToken when calling Files:list to check if there is more pages to look for the file. See more here https://developers.google.com/drive/api/v3/reference/files/list and Create folder if it does not exist in the Google Drive
This code will check if folder exist on drive. if exists, it will return id else create folder and returns id.
private DriveFile file;
GoogleApiClient mGoogleApiClient;
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.e(TAG, "connected");
new Thread(new Runnable() {
#Override
public void run() {
DriveId Id = getFolder(Drive.DriveApi.getRootFolder(mGoogleApiClient).getDriveId(), "FOLDER_NAME");
Log.e(TAG, "run: " + Id);
}
}).start();
}
DriveId getFolder(DriveId parentId, String titl) {
DriveId dId = null;
if (parentId != null && titl != null) try {
ArrayList<Filter> fltrs = new ArrayList<>();
fltrs.add(Filters.in(SearchableField.PARENTS, parentId));
fltrs.add(Filters.eq(SearchableField.TITLE, titl));
fltrs.add(Filters.eq(SearchableField.MIME_TYPE, DriveFolder.MIME_TYPE));
Query qry = new Query.Builder().addFilter(Filters.and(fltrs)).build();
MetadataBuffer mdb = null;
DriveApi.MetadataBufferResult rslt = Drive.DriveApi.query(mGoogleApiClient, qry).await();
if (rslt.getStatus().isSuccess()) try {
mdb = rslt.getMetadataBuffer();
if (mdb.getCount() > 0)
dId = mdb.get(0).getDriveId();
} catch (Exception ignore) {
} finally {
if (mdb != null) mdb.close();
}
if (dId == null) {
MetadataChangeSet meta = new MetadataChangeSet.Builder().setTitle(titl).setMimeType(DriveFolder.MIME_TYPE).build();
DriveFolder.DriveFolderResult r1 = parentId.asDriveFolder().createFolder(mGoogleApiClient, meta).await();
DriveFolder dFld = (r1 != null) && r1.getStatus().isSuccess() ? r1.getDriveFolder() : null;
if (dFld != null) {
DriveResource.MetadataResult r2 = dFld.getMetadata(mGoogleApiClient).await();
if ((r2 != null) && r2.getStatus().isSuccess()) {
dId = r2.getMetadata().getDriveId();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return dId;
}
The code working for me with updated API on Kotlin:
override fun createFolder(name: String): Task<GoogleDriveFileHolder> {
check(googleDriveService != null) { "You have to init Google Drive Service first!" }
check(search(name, FOLDER_MIME_TYPE).not()){"folder already exist"}
return Tasks.call<GoogleDriveFileHolder>(
mExecutor,
Callable<GoogleDriveFileHolder> {
val metadata = File()
.setMimeType(FOLDER_MIME_TYPE)
.setName(name)
GoogleDriveFileHolder(
googleDriveService!!.files()
.create(metadata)
.setFields("id")
.execute() ?: throw IOException("Null result when requesting file creation.")
)
})
}
private fun search(name: String, mimeType:String): Boolean {
var pageToken: String? = null
do {
val result: FileList =
googleDriveService!!
.files()
.list()
.setQ("mimeType='$FOLDER_MIME_TYPE'")
.setSpaces("drive")
.setFields("nextPageToken, files(id, name)")
.setPageToken(pageToken)
.execute()
for (file in result.files) {
Log.d(TAG_UPLOAD_FILE , "Found file: %s (%s)\n ${file.name}, ${file.id} ")
if (name == file.name) return true
}
pageToken = result.nextPageToken
} while (pageToken != null)
return false
}
private const val FOLDER_MIME_TYPE= "application/vnd.google-apps.folder"

How to retrieve all tagged facebook photos from the facebook sdk

After many attempts I have been unable to retrieve all of my tagged photos from the facebook sdk. I would like something similar to what tinder has, but my query only returns 110 photos, of which some repeat, compared to tinder retrieving all 296 tagged photos.
Here is the code for my request:
Bundle paramaters = new Bundle();
paramaters.putString("fields", "source");
paramaters.putInt("limit", 1000);
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/" + userId + "/photos",
paramaters,
HttpMethod.GET,
graphCallback
).executeAsync();
GraphRequest.Callback graphCallback = new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
try {
if (response.getError() == null) {
JSONObject joMain = response.getJSONObject();
if (joMain.has("data")) {
final JSONArray jaData = joMain.optJSONArray("data");
for (int i = 0; i < jaData.length(); i++) {
JSONObject joImages = jaData.getJSONObject(i);
String url = (String) joImages.get("source");
if (i == 0) {
facebookAlbum.setDisplayUrl(url);
}
facebookAlbum.addImage(url);
albumnListAdapter.notifyDataSetChanged();
}
}
}
GraphRequest nextRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
if(nextRequest != null) {
nextRequest.setCallback(this);
nextRequest.executeAsync();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
};

Realm findfirst() is returning null

realm newbie here and facing a problem in my project. So what I want to achieve is that, in my app when I click a photo I am saving a realm object inside my database as well as caching the image locally to be used later. Here is the code for both:
#Override
public void onPhotoSelected(PXImage photo) {
PXComposition composition = null;
PXPhoto photoParent = null;
for (PXComposition pxComposition : mSession.getCompositions()) {
if (pxComposition.getItems() == null || pxComposition.getItems().size() < 1)
continue;
for (PXPhoto item : pxComposition.getItems()) {
if (item.getImage().getOriginalPath().equals(photo.getOriginalPath())) {
composition = pxComposition;
photoParent = item;
break;
}
}
}
if (composition == null && photo.isSelected()) {
mRealm.beginTransaction();
String uuid = mSession.addPhoto(photo).getUuid();
mRealm.commitTransaction(); // IMPORTANT to commit transaction. ContentDownloadTask requires PXImage to be written in Realm.
ThreadUtils.getDefaultExecutorService().submit(new ContentDownloadTask(this, photo.getOriginalPath(), uuid));
} else if (composition != null && !photo.isSelected()) {
mRealm.beginTransaction();
if (photoParent.getImage().isDownloaded()) // FIXME What if not copied yet ???
FileUtils.deleteFile(photoParent.getImage().getApplicationPath());
mSession.removePhoto(photoParent);
mRealm.commitTransaction();
}
onCheckChanged(photo);
App.log().v("SESSION", mSession.toString());
}
This is where click events on the photo are handled. After the selection click I am calling ThreadUtils.getDefaultExecutorService().submit(new ContentDownloadTask(this, photo.getOriginalPath(), uuid)); to cache the image locally. Here is the code for the ContentDownloadTask:
public class ContentDownloadTask implements Callable<Void> {
private String id;
private String path;
private Context context;
private Realm mRealm;
public static final String TAG = "ContentDownloadTask";
private static final String DIR_EXTERNAL_NAME = "Local";
private static final String FILE_EXTENSION = ".jpg";
public ContentDownloadTask(Context context, String path, String id) {
this.path = path;
this.id = id;
this.context = context;
}
#Override
public Void call() throws Exception {
try {
Log.d(TAG, "Copying From " + path);
//create output directory if it doesn't exist
final File file = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (file == null) {
throw new IllegalStateException("Failed to get external storage files directory");
} else if (file.exists()) {
if (!file.isDirectory()) {
throw new IllegalStateException(file.getAbsolutePath() +
" already exists and is not a directory");
}
} else {
if (!file.mkdirs()) {
throw new IllegalStateException("Unable to create directory: " +
file.getAbsolutePath());
}
}
File to = new File(file, DIR_EXTERNAL_NAME);
if (to.exists()) {
if (!to.isDirectory()) {
throw new IllegalStateException(file.getAbsolutePath() +
" already exists and is not a directory");
}
} else if (!to.mkdirs()) {
throw new IllegalStateException("Unable to create directory: " +
file.getAbsolutePath());
}
to = new File(to, fileName(this.id));
if (!to.exists())
to.createNewFile();
InputStream in = null;
if (PackageUtils.isContentUri(path)) {
Uri uri = PackageUtils.toUri(path);
in = context.getContentResolver().openInputStream(uri);
} else {
File from = new File(this.path);
in = new FileInputStream(from);
}
OutputStream out = new FileOutputStream(to);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
mRealm = Realm.getDefaultInstance();
PXImage image = mRealm.where(PXImage.class).equalTo("uuid", this.id).findFirst();
if (image == null) {
to.delete();
throw new Exception("Photo Not Found ID: " + this.id);
}
mRealm.beginTransaction();
image.setApplicationPath(to.getPath());
mRealm.commitTransaction();
mRealm.close();
Log.d(TAG, "Complete Copied From " + path + " To " + to.getAbsolutePath());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return null;
}
Now the null is returned at this statement: PXImage image = mRealm.where(PXImage.class).equalTo("uuid", this.id).findFirst();. Basically here I need to save the application path of the image that I cached locally inside the realm object. But it's returning null. Also this not happening every time I click the photos. This only happens sometimes and the error is not reproducible. Any kind of help will be appreciated. I have already checked the following duplicate questions:
first
second
third
fourth
public PXPhoto addPhoto(PXImage image) {
PXComposition composition = null;
PXPhoto photo = null;
boolean isLandscape = false;
int photosPerItem = getProduct().getSelectedPhotosPerItem();
switch (getProduct().getRootShortCode()) {
case Product.CategoryType.SQUARES:
case Product.CategoryType.CLASSIC:
case Product.CategoryType.WALLOGRAPHS:
case Product.CategoryType.SIGNATURES:
case Product.CategoryType.MOSAIC:
setLayoutType(image.isLandscape() ? C.LayoutType.LANDSCAPE.ordinal() : C.LayoutType.PORTRAIT.ordinal());
composition = PXComposition.initializeNewComposition(this);
photo = PXPhoto.initializePhoto(image);
break;
case Product.CategoryType.PANORAMA:
composition = PXComposition.initializeNewComposition(this);
photo = PXPhoto.initializePhoto(image);
break;
case Product.CategoryType.STRIPS:
case Product.CategoryType.POSTERS:
if (getCompositions() == null || getCompositions().size() == 0
|| (getProduct().getRootShortCode().equals(Product.CategoryType.STRIPS) &&
getCompositions().last().getItems().size() % photosPerItem == 0))
composition = PXComposition.initializeNewComposition(this);
else
composition = getCompositions().last();
photo = PXPhoto.initializePhoto(image);
break;
}
composition.addItem(photo);
composition.updateComposition();
if (!composition.isManaged()) {
Realm realm = Realm.getDefaultInstance();
composition = realm.copyToRealmOrUpdate(composition);
realm.close();
photo.setComposition(composition);
addComposition(composition);
} else
photo.setComposition(composition);
return photo;
}
EDIT:
uuid generation:
public PXPhoto() {
this.uuid = UUID.randomUUID().toString();
this.autoEnhance = false;
this.zoom = 1;
}

How to know cookie property in android webkit

I used android.webkit.CookieManager.
I want to get all data about cookie.
But I got only cookie's name and value.
How do I get expires or other data.
Especially, I need expires of cookies.
Thank you.
Here is My Code
public void updateCookie(String url) {
String allCookie = null;
String[] cookies = null;
String cookieNameTmp = null;
String cookieContetTmp = null;
cookieNames.clear();
cookieValue.clear();
if(!m_adapter.isEmpty()) {
m_adapter.clear();
}
try {
allCookie = CookieManager.getInstance().getCookie(url);
if(allCookie != null) {
allCookie = allCookie.replace(" ", "");
cookies = allCookie.split(";");
for (String cookie : cookies) {
cookieNameTmp = cookie.split("=")[0];
m_adapter.add(cookieNameTmp);
cookieContetTmp = cookie.replace(cookieNameTmp+"=", "");
cookieNames.add(cookieNameTmp);
cookieValue.add(cookieContetTmp);
}
}
} catch (Exception e) {
Log.d("updateCookie: ", e.toString());
}
}

Invalid credentials exception while Importing contact list from gmail contacts using Java in Linux only

I have using Google (GDATA) Gmail API for retrieving the contact list from gmail, It is working successfully on windows environment, but when I run the same code on Linux, I get error of Invalid Credentials.
I googled it, but can't get much help,
here is my code
public static String getGmailContactList() {
String response = "";
StringBuilder str = new StringBuilder();
String statusString = "";
ArrayList list = new ArrayList();
ContactsService myService = new ContactsService("");
String email = "xxxxx#gmail.com";
String password = "xxxxxxxx";
try
{
try
{
myService.setUserCredentials(email, password);
}
catch (AuthenticationException ex)
{
ex.printStackTrace();
//****I got exception here when using this code on LINUX ENVIORMENT** ***
}
response = printAllContacts(myService, email);
Iterator itr = list.iterator();
while (itr.hasNext())
{
ArrayList contact = (ArrayList) itr.next();
try
{
str.append(contact.get(1)).append(",");
}
catch (Exception e)
{
log.debug("Exception ocurred inside fethching gmail contact >
>
>
" + e);
str.append("no contacts found");
}
str.substring(0, str.length() - 1);
}
}
catch (Exception ae)
{
response = statusString;
log.debug("Exception ocurred inside ReadContacts : getGmailContactList()" + ae);
}
return response;
}
public static String printAllContacts(ContactsService myService, String emailSent)//
throws ServiceException, IOException
{
URL feedUrl = new URL("http://www.google.com/m8/feeds/contacts/" + emailSent + "/full");
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(100);
ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);
String phones = null;
String emails = null;
log.debug(resultFeed.getTitle().getPlainText());
StringBuilder contacts = new StringBuilder();
contacts.append("<?xml version=\"1.0\"><Contacts>");
for (int i = 0; i < resultFeed.getEntries().size(); i++)
{
contacts.append("<Contact>");
ContactEntry entry = resultFeed.getEntries().get(i);
if (entry.hasName())
{
Name name = entry.getName();
if (name.hasFullName())
{
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi())
{
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
contacts.append("<Name>").append(fullNameToDisplay).append("</Name>");
}
else
{
contacts.append("<Name>").append("").append("</Name>");
}
}
else
{
contacts.append("<Name>").append("").append("</Name>");
}
StringBuilder emailIds = new StringBuilder();
if (entry.hasEmailAddresses())
{
List<Email> email = entry.getEmailAddresses();
if (email != null && email.size() > 0)
{
for (Email e : email)
{
emailIds.append(e.getAddress()).append(",");
}
emailIds.trimToSize();
if (emailIds.indexOf(",") != -1)
{
emails = emailIds.substring(0, emailIds.lastIndexOf(","));
}
contacts.append("<Email>").append(emails).append("</Email>");
}
else
{
contacts.append("<Email>").append("").append("</Email>");
}
}
else
{
contacts.append("<Email>").append("").append("</Email>");
}
contacts.append("</Contact>");
}
contacts.append("</Contacts>");
return contacts.toString();
}
so where I am lacking behind, some sort of help will be appriciated
here is the stack trace
com.google.gdata.client.GoogleService$InvalidCredentialsException: Invalid credentials
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthException(GoogleAuthTokenFactory.java:660)
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthToken(GoogleAuthTokenFactory.java:560)
at com.google.gdata.client.GoogleAuthTokenFactory.setUserCredentials(GoogleAuthTokenFactory.java:397)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:364)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:319)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:303)
at com.gmail.ReadContacts.getGmailContactList(ReadContacts.java:55)

Categories