I am trying to get data by using API. I get data in bufferedreader which contains multiple lines. But I am not able to extract that in a String. I do know that bufferedreader has data, i have checked by displaying it using multiple .readLine(); but the loop doesn't work.
protected String[][] doInBackground(Cursor[] cursors)
{
String list[][] = new String[cursors[0].getCount()][2];
//while(cursors[0].moveToNext())
{
String DATA="",temp;
String baseAddress="http://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY";
String apiKey="J63P";
Uri Url = Uri.parse(baseAddress)
.buildUpon()
.appendQueryParameter("symbol","SBIN")
.appendQueryParameter("interval","1min")
.appendQueryParameter("apikey",apiKey)
.build();
Log.d("built URL",Url.toString());
try
{
url= new URL(Url.toString());
urlconnection= (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("GET");
urlconnection.connect();
InputStream inputStream = urlconnection.getInputStream();
if (inputStream==null)
{
Log.d("inputstream","empty");
return null;
}
BufferedReader reader= new BufferedReader(new InputStreamReader(inputStream));
while((temp = reader.readLine())!=null)
{
DATA.concat(temp);
}
Log.d("unedited",DATA);
}
catch(IOException e)
{
Log.e("createList", "Error in url ", e);
return null;
}
try {
String List = "Time Series (1min)";
JSONObject full = new JSONObject(DATA);
JSONArray permin = full.getJSONArray(List);
for (int i=0;i<permin.length();i++)
{
String open,high,low,close;
JSONObject current = permin.getJSONObject(i);
open = current.getString("1. open");
high = current.getString("2. high");
low = current.getString("3. low");
close = current.getString("4. close");
Log.d("Extracted ",open + " " + high + " " + low + " " + close +"\n");
}
}
catch (JSONException e)
{
Log.e("createList","Error in json",e);
}
}
return list;
}
and Log is:
04-24 14:34:52.009 3574-3619/lcukerd.com.stocknotifier D/built URL: http://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=SBIN&interval=1min&apikey=J63P
04-24 14:34:53.723 3574-3619/lcukerd.com.stocknotifier E/createList: Error in json
org.json.JSONException: End of input at character 0 of
at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at lcukerd.com.stocknotifier.MainActivity$createList$override.doInBackground(MainActivity.java:123)
at lcukerd.com.stocknotifier.MainActivity$createList$override.access$dispatch(MainActivity.java)
at lcukerd.com.stocknotifier.MainActivity$createList.doInBackground(MainActivity.java:0)
at lcukerd.com.stocknotifier.MainActivity$createList.doInBackground(MainActivity.java:69)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Also, note that "Log" statement after inner while loop is also not working.
Pls, Help me Solve it.
You got exception in the Json data, it is very clear from the log, it says:
04-24 14:34:53.723 3574-3619/lcukerd.com.stocknotifier E/createList:
Error in json
Oh yeah:
Change this line:
DATA.concat(temp);
To
data = DATA.concat(temp);
Also in java it's better to write it this way:
data += temp;
Related
I am using below code to "GET" data using alpha Vantage API. It was working before for about 2 months then it suddenly stopped working. I don't see any change in JSON data.
private int retrievefromnet(int count,String symbol)
{
String temp;
String baseAddress = "http://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY";
String apiKey = "J63P";
Uri Url = Uri.parse(baseAddress)
.buildUpon()
.appendQueryParameter("symbol", symbol)
.appendQueryParameter("interval", "1min")
.appendQueryParameter("apikey", apiKey)
.build();
Log.d("createList","built URL: " +Url.toString());
try {
url = new URL(Url.toString());
urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("GET");
urlconnection.connect();
InputStream inputStream = urlconnection.getInputStream();
if (inputStream == null) {
return 0;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
Log.d("createList","here");
while ((temp = reader.readLine()) != null) {
DATA[count] += temp;
}
Log.d("unedited", DATA[count]);
} catch (IOException e) {
Log.e("createList", "Error in url ", e);
return 0;
}
return 1;
}
For extraction of data from JSON.
try {
String List = "Time Series (1min)";
JSONObject jsonObject = new JSONObject(DATA[count]);
jsonObject = jsonObject.getJSONObject(List);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis() - 34200000 );
String currtime = sdf.format(calendar.getTime());
Log.d("currtime",currtime);
jsonObject = jsonObject.getJSONObject(currtime);
return jsonObject.getString("4. close");
} catch (JSONException e) {
Log.e("createList", "Error in json");
}
Log says This:
D/createList: built URL: http://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=J63P
D/libc: [NET] android_getaddrinfofornetcontext+,hn 19(0x7777772e616c70),sn(),hints(known),family 0,flags 1024, D/libc: [NET] android_getaddrinfo_proxy get netid:0
D/libc: [NET] android_getaddrinfo_proxy-, success
D/createList: here
E/createList: Error in json
Notice that the last log statement of try block in retreivefromnet is not showing nor is the log of the catch block.
DATA[] is a string array. It has been initialised before. Also, I checked that reader is null.
Help me find the issue.
EDit for Abhishek:
06-23 14:25:37.315 16817-16980/lcukerd.com.stocknotifier E/createList: Error in json
org.json.JSONException: End of input at character 0 of
at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at lcukerd.com.stocknotifier.MainActivity$PlaceholderFragment$createList.workonJson(MainActivity.java:596)
at lcukerd.com.stocknotifier.MainActivity$PlaceholderFragment$createList.doInBackground(MainActivity.java:404)
at lcukerd.com.stocknotifier.MainActivity$PlaceholderFragment$createList.doInBackground(MainActivity.java:376)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
You are having JSON parsing issue. It is better to use GSON library to parse JSON.
EX:
Gson gson = new Gson();
YOUR_OBJECT response = gson.fromJson("your_json_string", YOUR_OBJECT.class);
You can use online tool to create java object from json.
EX: http://www.jsonschema2pojo.org/
TRY THIS:
public int retrievefromnet(int count, String symbol) {
String temp;
String baseAddress = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY";
String apiKey = "J63P";
Uri Url = Uri.parse(baseAddress)
.buildUpon()
.appendQueryParameter("symbol", symbol)
.appendQueryParameter("interval", "1min")
.appendQueryParameter("apikey", apiKey)
.build();
try {
URL url = new URL(Url.toString());
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("GET");
urlconnection.connect();
InputStream inputStream = urlconnection.getInputStream();
if (inputStream == null) {
return 0;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
Log.d("createList", "here");
String responseStr = "";
while ((temp = reader.readLine()) != null) {
responseStr += temp;
}
Log.d("unedited", responseStr);
} catch (IOException e) {
Log.e("createList", "Error in url ", e);
return 0;
}
return 1;
}
To find the issue use this code e.printStackTrace(); in your catch block and share the logs along with the stack trace of the Exception object
it seems to be that the format of the content of the json data has changed, have you check the json content, it have been modified. Could you compare a good json processed before with this new?
Sorry for my english
It was simple. I just needed to replace HTTP with HTTPS. AlphaVantage might have changed something that's why it worked earlier but not now. Everything working fine now.
I am making a http call to an api for a string response.
The result contains intentional % signs in a sentence like:
"This land is 95% fertail and 5% contaminated"
Android throws IllegalArgumentException: Invalid % sequence at 1756 which corresponds to the "95%" part.
EDIT: StackTrace:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IllegalArgumentException: Invalid % sequence at 1756: [{"address":{"addressComponen...
My httpGet method:
public String makeHttpGetRequestUtf8(String urlStr) throws IOException {
String result = "";
try {
URL url = new URL(urlStr);
BufferedReader brIn = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String line = "";
while ((line = brIn.readLine()) != null)
result += line;
}catch (Exception e){
Log.e("HTT_GET", "Failed to make httpGetRequestUtf8: " + e);
}
String afterDecode = URLDecoder.decode(result, "UTF-8");
return afterDecode;
}
Android throws IllegalArgumentException: Invalid % sequence at 1756 which corresponds to the "95%" part.
Server writes this data with this metod and so I believe the encoding should be fine?
File file = new File(path/filename.txt);
String content = writeMeToFile;
Writer out;
try{
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "UTF8"));
if(!file.exists()){
file.createNewFile();
}else{
FileUtils.copyFile(file, dest);
out.write(content);
out.close();
}
} catch (IOException e) {
Logger.getLogger(UpdateAds.class.getName()).log(Level.SEVERE, null, e);
}
Side question/note: Somehow characters like 'ä', 'ö', 'ü', 'õ' are fine in the browser but show up as � in android.
I don't understand at which side am I encoding the string wrong. Since the text is fine in the browser I am thinking it's android, but the httpGet method is done by the book.
Thanks!
I am using eclipse ADT for my android development. let me explain my problem. I can receive the response from my server api, the problem is, the data is very huge and am unable to display entire response in my logcat. I used AsynTask for getting response.
DoinBackground method
getBookingResults = ServerConnection.getbookings(
BookingsActivity.this, Utils.URL + "users/"
+ "123145/" + "subscribed");
This is my Get() in separate class
public static String getData(Context ctx, String uri) {
BufferedReader reader = null;
StringBuilder sb = null;
try {
Log.d("Serverconnection URL ", uri);
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(200000);
// save status code
Utils.statusCode = con.getResponseCode();
// String responseBody = EntityUtils.toString(response.getEntity());
sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("server connection getData", "" + sb.toString());
return sb.toString();
} catch (SocketTimeoutException e) {
Log.d("server connection getData Error ", "" + e);
} catch (IOException e) {
e.printStackTrace();
return " ";
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return " ";
}
}
}
return sb.toString();
}
When i am checking the response string in my logcat is shows string length 11743. The logcat is not displaying entire response
Help me out to handle huge data response
Thanks in advance
Thing is that you cannot blindly allocate all the data from server otherwise risk of OOM is very high. You should use technique similar to what android suggests with list, keep in memory only those elements visible to user. In other words, first you have to figure out what the size is or expect that size may be huge. Then load data chunk by chunk to some UI element and implement some kind of "load by scroll". In case you cannot load from the net as you scroll, perhaps due to nature of the connection, then you should load chunk by chunk and save the data to local store. And then display it chunk by chunk as described above. This is how I would do it. Sorry, not exactly the answer you look for.
I am building an app that connects to a blog then gathers the data in JSON. Currently I amgeting this error (sorry about all JSON dat not sure whether to include):
Exception Caught
org.json.JSONException: Unterminated string at character 6564 of {"status":"ok","count":20,"count_total":1727,"pages":87,"posts":[{"id":23419,"url":"http:\/\/blog.teamtreehouse.com\/happy-mothers-day-ones-whove-shaped-web-careers","title":"Happy Mother\u2019s Day! Thanks, Mom, for Helping Us Learn","date":"2014-05-08 11:00:29","author":"Ryan Brinks","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/mothers-dayHaik-Avanian-150x150.jpg"},{"id":23412,"url":"http:\/\/blog.teamtreehouse.com\/technology-brings-people-attitude-public-data-projects","title":"Public Data Brings ‘We the People’ Attitude to Technology","date":"2014-05-08 10:08:22","author":"Kelley King","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/adoptahydrant-150x150.jpg"},{"id":23409,"url":"http:\/\/blog.teamtreehouse.com\/help-students-learn-computer-programming","title":"A Push for More Computer Programming in Public Schools","date":"2014-05-07 15:50:51","author":"Tim Skillern","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/student-computer-class-woodleywonderworks-flickr-150x150.jpg"},{"id":23398,"url":"http:\/\/blog.teamtreehouse.com\/military-veterans-finding-technology-jobs-secure-bet","title":"Technology Jobs a Secure Bet for Military Veterans","date":"2014-05-06 13:45:13","author":"Anayat Durrani","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/durrani-kopser-150x150.jpg"},{"id":23407,"url":"http:\/\/blog.teamtreehouse.com\/typography-sidebars-style-guides-treehouse-show-ep-89","title":"Typography, Sidebars, Style Guides | The Treehouse Show Ep 89","date":"2014-05-06 10:15:43","author":"Jason Seifer","thumbnail":null},{"id":23393,"url":"http:\/\/blog.teamtreehouse.com\/5-tips-creating-perfect-web-design-portfolio","title":"5 Tips for Creating the Perfect Web Design Portfolio","date":"2014-05-05 17:55:08","author":"Nick Pettit","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/how-to-make-a-website-150x150.jpg"},{"id":23381,"url":"http:\/\/blog.teamtreehouse.com\/writing-tips-better-business-marketing","title":"11 Rules for Better Writing, or How Not to Use a Thesaurus","date":"2014-05-01 18:38:32","author":"Tim Skillern","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/pencils-wikimedia-150x150.jpg"},{"id":23387,"url":"http:\/\/blog.teamtreehouse.com\/web-job-perks-unlimited-vacation-catered-lunch-part-amazing-opportunity-weebly-com-programmer","title":"Web Job Perks: Unlimited Vacation, Catered Lunch Part of \u2018Amazing Opportunity\u2019 for Weebly.com Programmer","date":"2014-05-01 17:00:28","author":"Jimmy Alford","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/weebly-guy0-2-150x150.jpg"},{"id":23375,"url":"http:\/\/blog.teamtreehouse.com\/illustrator-ben-obrien-inspiration","title":"Noted Illustrator Ben O’Brien Talks About Finding Inspiration, Taking Chances","date":"2014-04-29 18:13:58","author":"Gillian Carson","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/04\/obrien3-150x150.jpg"},{"id":23373,"url":"http:\/\/blog.teamtreehouse.com\/gulp-sketch-3-bud-treehouse-show-episode-88","title":"Gulp | Sketch 3 | Bud | The Treehouse Show Episode 88","date":"2014-04-29 15:29:20","author":"Jason Seifer","thumbnail":null},{"id":23361,"url":"http:\/\/blog.teamtreehouse.com\/flexbox-next-generation-css-layout-arrived","title":"Flexbox: The Next Generation of CSS Layout Has Arrived","date":"2014-04-29 11:53:40","author":"Nick Pettit","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/04\/Screen-Shot-2014-04-28-at-1.00.03-AM-150x150.png"},{"id":23364,"url":"http:\/\/blog.teamtreehouse.com\/help-wanted-women-color-needed-technology-web-jobs","title":"Help Wanted: Women of Color Needed in Technology, Web Jobs","date":"2014-04-28 12:28:56","author":"Anayat Durrani","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/04\/poorn
This is where teh error is being caught:
public void updateList() {
if (mBlogData == null) {
// TODO: Handle Error
}
else {
try {
Log.d(TAG, mBlogData.toString(2));
}
catch (JSONException e) {
Log.e(TAG, "Exception Caught", e);
}
}
}
I am not sure what is causing this error so any suggestions are welcome. I can provide more code if needed. Thank You.
Just wanted to add to eMad's answer which helped me solve the same problem you are having. I hope this helps anybody who is to come after me because this darn bug killed 2 hours of my day (or night, I'm nocturnal). Well, with out further (ado? adieu?), here you go : P.S. the below code will go in your private class GetBlogPostsTask AsynnTask...
protected JSONObject doInBackground(Object... arg0) {
int responseCode = -1;
JSONObject jsonResponse = null;
try {
//set API URL
URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/? count=" + NUMBER_OF_POSTS);
//open URL connection
URLConnection connection = blogFeedUrl.openConnection();
//create BufferedReader to read the InputStream return from the connection
BufferedReader in = new BufferedReader(
new InputStreamReader ( connection.getInputStream() )
);
//initiate strings to hold response data
String inputLine;
String responseData = "";
//read the InputStream with the BufferedReader line by line and add each line to responseData
while ( ( inputLine = in.readLine() ) != null ){
responseData += inputLine;
}
//check to make sure the responseData is not empty
if( responseData!= "" ){
/*initiate the jsonResponse as a JSONObject based on the string values added
to responseData by the BufferedReader */
jsonResponse = new JSONObject(responseData);
}
/*return the jsonResponse JSONObject to the postExecute() method
to update the UI of the context */
return jsonResponse;
}
catch (MalformedURLException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (Exception e) {
Log.e(TAG, "Exception caught: ", e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
/* set the class' member JSONObject mBlogData to the result
to be used by the handleBlogResponse() method to update the UI */
mBlogData = result;
/*call the handleBlogResponse() method to update the UI with the result of this AsyncTask
which will be a JSONObject in best case scenario or a null object in worst case */
handleBlogResponse();
}
A friend of mine brought me a code that was generating the same output as yours. I think this is the solution that you're looking for. Given code is
// inside the class which connects to URL (Probably MainList)
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
jsonResponse = new JSONObject(responseData);
But don't know why using above code, you either not get the full string or get the ContentLenght right but the last few characters aren't received properly. Use following code instead which reads complete response:
URLConnection yc = blogFeedUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
responseData = "";
while ((inputLine = in.readLine()) != null) // read till you can receive any data
responseData += inputLine;
in.close();
I have an android application that use an external movies API in order to get content of a movie via HTTP request.
Every thing was going fine until the service change the domain used for movies queries , I can't create the JSON object to fetch the received content of the response into it.
Here is the snip of the code that do the work (it was working properly before they change the URL)
try {
Add.setEnabled(true);
movieContent.setText("");
URL url = new URL("http://www.omdbapi.com/?i=&t=" + searchET.getText().toString());
Log.d("URL content", url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
Log.d("URL content", "register URL");
urlConnection.connect();
Log.d("URL connection", "establish connection");
String res = null;
BufferedReader reader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
Log.d("stream buffer", "read the stream");
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
res = sb.toString();
Log.d("movie content", res);
JSONArray ja = new JSONArray(res);
Log.d("JSON array", "created");
JSONObject jo = ja.getJSONObject(0);
and here is the log cat snip of the logs:
02-25 21:28:42.287: D/Username passed(32500): joker
02-25 21:28:42.295: D/USERFINALSESSION(32500): 2
02-25 21:28:53.311: V/ViewRoot(32500): BACK _ IME finished event: seq=1, handled=true, action=0c4s158
02-25 21:28:53.311: V/ViewRoot(32500): BACK _ IME finished mView : com.android.internal.policy.impl.PhoneWindow$DecorView#405488f0
02-25 21:28:53.436: V/ViewRoot(32500): BACK _ IME finished event: seq=2, handled=true, action=1c4s158
02-25 21:28:53.436: V/ViewRoot(32500): BACK _ IME finished mView : com.android.internal.policy.impl.PhoneWindow$DecorView#405488f0
02-25 21:28:59.873: D/URL content(32500): http://www.omdbapi.com/?i=&t=ted
02-25 21:28:59.889: D/URL content(32500): register URL
02-25 21:29:02.037: D/URL connection(32500): establish connection
02-25 21:29:03.608: D/stream buffer(32500): read the stream
02-25 21:29:03.615: D/movie content(32500): {"Title":"Ted","Year":"2012","Rated":"R","Released":"29 Jun 2012","Runtime":"106 min","Genre":"Comedy, Fantasy","Director":"Seth MacFarlane","Writer":"Seth MacFarlane (screenplay), Alec Sulkin (screenplay), Wellesley Wild (screenplay), Seth MacFarlane (story)","Actors":"Mark Wahlberg, Mila Kunis, Seth MacFarlane, Joel McHale","Plot":"As the result of a childhood wish, John Bennett's teddy bear, Ted, came to life and has been by John's side ever since - a friendship that's tested when Lori, John's girlfriend of four years, wants more from their relationship.","Language":"English","Country":"USA","Awards":"Nominated for 1 Oscar. Another 6 wins & 21 nominations.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTQ1OTU0ODcxMV5BMl5BanBnXkFtZTcwOTMxNTUwOA##._V1_SX300.jpg","Metascore":"62","imdbRating":"7.1","imdbVotes":"315,192","imdbID":"tt1637725","Type":"movie","Response":"True"}
02-25 21:29:03.748: D/dalvikvm(32500): GC_CONCURRENT freed 177K, 47% free 3041K/5639K, external 2311K/2882K, paused 4ms+5ms
02-25 21:29:03.748: D/Cursor(32500): Database path: moviesGeeks
02-25 21:29:03.748: D/Cursor(32500): Table name : watched
02-25 21:29:03.748: D/Cursor(32500): Database path: moviesGeeks
02-25 21:29:03.748: D/Cursor(32500): Table name : users
what would be the problem ?
by the way the former URL was :http://mymovieapi.com
here is the code after edit the JSONArray into JSONObject:
#Dayan
res = sb.toString();
Log.d("movie content", res);
/*JSONArray ja = new JSONArray(res);
Log.d("JSON array", "created");
JSONObject jo = ja.getJSONObject(0);*/
JSONObject jo= new JSONObject(res);
st = "Title : " + jo.getString("Title");
movie[0] = st;
st = null;
Log.d("JSON", movie[0]);
st = "Directors : \n" +jo.getString("Director");
movie[1] = st;
st = null;
Log.d("JSON", movie[1]);
st = "Actors : \n"+ jo.getString("Actors");
movie[2] = st;
st = null;
Log.d("JSON", movie[2]);
st = "Runtime : " + jo.getString("Runtime");
movie[3] = st;
st = null;
Log.d("JSON", movie[3]);
st = "Release Year : " + jo.getString("Released");
movie[4] = st;
st = null;
Log.d("JSON", movie[4]);
st = "Rating : " + jo.getString("imdbRating");
movie[5] = st;
st = null;
Log.d("JSON", movie[5]);
st = "Description : \n" + jo.getString("Plot");
movie[6] = st;
st = null;
Log.d("JSON", movie[6]);
Log.d("before appending", movie[6] + "");
for (int i = 0; i < movie.length - 1; ++i) {
movieContent.append(movie[i] + "\n\n");
}
imageURL = jo.getString("Poster");
movie[7] = imageURL;
Log.d("image url", movie[7] + "");
// added jafar alali
// write Json content to a file
int c = 0;
for (String content : movie) {
if (c == 0) {
writefileInitial();
c++;
}
writeJsonFile(content, JsonFileToread);
}
try {
Bitmap bitmap = BitmapFactory
.decodeStream((InputStream) new URL(imageURL)
.getContent());
moviePoster.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
// TODO: handle exception
Log.d("poster", movie[7] + "");
} catch (IOException e) {
e.printStackTrace();
// TODO: handle exception
}
Add.setVisibility(View.VISIBLE);
addtolist.setVisibility(View.VISIBLE);
} catch (JSONException e) {
// TODO Auto-generated catch block
movieContent.setText("Film not found");
moviePoster.setImageBitmap(null);
Add.setVisibility(View.GONE);
addtolist.setVisibility(View.GONE);
} catch (IOException e) {
// TODO Auto-generated catch block
movieContent.setText("Error in Connection");
moviePoster.setImageBitmap(null);
Add.setVisibility(View.GONE);
addtolist.setVisibility(View.GONE);
}
catch (Exception e) {
movieContent.setText("Exception");
moviePoster.setImageBitmap(null);
Add.setVisibility(View.GONE);
addtolist.setVisibility(View.GONE);
}
// extract file content into a movie object to be inserted
movies tempMovie = new movies();
tempMovie.setTitle(movie[0]);
tempMovie.setDirector(movie[1]);
tempMovie.setActors(movie[2]);
tempMovie.setRuntime(movie[3]);
tempMovie.setYear(movie[4]);
tempMovie.setGrate(movie[5]);
tempMovie.setDescription(movie[6]);
tempMovie.setURL(movie[7]);
// insert movie into data base
// send object to data base movie inserter
try {
dbm.addMovie(tempMovie);
} catch (Exception e1) {
// TODO Auto-generated catch block
Toast tt = Toast.makeText(HomePage.this,
"Insertion failed", 3000);
tt.setGravity(Gravity.CENTER, 0, 0);
tt.show();
}
}
});
You are receiving a JsonObject in return and no more the JsonArray!
Change your code:
JSONArray ja = new JSONArray(res);
Log.d("JSON array", "created");
JSONObject jo = ja.getJSONObject(0);
for:
JSONObject jo = new JSONObject(res);
That should work!
Update
This works fine for me : http://rextester.com/live/ZKUZ3520
You should parse the text you are appending to the URI in your code:
URL url = new URL("http://www.omdbapi.com/?i=&t=" + searchET.getText().toString());
If you enter something such as "True Grit" it will respond with a 404:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: http://www.omdbapi.com/?t=True Grit
Because you are omitting the space, hence (%20)
http://www.omdbapi.com/?t=True%20Grit
Also, make sure to properly deserialize your JSON when received:
As stated by Rajesh CP, you are using the old API standard which apparently made used of Array instead of Object. So replace JSONArray ja = new JSONArray(res); with JSONObject movie = new JSONObject(res);
Here is the code I came up with after removing the JSON Deserialize to try and isolate the problem a bit more. This will properly fetch the JSON from the server without errors.
public static void main(String args[]) throws IOException
{
URL url = new URL("http://www.omdbapi.com/?i=&t=True%20Grit");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println(sb.toString());
}
Replace
JSONArray ja = new JSONArray(res);
With
JSONObject movie = new JSONObject(res);
Since your JSON String is this.
{"Title":"Ted","Year":"2012","Rated":"R","Released":"29 Jun 2012","Runtime":"106 min","Genre":"Comedy, Fantasy","Director":"Seth MacFarlane","Writer":"Seth MacFarlane (screenplay), Alec Sulkin (screenplay), Wellesley Wild (screenplay), Seth MacFarlane (story)","Actors":"Mark Wahlberg, Mila Kunis, Seth MacFarlane, Joel McHale","Plot":"As the result of a childhood wish, John Bennett's teddy bear, Ted, came to life and has been by John's side ever since - a friendship that's tested when Lori, John's girlfriend of four years, wants more from their relationship.","Language":"English","Country":"USA","Awards":"Nominated for 1 Oscar. Another 6 wins & 21 nominations.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTQ1OTU0ODcxMV5BMl5BanBnXkFtZTcwOTMxNTUwOA##._V1_SX300.jpg","Metascore":"62","imdbRating":"7.1","imdbVotes":"315,192","imdbID":"tt1637725","Type":"movie","Response":"True"}
{ -----> Represents JSONObject
[ -----> Represents JSONArray