Error: android unable to parse JSON with Android - android

I am new to Android Programming, I am trying to parse JSON with android
and trying to invoke the web service from this yahoo URL:
http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select+*+from+yahoo.finance.quote+where+symbol+in+(%22MSFT%22)
Error: However, I get error when I try to run this simple application on the emulator:
code:
MainActivity.java
package com.example.jsonparser;
public class MainActivity extends Activity {
//The JSON Rest Service I will pull from:
static String yahooStockInfo ="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22MSFT%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
//Will hold the values I pull from the JSON
static String stockSymbol = "";
static String stockDaysLow = "";
static String stockDaysHigh = "";
static String stockChange = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Call for doInBackground() in MyAsyncTask to be executed
new MyAsyncTask().execute();
}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute
private class MyAsyncTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... arg0) {
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(yahooStockInfo);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the
// Buffer is full
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer untilnothing is left
while ((line = reader.readLine()) != null)
{
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the InputStream when you're done with it
try{if(inputStream != null)inputStream.close();}
catch(Exception e){}
}
// Holds Key Value pairs from a JSON source
JSONObject jsonObject;
try {
// Print out all the data read in
// Log.v("JSONParser RESULT ", result);
// Delete cbfunc( and ); from the results
result = result.substring(7);
result = result.substring(0, result.length()-2);
// Get the root JSONObject
jsonObject = new JSONObject(result);
// Get the JSON object named query
JSONObject queryJSONObject = jsonObject.getJSONObject("query");
// Get the JSON object named results inside of the query object
JSONObject resultsJSONObject = queryJSONObject.getJSONObject("results");
// Get the JSON object named quote inside of the results object
JSONObject quoteJSONObject = resultsJSONObject.getJSONObject("quote");
// Get the JSON Strings in the quote object
stockSymbol = quoteJSONObject.getString("symbol");
stockDaysLow = quoteJSONObject.getString("DaysLow");
stockDaysHigh = quoteJSONObject.getString("DaysHigh");
stockChange = quoteJSONObject.getString("Change");
// EXTRA STUFF THAT HAS NOTHING TO DO WITH THE PROGRAM
Log.v("SYMBOL ", stockSymbol);
Log.v("Days Low ", stockDaysLow);
Log.v("Days High ", stockDaysHigh);
Log.v("Change ", stockChange);
// GET ARRAY DATA
JSONArray queryArray = quoteJSONObject.names();
List<String> list = new ArrayList<String>();
for (int i=0; i<queryArray.length(); i++) {
list.add( queryArray.getString(i) );
}
for(String item : list){
Log.v("JSON ARRAY ITEMS ", item);
}
// END OF GET ARRAY DATA
// Gets the first item in the JSONObject
JSONArray objectArray = resultsJSONObject.names();
// Prints out that first item in the JSONObject
Log.v("JSON NEXT NODE ", objectArray.getString(0));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result) {
// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
// Change the values for all the TextViews
line1.setText("Stock: " + stockSymbol + " : " + stockChange);
line2.setText("Days Low: " + stockDaysLow);
line3.setText("Days High: " + stockDaysHigh);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
code main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="#+id/line1"
style="#android:style/TextAppearance.Medium"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/line2"
style="#android:style/TextAppearance.Medium"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/line3"
style="#android:style/TextAppearance.Medium"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
please help me out, iam eager to learn

The url to get json from
Not knowing the actual error it's hard to see whats wrong with your code but looking at the json result from the url you are trying to parse I noticed that it doesn't start with cbfunc( which you're trying to clean up in the rows:
// Delete cbfunc( and ); from the results
result = result.substring(7);
result = result.substring(0, result.length()-2);
This means you're just corrupting the json just before trying to parse it. It's better to do the clean up with regex and String.replaceFirst(...) or just plain old String.replace(...).

Related

How to parse unnamed JSON Array in Android app

I have a JSON array sent from my SQL server via PHP in the following format which I am finding difficult to parse without encountering errors.
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
{
"placename": "place2",
"latitude": "51",
"longitude": "-0.5",
"question": "place2 existed when?",
"answer1": "800",
"answer2": "1000",
"answer3": "1200",
"answer4": "1400",
"correctanswer": "800"
},
{
"placename": "place3",
"latitude": "52",
"longitude": "-1",
"question": "place 3 was established when?",
"answer1": "2001",
"answer2": "2005",
"answer3": "2007",
"answer4": "2009",
"correctanswer": "2009"
}
]
I have verified my JSON at JSONLint and it comes up as valid. I have also used log code to print out my JSON in the Eclipse app debugger after my HTTP client has processed it and that also works fine (it shows the JSON as above so I know it has downloaded correctly).
I'm trying to fit the JSON Parser into the following activity but all my attempts thus far have either contained too many errors to run or have simply returned no results because of JSON parsing errors.
Here is the code of the main activity. The code for this activity is adapted from NewThinkTank.com (Android Development 15) and I'm trying to tweak it for my needs but the structure of the JSON used in the example is very different to mine.
I was hoping someone could suggest some code, or give me some pointers, as to how I could go about parsing this JSON array properly. I am fairly new to Android programming so this is a fairly steep task to figure out on my own.
Thanks for your time.
public class MainActivity extends Activity {
// The JSON REST Service I will pull from
static String dlquiz = "http://exampleserver.php";
// Will hold the values I pull from the JSON
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
#Override
public void onCreate(Bundle savedInstanceState) {
// Get any saved data
super.onCreate(savedInstanceState);
// Point to the name for the layout xml file used
setContentView(R.layout.main);
// Call for doInBackground() in MyAsyncTask to be executed
new MyAsyncTask().execute();
}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute
private class MyAsyncTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(dlquiz);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the Buffer is full
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer untilnothing is left
while ((line = reader.readLine()) != null)
{
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the InputStream when you're done with it
try{if(inputStream != null)inputStream.close();}
catch(Exception e){}
}
//this allowed me to verify the JSON download in the debugger
Log.v("JSONParser RESULT ", result);
// JSON parsing needs to happen here...
return result;
}
protected void onPostExecute(String result){
// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
// Change the values for all the TextViews
line1.setText("Place Name: " + placename);
line2.setText("Question: " + question);
line3.setText("Correct Answer: " + correctanswer);
}
}
}
Check this answer out: How to parse JSON in Android
You'll be using:
JSONArray array = new JSONArray(result);
From there, you'll loop through and get each JSONObject:
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
//now, get whatever value you need from the object:
placename = obj.getString("placename");
//or if on the MainUI thread you can set your TextView from here:
yourTextView.setText(obj.getString("placename"));
}
Good luck!

