Android Square Picasso not load persian character image url - android

I want to create web application by square picasso, but if image url contains persian characters (ا،ب،ج،ی، ...) Picasso not load image.
This url not working:
Picasso.with(mContext).load("http://www.shutterstock.ir/thumbs/10006/74601661-گربه-چشم-ابی-ولاغر-سیامی-در-یک-پس-زمینه-،-وکتور-سفید.jpg")
.placeholder(R.drawable.ic_launcher)
.error(R.drawable.face_top_image).noFade().resize(100, 100)
.into(imageView);
This url work
Picasso.with(mContext).load("http://www.shutterstock.ir/thumbs/10006/74601661-%DA%AF%D8%B1%D8%A8%D9%87-%DA%86%D8%B4%D9%85-%D8%A7%D8%A8%DB%8C-%D9%88%D9%84%D8%A7%D8%BA%D8%B1-%D8%B3%DB%8C%D8%A7%D9%85%DB%8C-%D8%AF%D8%B1-%DB%8C%DA%A9-%D9%BE%D8%B3-%D8%B2%D9%85%DB%8C%D9%86%D9%87-%D8%8C-%D9%88%DA%A9%D8%AA%D9%88%D8%B1-%D8%B3%D9%81%DB%8C%D8%AF.jpg")
.placeholder(R.drawable.ic_launcher)
.error(R.drawable.face_top_image).noFade().resize(100, 100)
.into(imageView);

You need to URI encode the URL.
See the docs
Uri.encode(url);
Or, if specifying certain allowed characters the following works:
private static final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);

You need to encode your Url .
So try this
URIUtil.encodeQuery(myUrl).
or also this one : http://developer.android.com/reference/java/net/URLEncoder.html
URLEncoder.encode(myUrl, "UTF-8");
Also there is an issue here

just use from this function
public static String encodUrl(String url){
String[] splitUrl = url.split("/");
String imageName = splitUrl[splitUrl.length-1];//get name of file
String mainUrl = url.replaceAll(imageName , "");//get url without file name bacause dont need to encode
return (mainUrl + Uri.encode(imageName));
}

Related

How to insert path between absoluteURL and parameter?

My url looks like this: https://test.com/test#someParameter
And i want to insert "/site" between the url and the parameter without string operations, because using string operations on urls are not best practise.
The final url should look like this: https://test.com/test/site#someParameter
I tried using .apply but it didn't work:
URI(url).apply { path += "/site" }.toString()
I believe that a safe way to do it is using urllib
import urllib
args = {"site": "site", "param": "some_parameter"}
url = "https://test.com/test/{}#{}".format(urllib.urlencode(args))

Getting audio URL from jsoup android

Below is the HTML tag for the audio link url,
And below is the logic I used to get the URL,
String url = "https://www.dictionary.com/browse/happy?s=t";
Document doc = Jsoup.connect(url).get();
Elements wordBlock = doc.getElementsByClass("e16867sm0");
Element e = wordBlock.get(0);
Elements audioSection = e.getElementsByClass("e1rg2mtf7");
String audioUrl = audioSection.get(0).attr("audio");
But still I am unable to get the URL,
How can we get the URL of audio by using class id.
You can use either doc.select("source[type=audio/ogg]" for the first file or doc.select("source[type=audio/mpeg]" for the second one.
You can also use source[type^=audio] - it will give you both.

Using Glide to load an image from remote storage

I am developing an android app that needs to load many images from a folder that is located on my online server (in this case a GoDaddy hosting shared-plan).
All of the images are stored in an image folder inside the FileManager folder provided by GoDaddy.
Glide needs a URL to load an image, but in my case these images are not public and can't be reached from a HTTP URL (and should remain that way).
I would like to use glide to load these remotely stored images just like I am able to do so locally by providing a local path to the images on my local machine
For example this code works locally where path = (C:\Users\user\images\myImage.png) notice that it is not https:// url .
Glide.with(mContext)
.load(C:\Users\user\images\myImage.png)
.into(mImageView);
The path provided here is local and works on my local machine, I would like to replace localPath with remoteStorageFolderPath but I am unsure how it is done. Any help would be greatly appreciated!
Thank you.
so I think this has already been brought up as an issue in Glides Github, and was solved by TWiStErRob on 10 Nov 2016. The way to do it is to add an authorisation header as follows:
LazyHeaders auth = new LazyHeaders.Builder() // This can be cached in a field and reused later.
.addHeader("Authorization", new BasicAuthorization(username, password))
.build();
Glide
.with(context)
.load(new GlideUrl(url, auth)) // GlideUrl is created anyway so there's no extra objects allocated.
.into(imageView);
}
public class BasicAuthorization implements LazyHeaderFactory {
private final String username;
private final String password;
public BasicAuthorization(String username, String password) {
this.username = username;
this.password = password;
}
#Override
public String buildHeader() {
return "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP);
}
}

Validate Specfic URL input in EditText for android

My application is about downloading an image from a specific website e.g. www.example.com/img-...
The user will input the url for the img to the EditText field. e.g. www.example.com/img-123
My problem is that when the user inputs a wrong URL, i.e. one with no no image, it is empty e.g. www.example.com/img-222
I want to detect this and tell the user their input does not link to an image and try again.
I'm using the isValidUrl() function to detect if the input is a WEB_URL only but what I want is that when the entered url has no image, the program should tell them it is an incorrect format for url.
I'm using Jsoup.connect(url).get(); to connect to the url and get the image and save it
private boolean isValidUrl(String url) {
Pattern p = Patterns.WEB_URL;
Matcher m = p.matcher(url);
if(m.matches())
return true;
else
return false;
}
We can use android native android.webkit.URLUtil class to validate any kind of url.
URLUtil.isValidUrl(downloadImaheEditText.getText().toString());
it will return true if valid else false.
String[] schemes = {"http","https"}; //DEFAULT schemes = "http", "https", "ftp"
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("http://www.google.com")) {
//url is valid
}else{
//url is invalid
}
Use Apache commons-validator URLValidator class
I tried this and it worked for me. Please find the code snippet below:
public static boolean isURL(String url) {
Pattern p = Patterns.WEB_URL;
Matcher m = p.matcher(url.toLowerCase());
return m.matches();
}

