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"
....
Related
I am developing android app where I am getting web-service data as:
"[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"}]"
Now I want to parse this data in json I used replaceAll() function to replace backslashes from the string like this:
String jsonFormattedString = line.replaceAll("\\\\", "");
But I think this method isnot good to work with because it removes all the backslashes from the string which creates problems like I recieved json node like:
"[{\"ID\":9617,\"Text\":\"1 1\/4\\\" PVC\/GI CLAMPS\"}]"
where the string value for Text contains double quotes within string which creates problem for me. So my question is what is the best way to parse this json data in java.
My full json data returned by webservice is as:
"[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"},{\"ID\":53,\"Text\":\"Kanix City\"},{\"ID\":54,\"Text\":\"KANIX DREAM CITY\"},{\"ID\":59,\"Text\":\"KANIX DREAM CITY -- PHASE II\"},{\"ID\":62,\"Text\":\"KANIX DREAM CITY PHASE I\"},{\"ID\":55,\"Text\":\"Kishor_TEST\"},{\"ID\":63,\"Text\":\"Next Generation Housing\"},{\"ID\":65,\"Text\":\"Nothing Job\"},{\"ID\":56,\"Text\":\"PAVAN_TEST\"},{\"ID\":46,\"Text\":\"PRODUCTION UNITS\"},{\"ID\":1,\"Text\":\"PROJECT-01(TYPE 1)\"},{\"ID\":3,\"Text\":\"PROJECT-02(TYPE 1)\"},{\"ID\":5,\"Text\":\"PROJECT-03(TYPE 1)\"},{\"ID\":6,\"Text\":\"PROJECT-04(TYPE 1)\"},{\"ID\":7,\"Text\":\"PROJECT-05(TYPE 1)\"},{\"ID\":8,\"Text\":\"PROJECT-06(TYPE 1)\"},{\"ID\":2,\"Text\":\"PROJECT-07(TYPE 2)\"},{\"ID\":4,\"Text\":\"PROJECT-08(TYPE 2)\"},{\"ID\":9,\"Text\":\"PROJECT-09(TYPE 3)\"},{\"ID\":10,\"Text\":\"PROJECT-10(TYPE 3)\"},{\"ID\":11,\"Text\":\"PROJECT-11(TYPE 4)\"},{\"ID\":57,\"Text\":\"Reviera Classic\"},{\"ID\":43,\"Text\":\"ROAD PROJECT\"},{\"ID\":41,\"Text\":\"SAMPLE PROJECT 1\"},{\"ID\":42,\"Text\":\"SAMPLE PROJECT 2\"},{\"ID\":52,\"Text\":\"Shailesh Test project#1000\"},{\"ID\":61,\"Text\":\"VISHAL PARADISE\"},{\"ID\":60,\"Text\":\"WTC\"}]"
my full code is like this:
#Override
protected List<CItem> doInBackground(String... params) {
try {
String line="";
String ur = "http://"+ServerDetails.hostServer+"/appservices.svc/Projects?Keyword=" ;
lstItm=new ArrayList<CItem>() ;
// Replace it with your own WCF service path
URL json = new URL(ur);
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
line = reader.readLine();
Log.d("LINE",line);
JSONArray array=new JSONArray(line);
Itm=new CItem( "-1", "Select Project" );
lstItm.add(Itm);
for(int i=0; i < array.length(); i++) {
JSONObject tmpJson=array.getJSONObject(i);
Itm=new CItem(tmpJson.getString("ID"),tmpJson.getString("Text"));
lstItm.add(Itm);
}
return lstItm ;
}
catch(Exception e)
{
Log.d("ERRROR--->",e.getMessage());
}
return lstItm ;
}
#mubu9082 ..you dont need to remove these backslashes...
as this json string is shown with backslashes in log or by debugger..
just parse it as usual
public void jsonParser()
{
ArrayList<> list=new ArrayList<>(); //declare this as global
String responseString="[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"}]";
JSONArray array=new JSONArray(responseString);
String id[]=new String[array.length()];
String text[]=new String[array.length()];
for(int i=0;i<array.length();i++)
{
JSONObject tmpJson=array.getJSONObject(i);
id[i]=tmpJson.getString("ID");
text[i]=tmpJson.getString("TEXT");
CItem Itm=new CItem(tmpJson.getString("ID"),tmpJson.getString("Text")); lstItm.add(Itm);
list.add(Itm);
}
}
do this to get response from server
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL ...use
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
HttpEntity entity = httpResponse.getEntity();
String response= EntityUtils.toString(entity);
//pass this response to JSONArray object
//save response and then flush the entity.
entity.consumeContent();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
pass this response to JSONArray object
public InsuranceDO getInsuranceData1(Context context) {
String urlStr = "http://192.168.2.11:8080/Service/category/sample";
InsuranceDO insuranceDO = new InsuranceDO();
HttpURLConnection urlConnection;
List<InsuranceDO> insList = new ArrayList<InsuranceDO>();
try {
String reqVal = "T=421D84EAC8DEB4878CE48C8A0CB870791EB96FE51C7800A8806032A8CE69A4966D87FFA2E139EE6586C1924F9BD070154CB7E8F92985AC6674B0AD37D9F3FC1ED7B2E4C2D01E5525DCE5E6FCDA26AF890633011894AA2B72604CC8B046E4F9C37DE9A61EECD7000325D3EC673E8609AAD753C52B9BC002C014BC18A35AA8AB3636C237088A08EEED72A7C5F2EDE60155E9111A6F74F082C0E4B45D484C00CA5AD5B3560B8A10D47616E48077EBDE490E&UserCode=172278&DBSource=bali";
URL url = new URL(urlStr);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(reqVal.getBytes());
outputStream.flush();
int code = urlConnection.getResponseCode();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder result = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
/**
* To parse json to list data
*/
JSONArray jsonArray = new JSONArray(result.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
insuranceDO.setAgeing(jsonObject.getString("xxx"));
insuranceDO.setInsuredName(jsonObject.getString("yyyy"));
insuranceDO.setProposalNumber(jsonObject.getString("zzzz"));
insuranceDO.setReason(jsonObject.getString("aaaa"));
insList.add(insuranceDO);
}
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Toast.makeText(context, insList.toString(), Toast.LENGTH_LONG).show();
return insuranceDO;
}
Please help me , I am trying to connect my android app to mysql database in localhost through connection in php and json array, but i cant figure out what is the problem , i cant view the data from database.
Here is my files.
Connection.php
<?php
$db_con = mysqli_connect('localhost', 'root', '', 'android') or die ("connection error");;
$query = "SELECT * FROM product";
$results = mysqli_query($db_con, $query) or die ("query error");;
while($row = mysqli_fetch_assoc($results)){
$output[]=$row;
}
echo json_encode($output);
?>
and this the android java "MainActivity.java" :
public class MainActivity extends ActionBarActivity {
TextView viewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
viewItem = (TextView) findViewById(R.id.itemView);
// Button btnViewItems = (Button) findViewById(R.id.btnViewItems);
getData();
}
public void getData() {
String results = "";
InputStream isr = null;
// Http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2:8080/android/Connection.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
} catch (Exception e) {
Log.e("log-tag", "Error in http connection" + e.toString());
viewItem.setText("Cannot connect to database");
}
// Converting response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
results = sb.toString();
} catch (Exception e) {
Log.e("log-tag", "Error Converting string" + e.toString());
viewItem.setText("Cannot convert string");
}
// prase jason data
try {
String s = "";
JSONArray jArray = new JSONArray(results);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jOb = jArray.getJSONObject(i);
s = s + jOb.getString("id") + " || " + jOb.getString("name")
+ " || " + jOb.getString("cost") + "\n\n";
}
viewItem.setText(s);
} catch (Exception e) {
Log.e("log-tag", "prasing json data" + e.toString());
viewItem.setText("cannot prase json data");
}
}
}
and the out keep saying : "cannot prase json data".
here is the log error :
E/log-tag(1904): Error in http connectionandroid.os.NetworkOnMainThreadException
E/log-tag(1904): Error Converting stringjava.lang.NullPointerException: lock == null
E/log-tag(1904): prasing json dataorg.json.JSONException: End of input at character 0 of
thanks
You need to run HTTP requests on different thread instead on main thread. Android API does not allow running HTTP requests on main thread. Try using Runnable() to run http request asynchronously on separate thread.
Guys can you help me a little bit, Im getting this error:
"JSONException: Value <!DOCTYPE of type java.lang cannot be converted to JSONObject"
When I'm parsing the data here is my code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Here is the code where I'm instantiating the Parser:
private void fillSpinnerCabTypes() {
List<String> cabTypesSpinner = new ArrayList<String>();
JSONParser jsonParser = new JSONParser();
JSONObject cabTypesObject = jsonParser.getJSONFromUrl(urlTypeCabs);
try{
TypesArray = cabTypesObject.getJSONArray(TAG_TYPES);
for(int i = 0; i < TypesArray.length(); i++){
JSONObject c = TypesArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
cabTypesSpinner.add(name);
}
}catch(Exception e ){
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cabTypesSpinner);
final Spinner spnCabTypes = (Spinner)findViewById(R.id.spnTypeOfCab);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spnCabTypes.setAdapter(adapter);
}
I'm really stuck with this. I'm populating the spinner from a database in a backend on Django in the server.
This is my JSON data
{"Types": [{"name": "Normal"}, {"name": "Discapacitados"}, {"name": "Buseta"}]}
This issue comes from the server.
The URL you're requesting, send you back data but not in the JSON format.
The Exception you get is telling you that the String the server send you back starts with:
<!DOCTYPE
This can be:
A simple webpage (instead of raw JSON). It correspond to the first XML tag of a web page (source)
An error page generated by the server, and printed in HTML
To debug this further, simply print the content of your json variable in the logcat:
Log.d("Debug", json.toString());
jObj = new JSONObject(json);
This problem came in my code also.and solution was different.It occured due to spelling mistake of webservice.
Solution 1:
for example real the url is
http://example.com/directory/file.php
and i had used
http://example.com/directory/file1.php
Solution 2:
use loopj library .it exactly gives you the explained error.
AsyncHttpClient client = new AsyncHttpClient();
client.post(str , localRequestParams, new AsyncHttpResponseHandler() {
#Override
public void onFinish() {
super.onFinish();
Log.i("onFinish","onFinish");
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.i("onSuccess","onSuccess");
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.i("onFailure","onFailure");
}
});
I use this code below, it works perfectly in Android 2.3.3. However, in 4.0+ it can't connect to database somehow. I saw some posts about you need to get it in a asynch class. I also tried that, but I can't seems it to work. I probably use it wrong, but it is hard for me to understand.
public class connector extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getServerData(null);
}
//i use my real ip here
public String getServerData(String returnString) {
System.out.println("going to connector class");
InputStream is = null;
final String KEY_121 = "http://10.0.0.128/connector.php";
String result = "";
//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 = null;
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);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", \nActara: "+json_data.getString("Actara")
);
//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;
}
}
Logcat error (on 4.0+):
11-12 12:02:35.658: E/log_tag(14083): Error in http connection android.os.NetworkOnMainThreadException
11-12 12:02:35.658: E/log_tag(14083): Error converting result java.lang.NullPointerException
11-12 12:02:35.663: E/log_tag(14083): Error parsing data org.json.JSONException: End of input at character 0 of
Only the first error line is important, because it can't connect to a database, it gives a nullPointer (2nd and 3rd error).
This is what I tried in Asynch:
public class connector extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new BackgroundAsyncTask().execute();
}
public class BackgroundAsyncTask extends
AsyncTask<Void, Integer, Void> {
InputStream is = null;
final String KEY_121 = "http://10.0.0.128/connector.php";
String result = "";
String returnString = "";
protected void onPostExecute(Void result) {
}
#Override
protected void onPreExecute() {
System.out.println("onPreExecute");
}
protected Void doInBackground(String... params) {
try{
System.out.println("background in progress");
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 = null;
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);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", \nActara: "+json_data.getString("Actara")
);
//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 null;
}
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
}
Someone that can help me? I don't know for sure what the real cause is why it isn't working for 4.0+.
If you need more info, just say it, and I will post it.
Code can be a bit messy, I didn't really "clean" it up yet properly.
Since Android 3.0 you are not allowed to do network stuff on the main thread. Why? because network problems will lead to a slow ui. So you have to do all the http stuff in a new thread. You are on the right path but you made a mistake in your AsyncTask. Delete the empty doInBackground method in you async task and write #Override over your method.
android.os.NetworkOnMainThreadException
this eror comes With HoneyComb(3.0 or Later). you can not perform a networking operation on its main thread as documentation says. to getting ride of this you must use handler or asynctask. AFAIK There is no another way to do it.
you can See this for More Details WHY ICS Crashes your App
Try Using Below Code Snippet
new Thread(){
public void run(){
//do your Code Here
}
}.start();
Ok right...
After searching for few hours, making this question, then 10 minutes later, you find a solution...
Option 1:
I added this line:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
But I reccomend NOT to use option 1, this is a bad solution for real. Use option 2!
//===========================================================================
Option 2:
Used this tutorial to make a proper ASyncTask: http://www.elvenware.com/charlie/development/android/SimpleHttpGetThread.html
//===========================================================================
Used ASyncTask as final (option 2).
why you are passing null in function of web connection and web service .?
getServerData(null);
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