Understands that using Patterns.WEB_URL.matcher(url).matches() will able to validate if that string is a valid url, however it will required in a full format which contain https: / .com.
In my case, i want to validate if the json return a string in correct format for path e.g /images/slider/my/myImage.jpg; which does not contain https or any. How can i do this?
What i want to do is something like:
if(ImageUrl equal "/images/slider/my/myImage.jpg" FORMAT) {
//Do something here
} else //ImageUrl = myImage.jpg {
//Add "/images/slider/my/" infront of the text
}
P.s: My image link will be like www.abc.com/images/slider/my/myImage.jpg
Use URLUtil to validate the URL as below.
URLUtil.isValidUrl(url)
It will return True if URL is valid and false if URL is invalid.
Another way is given below.
public static boolean checkURL(CharSequence input) {
if (TextUtils.isEmpty(input)) {
return false;
}
Pattern URL_PATTERN = Patterns.WEB_URL;
boolean isURL = URL_PATTERN.matcher(input).matches();
if (!isURL) {
String urlString = input + "";
if (URLUtil.isNetworkUrl(urlString)) {
try {
new URL(urlString);
isURL = true;
} catch (Exception e) {
}
}
}
return isURL;
}
This link will explain how you can check the url is available or not.
For more about URLS please visit this
Please have a try
I am trying to implement DRM in my application.
But I am facing a problem. canHandle() always returns false.
And DrmManagerClient.getOriginalMimeType(Uri); always returns null for http links.
But for files in the storage, everything is working fine.
DrmManagerClient mDrmManager;
mDrmManager = new DrmManagerClient(this);
String testUri = myUrl;
String mimeType = getOriginalMimeType( testUri );
Below is the method to get mimetype but unfortunately canHandle() always return false.
// get MimeType
public String getOriginalMimeType(String uri){
String mime = null;
try {
if( mDrmManager.canHandle(Uri.parse(uri), null) ){
mime = mDrmManager.getOriginalMimeType(Uri.parse(uri));
}
} catch (Exception e) {
Log.w(TAG, e.toString());
}
return mime;
}
Am I missing something?
The obvious would have been that probably the url I am using is not good, but
I have tried different urls which work in another application but the outcome is the same.
I have set INTERNET permission in the manifest file too. I am running out of ideas what is the problem.
After digging into DrmManagerClient source code, I noticed that canHandle() is defined as follows:
/**
* Checks whether the given MIME type or URI can be handled.
*
* #param uri URI for the content to be handled.
* #param mimeType MIME type of the object to be handled
*
* #return True if the given MIME type or URI can be handled; false if they cannot be handled.
*/
public boolean canHandle(Uri uri, String mimeType) {
if ((null == uri || Uri.EMPTY == uri) && (null == mimeType || mimeType.equals(""))) {
throw new IllegalArgumentException("Uri or the mimetype should be non null");
}
return canHandle(convertUriToPath(uri), mimeType);
}
What canHandle(Uri uri , String mimeType) is basically the same as canHandle( String path, mimeType ) because it is converting Uri to Path.
Does this mean that Http Urls wont work?
I have found that the problem lies in the urls.
I tested with these two links and everything is fine now.
Stream 1: http://commondatastorage.googleapis.com/wvmedia/sintel_main_720p_4br_tp.wvm
Stream 2: http://commondatastorage.googleapis.com/wvmedia/starz_main_720p_6br_tp.wvm
Hope it helps someone in the future.
I built an android app which can handle a share intent from Google Maps and show it's coordinates.
The problem is that they send a short url which I decode with Google's url shortner api and in some cases, the result long link is of this type: http://maps.google.com/?cid=3635533832900933072&hl=en&gl=us.
Can anyone help me on how to get the coresponding coordinates to "cid=3635533832900933072"
As far as I know there is no public API to get the location from a cid.
However, a possible workaround would be to parse the Google Maps output to obtain the latitude and longitude (though it may be brittle, if they change the result format).
(Although the url contains output=json, it's not actually json -- that's why I parse it with substring() and such instead of using JSONObject).
Try this code:
public static LatLng getCidCoordinates(String cid)
{
final String URL_FORMAT = "http://maps.google.com/maps?cid=%s&q=a&output=json";
final String LATLNG_BEFORE = "viewport:{center:{";
final String LATLNG_AFTER = "}";
final String LATLNG_SEPARATOR = ",";
final String LAT_PREFIX = "lat:";
final String LNG_PREFIX = "lng:";
try
{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(String.format(URL_FORMAT, cid));
HttpResponse response = client.execute(get);
String text = EntityUtils.toString(response.getEntity(), "UTF-8");
int startIndex = text.indexOf(LATLNG_BEFORE);
if (startIndex == -1)
return null;
startIndex += LATLNG_BEFORE.length();
int endIndex = text.indexOf(LATLNG_AFTER, startIndex);
// Should be "lat:<number>,lng:<number>"
String[] parts = text.substring(startIndex, endIndex).split(LATLNG_SEPARATOR);
if (parts.length != 2)
return null;
if (parts[0].startsWith(LAT_PREFIX))
parts[0] = parts[0].substring(LAT_PREFIX.length());
else
return null;
if (parts[1].startsWith(LNG_PREFIX))
parts[1] = parts[1].substring(LNG_PREFIX.length());
else
return null;
return new LatLng(Double.parseDouble(parts[0]), Double.parseDouble(parts[1]));
}
catch (NumberFormatException e)
{
e.printStackTrace();
return null;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
After reading this post yesterday, I found a new method to do it. I hope Google do not close this new API and hidden parameter. :)
You can use this API hidden parameter to get the coordinater. Usage: https://maps.googleapis.com/maps/api/place/details/json?cid=YOUR_CID&key=YOUR_KEY
It returns a result contains formatted address, place_id, name of the address and GPS coordinater.
Please see my blog to see more detail: https://leonbbs.blogspot.com/2018/03/google-map-cid-to-placeid-or-get.html
In latest Google Maps update, the share intent contains the address name in the body which can be decoded with Geocoder into coordinates.
I've got an Android app which scans for all Apps installed on the device and then reports this to a server (it's an MDM agent). Any suggestions on how to get the Category of the App? Everyone has a different list of Categories, but basically something like Game, Entertainment, Tools/Utilities, etc.
From what I can tell there is nothing related to Category stored on the device itself. I was thinking of using the android market API to search for the application in the market and use the Category value returned by the search. Not sure how successful this will be finding a match. Any suggestions on how best to do this?
Any suggestions on a different approach?
Thanks in advance.
mike
I know that this is an old post, but for anyone still looking for this, API level 26 (O) has added categories to android.content.pm.ApplicationInfo.
From the docs https://developer.android.com/reference/android/content/pm/ApplicationInfo#category:
public int category
The category of this app. Categories are used to cluster multiple apps together into meaningful groups, such as when summarizing battery, network, or disk usage. Apps should only define this value when they fit well into one of the specific categories.
Set from the R.attr.appCategory attribute in the manifest. If the manifest doesn't define a category, this value may have been provided by the installer via PackageManager#setApplicationCategoryHint(String, int).
Value is CATEGORY_UNDEFINED, CATEGORY_GAME, CATEGORY_AUDIO, CATEGORY_VIDEO, CATEGORY_IMAGE, CATEGORY_SOCIAL, CATEGORY_NEWS, CATEGORY_MAPS, or CATEGORY_PRODUCTIVITY
One can now do something like:
PackageManager pm = context.getPackageManager();
ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int appCategory = applicationInfo.category;
String categoryTitle = (String) ApplicationInfo.getCategoryTitle(context, appCategory)
// ...
}
if you get for each application its package name, you could ask directly to play store which category an app belongs, parsing html response page with this library:
org.jsoup.jsoup1.8.3
Here's a snippet to solve your problem:
public class MainActivity extends AppCompatActivity {
public final static String GOOGLE_URL = "https://play.google.com/store/apps/details?id=";
public static final String ERROR = "error";
...
private class FetchCategoryTask extends AsyncTask<Void, Void, Void> {
private final String TAG = FetchCategoryTask.class.getSimpleName();
private PackageManager pm;
private ActivityUtil mActivityUtil;
#Override
protected Void doInBackground(Void... errors) {
String category;
pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
Iterator<ApplicationInfo> iterator = packages.iterator();
while (iterator.hasNext()) {
ApplicationInfo packageInfo = iterator.next();
String query_url = GOOGLE_URL + packageInfo.packageName;
Log.i(TAG, query_url);
category = getCategory(query_url);
// store category or do something else
}
return null;
}
private String getCategory(String query_url) {
boolean network = mActivityUtil.isNetworkAvailable();
if (!network) {
//manage connectivity lost
return ERROR;
} else {
try {
Document doc = Jsoup.connect(query_url).get();
Element link = doc.select("span[itemprop=genre]").first();
return link.text();
} catch (Exception e) {
return ERROR;
}
}
}
}
}
You could make these queries in an AsyncTask, or in a service. Hope that you find it helpful.
I also faced the same issue. The solution for the above query is stated below.
Firstly, download the Jsoup library or download the jar file.
or
Add this to your build.gradle(Module: app) implementation 'org.jsoup:jsoup:1.11.3'
private class FetchCategoryTask extends AsyncTask<Void, Void, Void> {
private final String TAG = FetchCategoryTask.class.getSimpleName();
private PackageManager pm;
//private ActivityUtil mActivityUtil;
#Override
protected Void doInBackground(Void... errors) {
String category;
pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
Iterator<ApplicationInfo> iterator = packages.iterator();
// while (iterator.hasNext()) {
// ApplicationInfo packageInfo = iterator.next();
String query_url = "https://play.google.com/store/apps/details?id=com.imo.android.imoim"; //GOOGLE_URL + packageInfo.packageName;
Log.i(TAG, query_url);
category = getCategory(query_url);
Log.e("CATEGORY", category);
// store category or do something else
//}
return null;
}
private String getCategory(String query_url) {
try {
Document doc = Jsoup.connect(query_url).get();
Elements link = doc.select("a[class=\"hrTbp R8zArc\"]");
return link.text();
} catch (Exception e) {
Log.e("DOc", e.toString());
}
}
}
In return, you will get Application Company Name and category of the application
I made a Kotlin solution based on the answer from #Ankit Kumar Singh.
This solution maps the category to an enum, in case you want to do other things than just show it.
import kotlinx.coroutines.*
import org.jsoup.Jsoup
import javax.inject.Inject
import javax.inject.Singleton
class AppCategoryService {
companion object {
private const val APP_URL = "https://play.google.com/store/apps/details?id="
private const val CAT_SIZE = 9
private const val CATEGORY_STRING = "category/"
}
suspend fun fetchCategory(packageName: String): AppCategory {
val url = "$APP_URL$packageName&hl=en" //https://play.google.com/store/apps/details?id=com.example.app&hl=en
val categoryRaw = parseAndExtractCategory(url) ?: return AppCategory.OTHER
return AppCategory.fromCategoryName(categoryRaw)
}
#Suppress("BlockingMethodInNonBlockingContext")
private suspend fun parseAndExtractCategory(url: String): String? = withContext(Dispatchers.IO) {
return#withContext try {
val text = Jsoup.connect(url).get()?.select("a[itemprop=genre]") ?: return#withContext null
val href = text.attr("abs:href")
if (href != null && href.length > 4 && href.contains(CATEGORY_STRING)) {
getCategoryTypeByHref(href)
} else {
null
}
} catch (e: Throwable) {
null
}
}
private fun getCategoryTypeByHref(href: String) = href.substring(href.indexOf(CATEGORY_STRING) + CAT_SIZE, href.length)
}
And here is the enum with all the possible values at of this moment in time:
// Note: Enum name matches API value and should not be changed
enum class AppCategory {
OTHER,
ART_AND_DESIGN,
AUTO_AND_VEHICLES,
BEAUTY,
BOOKS_AND_REFERENCE,
BUSINESS,
COMICS,
COMMUNICATION,
DATING,
EDUCATION,
ENTERTAINMENT,
EVENTS,
FINANCE,
FOOD_AND_DRINK,
HEALTH_AND_FITNESS,
HOUSE_AND_HOME,
LIBRARIES_AND_DEMO,
LIFESTYLE,
MAPS_AND_NAVIGATION,
MEDICAL,
MUSIC_AND_AUDIO,
NEWS_AND_MAGAZINES,
PARENTING,
PERSONALIZATION,
PHOTOGRAPHY,
PRODUCTIVITY,
SHOPPING,
SOCIAL,
SPORTS,
TOOLS,
TRAVEL_AND_LOCAL,
VIDEO_PLAYERS,
WEATHER,
GAMES;
companion object {
private val map = values().associateBy(AppCategory::name)
private const val CATEGORY_GAME_STRING = "GAME_" // All games start with this prefix
fun fromCategoryName(name: String): AppCategory {
if (name.contains(CATEGORY_GAME_STRING)) return GAMES
return map[name.toUpperCase(Locale.ROOT)] ?: OTHER
}
}
}
private fun getCategory(){
val GOOGLE_URL = "https://play.google.com/store/apps/details?id=com.google.android.deskclock"
lifecycleScope.launch(Dispatchers.IO) {
val doc: Document = Jsoup.connect(GOOGLE_URL).get()
val index = doc.body().data().indexOf("applicationCategory")
val simpleString = doc.body().data().subSequence(index,index+100)
val data = simpleString.split(":")[1].split(",")[0]
Log.e("DATA-->",data.toString())
}
}
You can use below AsyncTask for extract Android app category from playStore by using app package id.
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class GetAppCategory extends AsyncTask<String, Void, String> {
//Main URL for each app on Play Store
public static final String APP_URL = "https://play.google.com/store/apps/details?id=";
//Use below String if extracting 'CATEGORY' from href tag.
private final String CATEGORY_STRING = "category/";
private final int cat_size = 9;
/*Use below String for identified 'GAME' apps, which must start with this prefix.
Here I only display 'Games' as category for all Games app instead of showing their subCategory also*/
private final String CATEGORY_GAME_STRING = "GAME_";
//Name of the app package for which you want to get category.
private String packageName = null;
private PackageManager pm = null;
//Activity or Application context as per requirement.
private Context appContext;
/* You can add default system app OR non play store app package name here as comma seprated for ignore them
and set their category directly 'Others' OR anythings you wish. */
private final String extractionApps = "com.android.providers.downloads.ui, com.android.contacts," +
" com.android.gallery3d, com.android.vending, com.android.calculator2, com.android.calculator," +
" com.android.deskclock, com.android.messaging, com.android.settings, com.android.stk";
//Class level TAG, use for Logging.
private final String TAG = "GetAppCategory";
/**
* #param packageName: package name of the app, you want to extract category.
* #param appContext: Activity/Application level Context ap per requirement.
*/
public GetAppCategory(String packageName, Context appContext) {
this.packageName = packageName;
this.appContext = appContext;
}
#Override
protected String doInBackground(String... params) {
try {
pm = appContext.getPackageManager();
if (packageName != null && packageName.length() > 1) {
if (packageName.contains("package:")) {
packageName = packageName.replace("package:", "");
}
/**
* Mathod used for parse play store html page and extract category from their.
*/
String appCategoryType = parseAndExtractCategory(packageName);
Log.i(TAG, "package :" + packageName);
Log.i(TAG, "APP_CATEGORY: " + appCategoryType);
}
} catch (Exception e) {
//TODO:: Handle Exception
e.printStackTrace();
} finally {
//TODO::
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
/**
* #param packageName
* #return
*/
private String parseAndExtractCategory(String packageName) {
//You can pass hl={language_code} for get category in some other langauage also other than English.
//String url = APP_URL + packageName + "&hl=" + appContext.getString(R.string.app_lang);
String url = APP_URL + packageName + "&hl=en"; //{https://play.google.com/store/apps/details?id=com.example.app&hl=en}
String appCategoryType = null;
String appName = null;
try {
if (!extractionApps.contains(packageName)) {
Document doc = null;
try {
doc = Jsoup.connect(url).get();
if (doc != null) {
//TODO: START_METHOD_1
//Extract category String from a <anchor> tag value directly.
//NOTE: its return sub category text, for apps with multiple sub category.
//Comment this method {METHOD_1}, if you wish to extract category by href value.
Element CATEGORY_SUB_CATEGORY = doc.select("a[itemprop=genre]").first();
if (CATEGORY_SUB_CATEGORY != null) {
appCategoryType = CATEGORY_SUB_CATEGORY.text();
}
//TODO: END_METHOD_1
//TODO: START_METHOD_2
// Use below code only if you wist to extract category by href value.
//Its return parent or Main Category Text for all app.
//Comment this method {METHOD_2}, If you wihs to extract category from a<anchor> value.
if (appCategoryType == null || appCategoryType.length() < 1) {
Elements text = doc.select("a[itemprop=genre]");
if (text != null) {
if (appCategoryType == null || appCategoryType.length() < 2) {
String href = text.attr("abs:href");
if (href != null && href.length() > 4 && href.contains(CATEGORY_STRING)) {
appCategoryType = getCategoryTypeByHref(href);
}
}
}
}
//TODO: END_METHOD_2
if (appCategoryType != null && appCategoryType.length() > 1) {
/**
* Ger formatted category String by removing special character.
*/
appCategoryType = replaceSpecialCharacter(appCategoryType);
}
}
} catch (IOException e) {
//appCategoryType = appContext.getString(R.string.category_others);
appCategoryType = "OTHERS";
//TODO:: Handle Exception
e.printStackTrace();
}
} else {
//appCategoryType = appContext.getString(R.string.category_others);
appCategoryType = "OTHERS";
}
} catch (Exception e) {
//TODO:: Handle Exception
e.printStackTrace();
}
return appCategoryType;
}
/**
* #param href
* #return
*/
private String getCategoryTypeByHref(String href) {
String appCategoryType = null;
try {
appCategoryType = href.substring((href.indexOf(CATEGORY_STRING) + cat_size), href.length());
if (appCategoryType != null && appCategoryType.length() > 1) {
if (appCategoryType.contains(CATEGORY_GAME_STRING)) {
//appCategoryType = appContext.getString(R.string.games);
appCategoryType = "GAMES";
}
}
} catch (Exception e) {
//TODO:: Handle Exception
e.printStackTrace();
}
return appCategoryType;
}
/**
* #param appCategoryType
* #return: formatted String
*/
private String replaceSpecialCharacter(String appCategoryType) {
try {
//Find and Replace '&' with '&' in category Text
if (appCategoryType.contains("&")) {
appCategoryType = appCategoryType.replace("&", " & ");
}
//Find and Replace '_AND_' with ' & ' in category Text
if (appCategoryType.contains("_AND_")) {
appCategoryType = appCategoryType.replace("_AND_", " & ");
}
//Find and Replace '_' with ' ' <space> in category Text
if (appCategoryType.contains("_")) {
appCategoryType = appCategoryType.replace("_", " ");
}
} catch (Exception e) {
//TODO:: Handle Exception
e.printStackTrace();
}
return appCategoryType;
}
}
It's requires jsoup library for parsing the html page. you can find it here org.jsoup.jsoup1.11.1
Probably a bit late, but the problem is still here.
The OP has the advantage because of sending those results to the API (here I assume that the API is managed by the OP or his API colleagues at least).
So, for anyone with the similar problem I'd suggest following:
Collect all the package names you're interested in from device.
Send that data to the your API
API should extract package names and try to read results from its cache / db...
For those packages that do not exist in cache / db make "market API" call and extract category - save it to the db / cache for reuse in this iteration.
When all requests (to cache / db and market API) are completed do whatever you like with the results.
Things to consider:
When multiple users try to query your API for a same package name and you don't have a category for that package in your cache / db...
Do 1 request to "market API" for packagex and update packagex in your cache / db to "waiting for results" state - next request should either get a "waiting for results" or a result that "market API" returned.
One should also consider a fallback for possible "market API" fails (market API not working, not a google play app, or something similar). This decision is basically tied to your domain and the business trend that you're trying to catch will force a decision about this for you. If you're really into getting this category stuff sorted out you could pipeline this fallback to human decision and update your API db / cache for packagex accordingly.
put up a nice API that would handle these and similar scenarios gracefully then one could probably even commercialize it up to a certain extent and "market API endpoint" - AKA play store package details page. That page would lose a big part of it's fake users :)
This question already has answers here:
How to display thumbnail of YouTube Videos in Android
(8 answers)
Closed 6 years ago.
In my android Activity I want to play video from YouTube through YouTube application or some other. For that I want to load thumbnails of the video in my activity.
Is this possible? If so, how?
YouTube puts the thumbnails of the video at a specific predictable URL. It would be a bit of a pain, but I'm sure you could find a way to display the images from the URL, or to download them and then display them.
Here's information on my blog on what those thumbnail URLs are.
I'll copy and paste what I wrote in the blog post:
Look at the link for the video–for example, http://www.youtube.com/watch?v=GDFUdMvacI0
Take the video ID… the portion after “v=”, in this case GDFUdMvacI0. If the URL is longer than that, only go until the next ampersand. For example, http://www.youtube.com/watch?v=GDFUdMvacI0&feature=youtu.be is the same, GDFUdMvacI0.
Then just substitute your video ID for the video ID in the following URLs to these thumbnail images:
http://img.youtube.com/vi/GDFUdMvacI0/0.jpg
http://img.youtube.com/vi/GDFUdMvacI0/1.jpg
http://img.youtube.com/vi/GDFUdMvacI0/2.jpg
http://img.youtube.com/vi/GDFUdMvacI0/3.jpg
0.jpg is a full-sized image. The other three are very small (120×90) and are taken automatically by YouTube from three certain points in the video.
Download picasso jar file and put that jar file in "libs" folder
Use picasso to download image
Use method extractYoutubeId(url) to extract youtube id from YoutubeVideo Url
To get image of youtube video use given link and put youtube id in that url as below: "http://img.youtube.com/vi/"+extractYoutubeId(url)+"/0.jpg"
Youtube_Video_thumnail
package com.app.download_video_demo;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
// get Picasso jar file and put that jar file in libs folder
public class Youtube_Video_thumnail extends Activity
{
ImageView iv_youtube_thumnail,iv_play;
String videoId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
super.setContentView(R.layout.youtube_video_activity);
init();
try
{
videoId=extractYoutubeId("http://www.youtube.com/watch?v=t7UxjpUaL3Y");
Log.e("VideoId is->","" + videoId);
String img_url="http://img.youtube.com/vi/"+videoId+"/0.jpg"; // this is link which will give u thumnail image of that video
// picasso jar file download image for u and set image in imagview
Picasso.with(Youtube_Video_thumnail.this)
.load(img_url)
.placeholder(R.drawable.ic_launcher)
.into(iv_youtube_thumnail);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
}
public void init()
{
iv_youtube_thumnail=(ImageView)findViewById(R.id.img_thumnail);
iv_play=(ImageView)findViewById(R.id.iv_play_pause);
}
// extract youtube video id and return that id
// ex--> "http://www.youtube.com/watch?v=t7UxjpUaL3Y"
// videoid is-->t7UxjpUaL3Y
public String extractYoutubeId(String url) throws MalformedURLException {
String query = new URL(url).getQuery();
String[] param = query.split("&");
String id = null;
for (String row : param) {
String[] param1 = row.split("=");
if (param1[0].equals("v")) {
id = param1[1];
}
}
return id;
}
}
youtube_video_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/webvideo_layout2"
android:layout_width="250dp"
android:layout_height="180dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
>
<ImageView
android:id="#+id/img_thumnail"
android:layout_width="250dp"
android:layout_height="180dp"
android:layout_centerInParent="true"
android:scaleType="fitXY" />
<ImageView
android:id="#+id/iv_play_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/icn_play" />
</RelativeLayout>
</LinearLayout>
Try this
public static String getYoutubeThumbnailUrlFromVideoUrl(String videoUrl) {
return "http://img.youtube.com/vi/"+getYoutubeVideoIdFromUrl(videoUrl) + "/0.jpg";
}
public static String getYoutubeVideoIdFromUrl(String inUrl) {
inUrl = inUrl.replace("&feature=youtu.be", "");
if (inUrl.toLowerCase().contains("youtu.be")) {
return inUrl.substring(inUrl.lastIndexOf("/") + 1);
}
String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(inUrl);
if (matcher.find()) {
return matcher.group();
}
return null;
}
This might help someone. The idea is to first get the videos you want, Here I've retrieved a list of videos from a playlist. After that i used this class:
http://blog.blundell-apps.com/imageview-with-loading-spinner/
To display a progress bar while the thumbnail was being retrieved from the web.
/***
* Fetch all videos in a playlist
* #param playlistId
* #return
* #throws ClientProtocolException
* #throws IOException
* #throws JSONException
*/
public YouTubePlaylist fetchPlaylistVideos(String playlistId) throws ClientProtocolException, IOException, JSONException {
String playlistUrl = "https://gdata.youtube.com/feeds/api/playlists/" + playlistId + "?v=2&alt=jsonc";
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(playlistUrl);
HttpResponse response = client.execute(request);
String jsonString = GeneralHelpers.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
if (jsonString.contains("Playlist not found")) {
Log.e(TAG, "playlist not found. id: " + playlistId);
return null;
}
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
String playlistTitle = json.getJSONObject("data").getString("title");
String author = json.getJSONObject("data").getString("author");
List<YouTubeVideo> videos = new ArrayList<YouTubeVideo>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject video = jsonArray.getJSONObject(i).getJSONObject("video");
// The title of the video
String title = video.getString("title");
String url;
try {
url = video.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = video.getJSONObject("player").getString("default");
}
String thumbUrl = video.getJSONObject("thumbnail").getString("sqDefault");
String videoId = video.getString("id");
String uploaded = video.getString("uploaded");
String duration = video.getString("duration");
String minutes = (Integer.parseInt(duration) / 60 < 10) ? "0" + (Integer.parseInt(duration) / 60) : "" + (Integer.parseInt(duration) / 60);
String seconds = (Integer.parseInt(duration) % 60 < 10) ? "0" + (Integer.parseInt(duration) % 60): "" + (Integer.parseInt(duration) % 60);
duration = minutes + ":" + seconds;
videos.add(new YouTubeVideo(title, author, url, thumbUrl, videoId, uploaded, duration));
}
YouTubePlaylist playlist = new YouTubePlaylist(author, playlistId, playlistTitle, videos);
return playlist;
}//end fetchPlaylistVideos