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
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 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;
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();
Here I want to display the JSON content using API key. But I am unable to get the authentication.
I am getting the error in JsonObject:
org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONObject
In my android application, I just pass the API key and URL id to get the JSON response in the following URL. I display the JSON content using JSON array.
But if I:
public class AndroidAPiActivity extends Activity {
/*
* FlickrQuery = FlickrQuery_url
* + FlickrQuery_per_page
* + FlickrQuery_nojsoncallback
* + FlickrQuery_format
* + FlickrQuery_tag + q
* + FlickrQuery_key + FlickrApiKey
*/
String FlickrQuery_url = "http://192.138.11.9/api/interests/";
String FlickrQuery_per_page = "&per_page=1";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "f65215602df8f8af";
EditText searchText;
Button searchButton;
TextView textQueryResult, textJsonResult;
ImageView imageFlickrPhoto;
Bitmap bmFlickr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
searchText = (EditText)findViewById(R.id.searchtext);
searchButton = (Button)findViewById(R.id.searchbutton);
textQueryResult = (TextView)findViewById(R.id.queryresult);
textJsonResult = (TextView)findViewById(R.id.jsonresult);
imageFlickrPhoto = (ImageView)findViewById(R.id.flickrPhoto);
searchButton.setOnClickListener(searchButtonOnClickListener);
}
private Button.OnClickListener searchButtonOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
String searchQ = searchText.getText().toString();
String searchResult = QueryFlickr(searchQ);
textQueryResult.setText(searchResult);
String jsonResult = ParseJSON(searchResult);
textJsonResult.setText(jsonResult);
if (bmFlickr != null){
imageFlickrPhoto.setImageBitmap(bmFlickr);
}
}};
private String QueryFlickr(String q){
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private String ParseJSON(String json){
String jResult = null;
bmFlickr = null;
String key_id;
String category;
String subcategory;
String title;
String icon_image;
try
{
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("interests");
JSONArray JsonArray_photo = Json_photos.getJSONArray("interest");
//We have only one photo in this exercise
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(0);
key_id = FlickrPhoto.getString("row_key");
category = FlickrPhoto.getString("category");
subcategory = FlickrPhoto.getString("subcategory");
title = FlickrPhoto.getString("title");
jResult = "\n key_id: " + key_id + "\n"
+ "category: " + category + "\n"
+ "subcategory: " + subcategory + "\n"
+ "title: " + title + "\n";
bmFlickr = LoadPhotoFromFlickr(key_id, category, subcategory,title);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jResult;
}
private Bitmap LoadPhotoFromFlickr(
String key_id, String category, String subcategory,
String title){
Bitmap bm= null;
String icon_image = null;
// String FlickrPhotoPath ="";
String FlickrPhotoPath ="http://182.72.180.34/media/"+icon_image+".jpg";
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection = (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
}
Update:
Based on the HTML response, I can tell you that this is not JSON. The response tells me that you have the incorrect URL for your web service.
You need to check your URL.
Extra Info / Previous Answer:
It looks like the simple answer is the right one - your result is not a valid JSON string. See JSON.org website for details on what JSON should look like.
Check out JSON Parser Online - I find its very useful when working with JSON.
It is strange that you are requesting JSON, and it is not returning it properly - perhaps I have missed something.
Yes, we get such kind of warning when the given URL is not valid.
Just check the URL once.
Remove docType from API. and set content Type Application/json .
(as text/html will not read as json . thus you were seeing the error.)
May be this can help
https://teamtreehouse.com/community/solved-exception-cannot-convert-string-type-to-json-object
Solved.
It turns out the runtime error stretched back to the previous video.
I was doing
JSONObject currently = new JSONObject("currently");
instead of
JSONObject currently = forecast.getJSONObject("currently");
So my guess is Android thought I was trying to setup an entirely new JSON object instead of trying to retrieve information from an existing one! :) Now the console displays the time perfectly!
I've faced this issue too, I changed my Internet connection to another network and it works.
The problem was that ISP doesn't accept http access.
Another solution you can open VPN and try again, and maybe it works...
HOW I FIXED THE FOLLOWING ERRORS:
=============================================================================
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
org.json.JSONException: Value permissions of type java.lang.String cannot be converted to JSONObject
==============================================================================
This might not apply to this particular scenario, but it comes up as a top search result for the given issue/keyword.
So, i bought a script from a professional vendor on codecanyon.
The script consisted of 3x main parts;
- MAIN CART SITE (PHP)
- MAIN ADMIN SITE + /API (PHP)
- ANDROID ADMIN APP (JAVA)
I found many issues once the script was installed. Ranging from incomplete or missing table arrays on the MAIN CART SITE, then i had a problem on the ANDROID ADMIN APP that (upon inspection of logs) revealed a mysqli_exception was to blame.
So after hours of messing around with loops and trying to figure out where the issue was. After actually learning how to dump output to the logs / logcat. I was able to determine that it was in actual fact, a;
BREAKING CHANGE SINCE MYSQL-8
TO FIX, RUN THE FOLLOWING COMMANDS IN mysql TERMINAL;
SET GLOBAL sql_mode = '';
SET SESSION sql_mode = '';
THIS REMOVES THE 'STRICT MODE' amongst other rules that has caused me so much grief over the last few days. Thought i'd better share the answer, hopefully save someone else days of eye-drying torment =].
Remember to reintroduce the default ruleset one rule at a time and test to see what modes your app can support (if this solution fixes your problem) as they are no doubt essential security/data-integrity measures that are there for good reason. Ideally, update codebase to comply with current standards. Unfortunately that's way beyond me at this stage.
Hope this works for you guys.
I received the same "<!Doctype..." error when working with Google Translate's json URLs. Then, I found this code somewhere and it worked :
BasicHttpParams basicHttpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout((HttpParams)basicHttpParams, (int)10000);
HttpConnectionParams.setSoTimeout((HttpParams)basicHttpParams, (int)10000);
HttpConnectionParams.setTcpNoDelay((HttpParams)basicHttpParams, (boolean)true);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient((HttpParams)basicHttpParams);
HttpGet httpGet = new HttpGet(url);
BasicResponseHandler basicResponseHandler = new BasicResponseHandler();
JSONObject json=null;
try {
json = new JSONObject((String)defaultHttpClient.execute((HttpUriRequest)httpGet, (ResponseHandler)basicResponseHandler));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I am developing a final year project where I need to connect Android emulator with MySQL database in order to retrieve values. Java file:
public class connectivity extends Activity {
/** Called when the activity is first created. */
TextView txt;
public static final String KEY_121 = "http://10.0.2.2/mysqlcon.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
// call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
private String getServerData(String returnString) {
InputStream is = null;
String result = null;
// the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1970"));
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Log.i("log_tag", "id: " + json_data.getInt("id") + ", name: " + json_data.getString("name") + ", sex: " + json_data.getInt("sex") + ", birthyear: " + json_data.getInt("birthyear"));
// Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
I have also given an internet permission in my Android manifest file. But after running the application I get the following error in logcat:
ERROR PARSING DATA org.json.JSONException:A JSONArraytext must start with '[' at character 0
I think this goes to show that a null value is being returned. Please help me out as this is my final year project. I have spent hours trying to find the solutions but it has been of no use.
I am currently using Android 2.2. The wamp server is on the localhost so I am using the address 10.0.2.2 which is a special alias to localhost (127.0.0.1). Any help will be really appreciated.
Here is the PHP code:
<?php
mysql_connect("127.0.0.1","root","chetan");
mysql_select_db("db1");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output,JSON_FORCE_OBJECT));
mysql_close();
This is actually an issue I've run into before. The problem is your server isn't outputting valid JSON. It's missing some of the markup. I suggest you print the raw text of the response to Logcat and examine it. Perhaps even pass it into a JSON validator. That will also help you figure out if it is returning an empty value. If it's returning an empty value, then you'll need to debug your server...not your client...
Additionally, try visiting the php page from your browser and letting it simply display the JSON response. This will allow you to see what's being written by the server and help you determine where the problem really is. Just be aware, because the server is expecting a POST the easiest way to test this would probably to be to create a simple html form to POST the test data to that page. Without doing that, getting a browser to do a POST on it's own can be a pain.
do u need to use connection to php??? if not you can directly connect to mysql db to retrieve the result:
// Assume function to be :
public String customerData() {
String customerInfo = ""; //To store result
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://10.0.2.2:3306/retailer","root","pswrd");
PreparedStatement statement = con.prepareStatement("SELECT * FROM customers");
ResultSet result = statement.executeQuery();
while(result.next()) {
customerInfo = customerInfo + result.getString("name") + "&" +
result.getString("C_ID") + "&" + result.getString("address") +
"&" + result.getString("email");
// Here "&"s are added to the return string. This is help to split the
// string in Android application
}
} catch(Exception exc) {
System.out.println(exc.getMessage());
}
return customerInfo;
}
But to your project library include Connector jar file for Mysql.