How parse a simple string that contains xml tags (need to read two tags)

I'm using a class to read the content of a web page (it contains text like xml) and save it in a string variable. It is working correctly. What i need to do now is found the value of some tags inside this string.
So this is the class that read the page. As you can see there is the method "onPostExecute" that is where i need to read the tags.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient(); //create a new http client
HttpGet httpGet = new HttpGet(url); //create a new http request passing a valid url
try {
HttpResponse execute = client.execute(httpGet); //try to execute the http get request
InputStream content = execute.getEntity().getContent(); //prepare the input stream to read the bytes of the request
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s; //until is present a line to read, the response variable store the value of the lines
}
} catch (Exception e) {
Log.i("MyApp", "Download Exception : " + e.toString()); //Print the error if something goes wrong
}
}
Log.i("RESPONSE",""+response);
return response; //return the response
}
#Override
protected void onPostExecute(String result) {
result = webPage.doInBackground(initConfiguration); //take the result from the DownloadWebPageTask class
Log.i("RESULT",""+result);
//find the price and format value from the result
}
}
So now what can i do? Have you some suggestions? Have i to use some kind of xml parser? I need something easy to use because i have only to read one or two tags.
This is an example of the string that contains the tags:
<products currency="EUR">
<product id="1" width="1796" height="1228" name="10 X 15 cm">
<prices>
<price fixfee="0.5" from="50" price="0.65" />
<price fixfee="0.10" from="20" price="0.70" />
<price fixfee="0.10" from="0" price="0.75" />
</prices>
</product>
<product id="2" width="3626" height="2422" name="20 X 30 cm">
<prices>
<price fixfee="0.5" from="50" price="0.75" />
<price fixfee="0.10" from="20" price="0.80" />
<price fixfee="0.10" from="0" price="0.100" />
</prices>
</product>
Thanks
I suggest you to use Jsoup library. here is good example that can serve you:
String html = "<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\">" +
" <book>" +
" <string> book name </string>" +
" <array>" +
" <string> Name1 </string>" +
" <string> Name2 </string>" +
" </array>" +
" </book></xml>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
Element book = doc.select("book").first();
Element bookName = book.getElementsByTag("string").first();
Elements array = book.getElementsByTag("array");
for (Element e : array.select("string")) {
//....
}
However Android today has his one parser XmlPullParser.
So you can try both options,
Hope it will help you
You can parse the incoming xml using android default xml parser. better to use Simple XML parser take a look here.