How can I load an image from a url into an android remote view for a widget

I have an image url I parse form json that I want to load into an android widget onto the homescreen. Right now I am trying to do it this way but its wrong:
ImageDownloadTask imageD = new ImageDownloadTask(image);
views.setImageViewBitmap(R.id.image, imageD.execute(image));
image is a string holding a url to an image that needs to be downloaded and I am trying to set it to R.id.image
I found another stack question and tried this as a result:
views.setBitmap(R.id.image, "setImageBitmap",BitmapFactory.decodeStream(new URL(image).openStream()));
And when I use that nothing in the app loads at all, none of the text views get set.
My third try was this:
//get beer data
JSONObject o = new JSONObject(result);
String name = getName(o);
String image = getImage(o);
String abv = getABV(o);
String ibu = getIBU(o);
String glass = getGlass(o);
String beerBreweryName = getBreweryName(o);
String beerBreweryStyle = getBreweryStyle(o);
String beerDescription = getDescription(o);
InputStream in = new java.net.URL(image).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
views.setTextViewText(R.id.beerTitle, name);
views.setTextViewText(R.id.beerBreweryName, beerBreweryName);
views.setTextViewText(R.id.beerStyleName, beerBreweryStyle);
views.setImageViewBitmap(R.id.image, bitmap);
This gave the same result as the last attempt, it would not even set any text views....
Just tried another attempt after one of the answers posted below:
RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget_test);
//get beer data
JSONObject o = new JSONObject(result);
String name = getName(o);
String imageURL = getImage(o);
String abv = getABV(o);
String ibu = getIBU(o);
String glass = getGlass(o);
String beerBreweryName = getBreweryName(o);
String beerBreweryStyle = getBreweryStyle(o);
String beerDescription = getDescription(o);
Log.d("widgetImage" , imageURL);
views.setImageViewUri(R.id.image, Uri.parse(imageURL));
views.setTextViewText(R.id.beerTitle, name);
views.setTextViewText(R.id.beerBreweryName, beerBreweryName);
views.setTextViewText(R.id.beerStyleName, beerBreweryStyle);
mgr.updateAppWidget(appWidgetIds, views);
This attempt lets all the text views load, but no image ever shows up.
The way to do this reliably is to use setImageViewURI on the remote ImageView. The trick is that the URI you give it is a content:// URI which then points back to a content provider that you export from your application. In your content provider you can do anything you need to do to supply the image bytes.
For example, in your manifest:
<provider android:name=".ImageContentProvider" android:authorities="com.example.test" android:exported="true" />
And your provider:
public class ImageContentProvider extends ContentProvider {
// (Removed overrides that do nothing)
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
List<String> segs = uri.getPathSegments();
// Download the image content here, get the info you need from segs
return ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY);
}
}
And then your URL is something like:
content://com.example.test/something-you-can-define/here
This is necessary because your remote image view is not running in your process. You are much more limited in what you can do because everything must be serialized across the process boundary. The URI can serialize just fine but if you try to send a megabyte of image data with setImageViewBitmap, it's probably going to fail (depending on available device memory).
Got a lot of help from multiple sources for this question. The big problem for me why a bunch of the attempts I tried listed above seemed to lock the widget app and not load anything is because I can not download the image and set it in a UI thread.
To accomplish this I had to move everything to the do in background of my async task and not in the onPostExecute.

Categories

Resources