Here is a sample of my json_encode in PHP:
print(json_encode($row));
leads to {"AverageRating":"4.3"} which is good.
But in Java, I can not seem to grab this 4.3 value. Here it is (for an Android project) I have edited non-relevant data.
public class Rate extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
String Item, Ratings, Review, starAvg;
RatingBar ratingsBar;
ArrayList<NameValuePair> param;
public void onCreate(Bundle savedInstanceState) {
starAvg = "0"; // Sets to 0 in case there are no ratings yet.
new starRatingTask().execute();
ratingsBar = (RatingBar) findViewById(R.id.theRatingBar);
class starRatingTask extends AsyncTask<String, String, Void> {
InputStream is = null;
String result = "";
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.---.com/---/average_stars.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("item", Item));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
String starAvgTwo = null;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
starAvg = json_data.getString("AverageRating");
starAvgTwo = starAvg;
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Star Ratings!",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
Toast.makeText(getBaseContext(), starAvgTwo,
Toast.LENGTH_LONG).show();
ratingsBar.setRating(Float.valueOf(starAvg));
}
}
That second toast produces a blank (I assume a "" - empty string?). If I change the toast variable back to starAvg, then it toasts "0".
How can I retrieve the value of 4.3.
As we discussed in the comments on the original question, the PHP is sending down as single JSONObject rather than an array. Parsing as a JSONObject is required in it's present state; however, if you begin sending down an array of your value objects, then you'd use JSONArray to parse it.
I think your JSON doesn't contain array. so just do this:
JSONObject jsonObject = new JSONObject(result); //to convert string to be a JSON object
String averageRating = jsonObject.getString("AverageRating"); //get the value of AverageRating variable
and try toast the averageRating.
and how to get the array from JSON object?
if you have JSON:
{"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }]
}
then use this code
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(Rate.class.getName(), jsonObject.getString("firstName"));
}
that code will produce
John Anna Peter
in your LogCat
Related
This is the URL which returns me the json object Link.
Now I need to get the json data to my code. When I try to access the link I get the html script. How do I get the json data from the above URL to my code. Here is my code.
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new
`ProgressDialog(MainActivity.this);`
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select1 = "http://andpermission.byethost5.com/PermissionList.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select1);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
//Toast.makeText(MainActivity.this, "Please Try Again", Toast.LENGTH_LONG).show();
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
//text_1 = (TextView)findViewById(R.id.txt1);
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
//String id = Jasonobject.getString("id");
String name = Jasonobject.getString("name");
String db_detail="";
if(et.getText().toString().equalsIgnoreCase(name)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
break;
}
//text_1.append(id+"\t\t"+name+"\t\t"+password+"\t\t"+"\n");
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Using string builder I append the content and I find only the java script and I don't find the json data. How to I get the json data from the above URL.
In string "Result" in my code I get the below output.
<html>
<body>
<script type="text/javascript" src="/aes.js"></script>
<script>
function toNumbers(d) {
var e = [];
d.replace(/(..)/g, function(d) {
e.push(parseInt(d, 16))
});
return e
}
function toHex() {
for (var d = [], d = 1 == arguments.length && arguments[0].constructor == Array ? arguments[0] : arguments, e = "", f = 0; f < d.length; f++) e += (16 > d[f] ? "0" : "") + d[f].toString(16);
return e.toLowerCase()
}
var a = toNumbers("f655ba9d09a112d4968c63579db590b4"),
b = toNumbers("98344c2eee86c3994890592585b49f80"),
c = toNumbers("b8eeb5e790c4a5395d01cde6b8230fdd");
document.cookie = "__test=" + toHex(slowAES.decrypt(c, 2, a, b)) + "; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";
location.href = "http://andpermission.byethost5.com/PermissionList.php?ckattempt=1";
</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
How do I get only the json data from the URL instead the java script.
Try the full URL: http://andpermission.byethost5.com/PermissionList.php?ckattempt=1.
And also make sure you are using GET instead of POST, because that's what the URL refers to.
Here a good example: http://www.learn2crack.com/2013/10/android-json-parsing-url-example.html
On the other hand, there are some libraries like Aquery, Okhttp and Volley, that do this job very good.
I am trying to access a json array from android. But it shows an exception. This is my android code used for retrieving the json array:
protected void showList(){
final String TAG_RESULTS="result";
final String TAG_USERNAME="username";
final String TAG_NAME = "message_recd";
final String TAG_ADD ="message_sent";
ArrayList<HashMap<String, String>> personList;
personList = new ArrayList<HashMap<String,String>>();
//for tesitng
JSONObject jObject=null;
//
try {
//for testing
//
JSONObject json = new JSONObject(myJSON);
JSONArray peoples =json.getJSONArray("emparray");
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null;
name = c.getString("user_id");
address = c.getString("crtloc_lat");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("user_id",name);
persons.put("crtloc_lat",address);
personList.add(persons);
Toast.makeText(MapsActivity.this, "woow id"+name, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("errore",e.toString());
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// nameValuePairs.add(new BasicNameValuePair("username", fName));
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://abh.netai.net/abhfiles/searchProfession.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
php file
<?php
require "config.php";
$con = mysqli_connect(HOST,USER,PASS,DB);
$pro_id=0;
$sql="SELECT user.user_id, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($con);
?>
and the json array
[[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769566","crtloc_lng":"72.361031"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}]
the error it show me is this
Value [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769749","crtloc_lng":"72.361168"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}] of type org.json.JSONArray cannot be converted to JSONObject
It is giving you this error because the first object in the array is not a JSONObject but an JSONArray following 4 JSONObjects.
[
[],
{
"user_id": "77",
"crtloc_lat": "34.769638",
"crtloc_lng": "72.361145"
},]
As you can see you expect it to always be a JSONObject.
JSONObject c = peoples.getJSONObject(i);
Anticipate on that first JSONArray in the list.
01-16 08:16:19.210: W/System.err(1394): org.json.JSONException: Value
{"GetDoctorsListResult":[
{"Name":"Sujay Sharma","DoctorID":154,"Clinics":null,"speciality":"Allergy and immunology","Locality":"Mumbai","Address":"Abcc Building "}
,{"Name":"Samir Tapiawala","DoctorID":159,"Clinics":null,"speciality":"Homeopath","Locality":"Mumbai","Address":"57\/101, Jawahar Nagar RD. NO. 6, GOREGAON WEST "}
,{"Name":"Sahil Kuma","DoctorID":171,"Clinics":null,"speciality":"Aerospace Medicine","Locality":"Mumbai","Address":"Digvija "}
,{"Name":"Himesh Jagtap","DoctorID":180,"Clinics":null,"speciality":"Bariatric Surgery","Locality":"Mumbai","Address":"Abc- Society "}
,{"Name":"Aarnav Prabhudesai","DoctorID":190,"Clinics":null,"speciality":"Dentistry","Locality":"Mumbai","Address":"Joyvilla Jawahar Nagar "}
,{"Name":"Neeharika Saxana","DoctorID":197,"Clinics":null,"speciality":"Gynaecologist","Locality":"Mumbai","Address":"Joyvilla, Jawahar Nagar "}
,{"Name":"Neeharika Saxena","DoctorID":205,"Clinics":null,"speciality":"Gynaecologist","Locality":"Mumbai","Address":"Joyvilla "}
,{"Name":"Ravi Sharma","DoctorID":207,"Clinics":null,"speciality":"Ayurvedacharya","Locality":"Mumbai","Address":"Q\/02 "}
,{"Name":"Prashant Bhatt","DoctorID":209,"Clinics":null,"speciality":"Dentistry","Locality":"Mumbai","Address":"202 Anand Vihar , Bldg No-2 , D-wing , Bhawani Chowk , b--cabin Road , Ambernath(e). Bhawani Chowk"}
,{"Name":"Samidha Sen","DoctorID":210,"Clinics":null,"speciality":"Addiction Medicine","Locality":"Mumbai","Address":"S\/09 "}
,{"Name":"Subodh Mehta","DoctorID":212,"Clinics":null,"speciality":"Orthopaedic Surgery","Locality":"Mumbai","Address":"Opera "}]} of type org.json.JSONObject cannot be converted to JSONArray
here is my activity code:
class DownloadTask extends AsyncTask<String, Void, Object> {
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(4000); // Do your real work here
} catch (InterruptedException e) {
e.printStackTrace();
}
return true; // Return your real result here
}
protected void onPostExecute(Object result) {
// Pass the result data back to the main activity
DoctorSearchActivity.this.data = result;
if (DoctorSearchActivity.this.progressdialog != null) {
DoctorSearchActivity.this.progressdialog.dismiss();
}
try {
JSONStringer geneology = new JSONStringer()
.object().key("Params").object().key("TypesOnSearch")
.value("name").key("CharactersToSearch")
.value("s")
.endObject();
JSONArray results = new JSONArray();
results = BC
.returnJSONArray(geneology,
"http://192.168.2.27/HYEHR_WCFService/DoctorService.svc/GetDoctorsList");
if (results.length() == 0) {
Toast.makeText(
DoctorSearchActivity.this,
"Error Occured while loading data.Try again later.",
Toast.LENGTH_LONG).show();
}
// for (int i = 0; i < results.length(); i++) {
// Log.v("data", results.getString(i));
// }
// aTable = BC.appendRows(aTable, results,
// DoctorSearchActivity.this);
} catch (Exception e) {
// TODO: handle exception
}
}
}
and my json function
:
public JSONArray returnJSONArray(JSONStringer JsonString, String url) {
results = new JSONArray();
try {
HttpPost request = new HttpPost(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string
StringEntity entity = new StringEntity(JsonString.toString());
request.setEntity(entity);
Log.v("data", request + JsonString.toString());
// Log.v("data sender",request.setEntity(entity));
// Send request to WCF service
DefaultHttpClient httpClient1 = new DefaultHttpClient();
HttpResponse response = httpClient1.execute(request);
Log.v("response code", response.getStatusLine().getStatusCode()
+ "");
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
results = new JSONArray(new String(buffer));
Log.v("results length : ", results.length() + "");
}
catch (Exception e) {
// i mean sending data without key
// TODO: handle exception
e.printStackTrace();
}
return results;
}
I am getting this error i am passing data in jsonobject and receiving data in jsonarray.
Try to replace this:
results = new JSONArray(new String(buffer));
by this:
results = new JSONObject(new String(buffer)).getJSONArray("GetDoctorsListResult");
The root element of the JSON from URL is a JSONObject you should first parse it to JSONObject and then
get GetDoctorsListResult which is an array from the object.
I think your First Element of object GetDoctorsListResult is JSON array . So you have to take its value in json array.
REFER THIS THREAD and THIS ONE
JSONArray DoctorsList= jsonResponse.getJSONArray("GetDoctorsListResult");
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jsonObject=new JSONObject(result);
JSONArray jsonArray=jsonObject.getJSONArray("GetDoctorsListResult");
use this code after getting response.
When i passing json data from Android to server , its howing following error at server at the time of parsing.org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
The servlet code is :
protected void doProcess(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
BufferedReader br = request.getReader();
String sCurrentLine;
StringBuilder sb = new StringBuilder();
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
System.out.println(sb.toString().substring(4));
try {
JSONArray jArray = new JSONArray(sb.toString().substring(4));
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
json_data.getString("dwsList");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Android portion is :
ArrayList<STRModel> strlist = StrDbHelper
.getPendingStrlist(Splash.this);
System.out.println("--------Inside------" + strlist.size());
if (strlist != null) {
String URL = "http://ip:8080/Admin/upload";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("str", new Gson()
.toJson(strlist)));
System.out.println(new Gson().toJson(strlist));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i("Response", response.getEntity().getContent()
.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
I'm passing from client as :
[
{"dwsList":
[
{"farmer_name":"JINJU","dws_date":"2013-03-08","farmer_code":"10004","dws_num":"53","dws_id":4,"bag_weight":3000.0,"net_weight":2000.0,"selected":false,"str_id":0,"totalBags":20},
{"farmer_name":"KANNAN","dws_date":"2013-03-08","farmer_code":"10005","dws_num":"54","dws_id":5,"bag_weight":1500.0,"net_weight":1000.0,"selected":false,"str_id":0,"totalBags":10}
],
"str_total_weight":4000.0,"str_date":"2013-03-08","str_number":"1003","str_id":4,"str_total_bag":0,"status":0,"selected":false}
]
when i print Json data in server its look like
str=%5B%7B%22dwsList%22%3A%5B%7B%22farmer_name%22%3A%22JINJU%22%2C%22dws_date%22%3A%222013-03-08%22%2C%22farmer_code%22%3A%2210004%22%2C%22dws_num%22%3A%2253%22%2C%22dws_id%22%3A4%2C%22bag_weight%22%3A3000.0%2C%22net_weight%22%3A2000.0%2C%22selected%22%3Afalse%2C%22str_id%22%3A0%2C%22totalBags%22%3A20%7D%2C%7B%22farmer_name%22%3A%22KANNAN%22%2C%22dws_date%22%3A%222013-03-08%22%2C%22farmer_code%22%3A%2210005%22%2C%22dws_num%22%3A%2254%22%2C%22dws_id%22%3A5%2C%22bag_weight%22%3A1500.0%2C%22net_weight%22%3A1000.0%2C%22selected%22%3Afalse%2C%22str_id%22%3A0%2C%22totalBags%22%3A10%7D%5D%2C%22str_total_weight%22%3A4000.0%2C%22str_date%22%3A%222013-03-08%22%2C%22str_number%22%3A%221003%22%2C%22str_id%22%3A4%2C%22str_total_bag%22%3A0%2C%22status%22%3A0%2C%22selected%22%3Afalse%7D%5D
You can try below code for parsing JSON
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea, Republic of"},
{"countryCode":"us","countryName":"United States"},
{"countryCode":"jp","countryName":"Japan"},
{"countryCode":"cn","countryName":"China"},
{"countryCode":"in","countryName":"India"}
]
}
public static ArrayList<Country> ParseJson(String jsonstring) {
ArrayList<Country> arrCountries = new ArrayList<Country>();
String status;
String message = "";
try {
JSONObject json = new JSONObject(jsonstring);
status = json.getString("result");
if (status.equalsIgnoreCase("success")) {
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
}
} catch (JSONException e) {
Log.e("JSON", "There was an error parsing the JSON", e);
}
return arrCountries;
}
I've been using the coding from an example from this link: The code is as shown below:
public class food extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = null;
InputStream is = null;
StringBuilder sb=null;
String result=null;
TextView fdi = (TextView)findViewById(R.id.textView1);
TextView fdn = (TextView)findViewById(R.id.textView2);
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/food.php");
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);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
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());
}
//paring data
int fd_id;
String fd_name;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("FOOD_ID");
fd_name=json_data.getString("FOOD_NAME");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
}
Now my question is how to pass this data to a list view, like for each iteration a list item must be added with the retrieved data.
Please help me
Thanks in advance
You are already getting strings in below code, Why don't you use that.
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("FOOD_ID");
fd_name=json_data.getString("FOOD_NAME");
}
//fdname and fd_id you are getting it right,
If your code is not working then add what problem you are facing.
according to your response/result from the server below code is working for me and giving output in string ,
try {
String response ="[{\"FOOD_ID\":\"1\",\"FOOD_NAME\":\"Rice\"},{\"FOOD_ID\":\"2\",\"FOOD_NAME\":\"Daal\"}] ";
JSONArray array;
array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(0);
String id_fd = obj.getString("FOOD_ID");
String name_fd = obj.getString("FOOD_NAME");
Log.d("JSONArray", id_fd+" " +name_fd);
}} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
please use it according to your need.
The root cause of the error a NullPointerException. This means that you are trying to use an object that has the value null. Usually this is because the object has not yet been initialised.
In your case the nullpointer is caused by something at line 29 of your Food class, probably one of these two lines
TextView fdi = (TextView)findViewById(R.id.textView1);
TextView fdn = (TextView)findViewById(R.id.textView2);
Are you sure that both the R.id.textView1 and R.id.textView1 exist? They should be specified somewhere in a layout xml file, something like this:
<TextView
android:id="#+id/textView1"
....