org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

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();
}

How do I prevent my app from crashing unexpectedly, "force close", when using JSON data, and handle the exception instead?

In my application, I have a food activity in which the user enters his/her food, and the app requests the food, by the name entered by the user, from a MYSQL database. In the case that the entered food not exist, the string returned by the database should be null.
Currently, when this happens, an exception to occurs since the null value cannot be parsed to a JSON array. My question is: "Is there a way to prevent my app from force closing? Can I handle the exception and display a toast notifying the user that the requested food was not found?" I would like to prevent the app from crashing, and, rather, fail gracefully.
Please help me.
I've shown the relevant code in my application..
private class LoadData extends AsyncTask<Void, Void, String>
{
private JSONArray jArray;
private String result = null;
private InputStream is = null;
private String entered_food_name=choice.getText().toString().trim();
protected void onPreExecute()
{
}
#Override
protected String doInBackground(Void... params)
{
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/food.php");
nameValuePairs.add(new BasicNameValuePair("Name",entered_food_name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//convert response to string
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result =sb.toString();
result = result.replace('\"', '\'').trim();
}
catch(Exception e){
Log.e("log_tag", " connection" + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result)
{
try{
String foodName="";
int Description=0;
jArray = new JSONArray(result); // here if the result is null an exeption will occur
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
foodName=json_data.getString("Name");
.
.
.
.
.
}
catch(JSONException e){
**// what i can do here to prevent my app from crash and
// make toast " the entered food isnot available " ????**
Log.e("log_tag", "parssing error " + e.toString());
}
}
}
This will fix your code:
jArray = (result == null) ? new JSONArray() : new JSONArray(result);
Now that you have an empty JSONArray, you will be able to test for null JSONObjects later in your program. Many of the JSON methods return a JSONObject if one is found, of null if none exists.
You might also want to initialize your JSONObject with the no-argument JSON constructor, rather than simply setting it to null. It will avoid problems when passing it to other JSON methods (such as using it in a constructor to a JSONArray():
JSONObject json_data = new JSONObject();
Finally, if you're still getting JSONExceptions, it's because you're not actually passing a valid JSON string to the constructor. You can print out the value of result to the log:
Log.d("JSON Data", result);
You may see some SQL error text or if you retrieve from a web server, then an HTTP error code (404 is common if you don't have your url correct).
If your result does look like JSON, then you can verify whether it's actually valid JSON or not using the JSONLint validator. It will help you catch any errors you may have, especially if you're formatting the JSON yourself.
Are you looking to capture the Exception and log it (remotely) to aid in crash reporting and debugging? I've used this package to remotely capture Exceptions and it works pretty good:
http://code.google.com/p/android-remote-stacktrace/

Android connectivity with MySQL

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.

Categories

Resources