I am using URI Builder class to build this url
http://image.tmdb.org/t/p/w185//qjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg
Here is my code:
`final String TMDB_results = "results";
final String TMDB_title = "original_title";
final String TMDB_poster = "backdrop_path";
JSONObject moviesJson = new JSONObject(moviesJsonStr);
JSONArray resultArray = moviesJson.getJSONArray(TMDB_results);
String[] resultnameStrs = new String[resultArray.length()];
String[] resultposterStrs = new String[resultArray.length()];
for (int i = 0; i < resultArray.length(); i++) {
String moviename;
String movieposter;
// Get the JSON object in which movie title is there
JSONObject movietitle = resultArray.getJSONObject(i);
moviename = movietitle.get(TMDB_title).toString();
movieposter = movietitle.get(TMDB_poster).toString();
//Poster URL Builder
Uri posterbuiltUri = Uri.parse("http://image.tmdb.org/t/p/w185/").buildUpon()
.appendPath(movieposter).build();
String PosterUrl = posterbuiltUri.toString();
resultposterStrs[i] = PosterUrl;
resultnameStrs[i] = moviename;
}
But the URL being build is
http://image.tmdb.org/t/p/w185/%2Fqjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg
Here is a part of JSON String from which I am retrieving data:
{"page":1,"results":[{"adult":false,"backdrop_path":"/kvXLZqY0Ngl1XSw7EaMQO0C1CCj.jpg","genre_ids":[28,12,878],"id":102899,"original_language":"en","original_title":"Ant-Man","overview":"Armed with the astonishing ability to shrink in scale but increase in strength, con-man Scott Lang must embrace his inner-hero and help his mentor, Dr. Hank Pym, protect the secret behind his spectacular Ant-Man suit from a new generation of towering threats. Against seemingly insurmountable obstacles, Pym and Lang must plan and pull off a heist that will save the world.","release_date":"2015-07-17","poster_path":"/D6e8RJf2qUstnfkTslTXNTUAlT.jpg","popularity":54.222073,"title":"Ant-Man","video":false,"vote_average":6.9,"vote_count":1859},.......
I think the '/' is being encoded to '%2F'. Is there any way to stop that?
Any help regrading this is appreciated.
appendPath is encoding the / character from your image path -- you're likely seeing %2F as the encoded (aka URL safe) alternative. Your quickest bet here is to do a quick removal of that first slash (which will also prevent double slash from the base URL and the image URL path).
Uri posterbuiltUri = Uri.parse("http://image.tmdb.org/t/p/w185/").buildUpon()
.appendPath(movieposter.replace("/","").build();
You have an extra '/' in there, encode this instead:
http://image.tmdb.org/t/p/w185/qjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg
Related
Sorry for my bad English, i'm from Germany, but i hope, i'm understandable.
String = Dömä
Result = D(any signs)m(any signs)
My Code:
JSONObject json = jsonParser.makeHttpRequest(UserFactory.GET_URL, "POST", paramsx);
sList = new ArrayList<Data>();
JSONArray cast = json.getJSONArray("friends");
for (int i = 0; i < cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String fullname = actor.getString("fullname");
String country = actor.getString("country");
String profile_image = actor.getString("profile_image");
sList.add(new Data(fullname, country, profile_image));
}
How can I fix this problem?
There are problems with your character encoding. You need to make sure the character encoding you are using for the JSON supports the language you are using and that both ends of the link are using the same encoding.
I want to get movie data from the OMDB API which is JSON text. I am using Java to decode this and the package JSON-simple.
The URL I want to decode is this for example: http://www.omdbapi.com/?t=icarus
Outcome (directly copy and paste, not structured):
{"Title":"Icarus","Year":"2010","Rated":"TV-14","Released":"10 Dec 2010","Runtime":"42 min","Genre":"Adventure, Drama, Romance","Director":"Mairzee Almas","Writer":"Alfred Gough (creator), Jerry Siegel (character created by: Superman), Miles Millar (creator), Joe Shuster (character created by: Superman), Alfred Gough (developed for television by), Miles Millar (developed for television by), Genevieve Sparling","Actors":"Tom Welling, Erica Durance, Cassidy Freeman, Justin Hartley","Plot":"As the VRA threat intensifies, Clark takes initiative by closing down watchtower and declaring the League go officially underground, but will this be enough to stop trotter and Slade Wilson...","Language":"English","Country":"USA","Awards":"N/A","Poster":"http://ia.media-imdb.com/images/M/MV5BMjIwNDQ2MjM5OV5BMl5BanBnXkFtZTcwODU4NzU0NA##._V1_SX300.jpg","Metascore":"N/A","imdbRating":"8.6","imdbVotes":"367","imdbID":"tt1628582","Type":"episode","Response":"True"}
The code under my button:
String url = "http://www.omdbapi.com/?t=" + jListFilms.getSelectedValue().toString();
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(url);
JSONObject jsonObj = (JSONObject) obj;
String title = (String) jsonObj.get("Title") ;
System.out.println(title);
} catch (ParseException e){
System.out.println(e);
}
When I print out the variable title
Unexpected character (h) at position 0.
Does anyone know why I don't get the title of the movie?
What your code is doing is parsing the string URL which starts "http://", hence the h at location 0.
You need to issue an HTTP GET request at that url in order to get the JSON back.
Here's an answer for how to issue the GET request
Thanks Adam for leading me into the right direction. I am using InputStream and Google Gson instead of JSON.Simple now.
This is my code now and it works how I wanted it to work.
try {
String selectedItem = jListFilms.getSelectedValue().toString().replace("\\s+", "+");
InputStream input = new URL("http://www.omdbapi.com/?t=" + URLEncoder.encode(selectedItem, "UTF-8")).openStream();
Map<String, String> map = new Gson().fromJson(new InputStreamReader(input, "UTF-8"), new TypeToken<Map<String, String>>(){}.getType());
String title = map.get("Title");
String year = map.get("Year");
String released = map.get("Released");
String runtime = map.get("Runtime");
String genre = map.get("Genre");
String actors = map.get("Actors");
String plot = map.get("Plot");
String imdbRating = map.get("imdbRating");
String poster = map.get("Poster");
testForm tf = new testForm(title, year, released, runtime, genre, actors, plot, imdbRating);
tf.setVisible(true);
} catch (JsonIOException | JsonSyntaxException | IOException e){
System.out.println(e);
}
I have the following String:
[{"index":1,"image":"1234a.jpg","thumbnail":"1234a_t.jpg","medium":"1234a.jpg"},
{"index":2,"image":"43215256b.png","thumbnail":"43215256b_t.jpg","medium":"43215256b.jpg"}]
I would like to select only JPG name or the pngs like (1234a.jpg OR 43215256b.png) and ignore the rest of the String, How can I do that in Java?? I tried substring but it works not fine because the names of the JPGs are different.
Here a piece of my Java code:
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("imageID", c.getString("imageID"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
Where image is a database field that contains the String above, So I would like to select the JPGs names OR the PNGs names from the content of c.getString("image") I tried JSON but not worked, mabye have someone better Idea?? please help.
You should use a regular JSON parser. If this is not possible use the regex (?<=")\w+\.jpg(?=") to find the names enclosed in quotes ("") ending with jpg.
When using a Java Pattern, you need double \ inside the String "(?<=\")\\w+\\.jpg(?=\")"
Try this:
Modified Your Code:
for (int i = 0; i < data.length(); i++)
{
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
if(isValid(c.getString("image")))
{
map.put("imageID", c.getString("imageID"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
}
This is my Patch:
public boolean isValid(String value)
{
String jpgChk = "\\.jpg$";
String pngChk = "\\.png$";
Matcher jpgMatcher = Pattern.compile(jpgChk).matcher(value);
Matcher pngMatcher = Pattern.compile(pngChk).matcher(value);
if(jpgMatcher.find())
return value.contains(".png")?false:true;
else if (pngMatcher.find())
return value.contains(".jpg")?false:true;
else
return false;
}
This is long but immediate solution to your problem. If works accept it or we will try to minimize and optimize this one
Parse it in json format and check for each key if the value has a substring of jpg. if yes then you can use the whole value.
I'd like to extract URL from hi there this is a URL String http://mytest.com.
I tried to use EditText.getURLs but it didn't work for me.
EditText.setText("hi there this is a URL String http://stackoverflow.com");
EditText.getURLs.toString();
How can I get URL from EditText?
Here is the function:
//Pull all links from the body for easy retrieval
private ArrayList pullLinks(String text) {
ArrayList links = new ArrayList();
String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&##/%?=~_()|!:,.;]*[-A-Za-z0-9+&##/%=~_()|]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while(m.find()) {
String urlStr = m.group();
if (urlStr.startsWith("(") && urlStr.endsWith(")")) {
urlStr = urlStr.substring(1, urlStr.length() - 1);
}
links.add(urlStr);
}
return links;
}
change input type of your EditText ---- android:inputType="textUri"
and get your url using --- String url=edittext.getText().toString();
Check this library: (https://github.com/robinst/autolink-java)
compile "org.nibor.autolink:autolink:0.7.0"
Working fine with Android.
Example:
LinkExtractor linkExtractor = LinkExtractor.builder()
.linkTypes(EnumSet.of(LinkType.URL))
.build();
Iterable<LinkSpan> links = linkExtractor.extractLinks(String_with_Link");
LinkSpan link = links.iterator().next();
link.getType(); // LinkType.URL
link.getBeginIndex(); // 17
link.getEndIndex(); // 32
final_Url = String_with_Link.substring(link.getBeginIndex(), link.getEndIndex());
I was using JSONParser to obtain results of a search, for that I followed this tutorial: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
The thing is that, the API I am using gives the results like this:
{"response":[50036,{"aid":88131498,"owner_id":61775052,"artist":"Terror Squad","title":"Lean Back (OST Need For Speed Underground 2)","duration":249,"url":"http:\/\/cs4408.vkontakte.ru\/u59557424\/audio\/7f70f58bb9b8.mp3","lyrics_id":"3620730"},{"aid":106963458,"owner_id":-24764574,"artist":"«Dr. Dre ft Eminem, Skylar Grey (Assault Terror)","title":"I Need A Doctor (ASSAULT TERROR DUBSTEP REMIX)»","duration":240,"url":"http:\/\/cs5101.vkontakte.ru\/u79237547\/audio\/12cd12c7f8c2.mp3","lyrics_id":"10876670"}]}
My problem comes when I have to parse the first integer (here it is 50036) which is the number of results found.
I don't know how to read that integer.
This is my code:
private void instance(String artisttrack){
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String jsonurl = new String( "https://api.vk.com/method/audio.search?access_token=ACC_TOKEN&api_id=ID&sig=SIG&v=2.0&q=" + artistname + artisttrack + "&count=5");
JSONObject json = jParser.getJSONFromUrl(jsonurl);
try {
// Getting Array of Contacts
response = json.getJSONArray(TAG_RESPONSE);
// looping through All Contacts
for(int i = 0; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
// Storing each json item in variable
//int results = Integer.parseInt(c.getString(TAG_RESULTS));
String aid = c.getString(TAG_AID);
String owner_id = c.getString(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
String duration = c.getString(TAG_DURATION);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
String url = c.getString(TAG_URL);
String lyrics_id = c.getString(TAG_LYRICS_ID);
Log.e("áaaaaaaaaaaaaaa", url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The JSONParser.java is like written in the tutorial.
And here 2 lines of the logcat error:
W/System.err(10350): org.json.JSONException: Value 50036 at 0 of type java.lang.Integer cannot be converted to JSONObject
W/System.err(10350): at org.json.JSON.typeMismatch(JSON.java:100)
Your JSON sample is a poor way to organize the results: mixing the number in with the result objects. Is the number supposed to indicate the number of objects in the array or something else?
If you can assume that this number will always be the first element, and according to this then it's supposed to work this way, you can try to read the first value of the array outside the loop:
response = json.getJSONArray(TAG_RESPONSE);
// from your example, num will be 50036:
num = response.getInt(0);
for (int i = 1; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
Note that the example in the linked documentation has this number as a string:
{"response":
["5",
{"aid":"60830458","owner_id":"6492","artist":"Noname","title":"Bosco",
"duration":"195","url":"http:\/\/cs40.vkontakte.ru\/u06492\/audio\/2ce49d2b88.mp3"},
{"aid":"59317035","owner_id":"6492","artist":"Mestre Barrao","title":"Sinhazinha",
"duration":"234","url":"http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"}]}
But JSONArray.getInt() will parse the String as an int for you.
And notice that some of the values in the objects in your array are also numbers, you may want to read those as int also:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
int duration = c.getInt(TAG_DURATION);
A lot of the values you are trying to parse in are not String objects, specifically "aid", "owner_id", and "duration". Use the correct method to retrieve values. For example:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
int duration = c.getInt(TAG_DURATION);
edit: Another error that I missed is you start your array with 50036. This is not a JSONObject and cannot be parsed as so. You can add a conditional statement to check if it's array index 0 to parse the int using getInt(), and then parse as JSONObjects for the rest of the array values.
Try changing
response = json.getJSONArray(TAG_RESPONSE);
into
response = (JSONObject)json.getJSONArray(TAG_RESPONSE);
I dont have any experience with JSONObject, but works often with type mismatches.
Try putting 50036 in quotes like this "50036" .