i am currently trying to parse a simple JSON information but can't figure out the JSON object and array part... I'm trying to extract from this JSON(below) the app_time and postcode + address. Can anyone give me a solution about my "extractFeatureFromJson()", sorry about the formatting it's my first post here.
{
"data": [
{
"id": 24256,
"app_time": 1904280242,
"addresses": [
{
"id": 1,
"postcode": "9000",
"address": "Street:Street, City: City, Country: Country"
}
],
"comments": [
{
"id": 1,
"comment": "Comment",
"created_at": 234234234
}
]
}
]
}
public static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String _URL = "https://.......com/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScheduleAsyncTask task = new ScheduleAsyncTask();
task.execute();
}
private void updateUi(Event job) {
TextView titleTextView = (TextView) findViewById(R.id.time);
titleTextView.setText(getDateString(job.time));
TextView dateTextView = (TextView) findViewById(R.id.address);
dateTextView.setText(job.address);
}
private String getDateString(long timeInMilliseconds) {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
return formatter.format(timeInMilliseconds);
}
private class ScheduleAsyncTask extends AsyncTask<URL, Void, Event> {
#Override
protected Event doInBackground(URL... urls) {
// Create URL object
URL url = createUrl(_URL);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
Event jobs = extractFeatureFromJson(jsonResponse);
return jobs;
}
#Override
protected void onPostExecute(Event job) {
if (job == null) {
return;
}
updateUi(job);
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("X-Application", ".....");
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private Event extractFeatureFromJson(String scheduleJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(scheduleJSON);
JSONArray featureArray = baseJsonResponse.getJSONArray("comments");
// If there are results in the features array
// Extract out the first feature
JSONObject firstFeature = featureArray.getJSONObject(0);
JSONObject properties = firstFeature.getJSONObject("comment");
// Extract out the time address values
String address = properties.getString("address");
long time = properties.getLong("app_time");
// Create a new {#link Event} object
return new Event(address, time);
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the JSON results", e);
}
return null;
}
}
}
As per your json structure, data is json array and so is addresses and comments, so you have to work your way down to those json arrays and finally json objects.
One way to understand json structure (objects and array is to format it and view it. Use online json formatters like https://jsonformatter.org/ or install plugins in notepad++ to format json.
NOTE: I am not giving you full solution as it is for your own benefit so here is what you should do and add debugger points and system.out.println (Log.d in android) for understanding json object and array you traverse and learn yourself.
JSONObject obj = new JSONObject(str);
JSONObject appTime = obj.getJSONArray("data").getJSONObject(0).getJSONObject(“app_time”);
JSONObject postal_code = obj.getJSONArray("data").getJSONObject(0).getJSONArray(“addresses”).getJSONObject(0).getJSONObject(“postcode”);
You have to add appropriate null checks at each step to avoid NPE.
You can also use JSONObject’s methods to retrieve specific data type (getString, getLong, etc.)
https://developer.android.com/reference/org/json/JSONObject.html
if (scheduleJSON!= null) {
try {
JSONObject jsonObj = new JSONObject(scheduleJSON);
// Getting JSON Array node
JSONArray data= jsonObj.getJSONArray("data");
// looping through All data
for (int i = 0; i < data.length(); i++) {
JSONObject id = data.getJSONObject(id);
JSONObject app_time=data.getJSONObject(app_time);
String id = c.getString("id");
// Getting JSON Array node
JSONArray addresses=new JSONArray(data.getJSONObject(i).getString("addresses"));
JSONArray comments= new JSONArray(data.getJSONObject(i).getString("comments"));
}
}catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
Related
This question already has answers here:
Asynctask: pass two or more values from doInBackground to onPostExecute
(5 answers)
Closed 5 years ago.
I have problem with parsing my JSON Object to multiple textview.
I have a TextView1, TextView2 and TextView3.
I would like to download data from: "max", "min" and "average" and synch data with .settext in TextView1, TextView2 and TextView3
My JSON looks: {"max":15.6,"min":14.05,"average":14.55}
My code below:
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
Log.d("Login attempt", connection.toString());
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
String maxPrice = parentObject.getString("max");
return maxPrice;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
onPostExecute:
protected void onPostExecute (String result){
super.onPostExecute(result);
maxPrice.setText(result);
I can't add more String and synch in other TextView. That's work only for one TextView. I can't synch multiple TextView. Can you help me?
1) Return your finalJson from doInBackground
2) getString & setText in onPostExecute
JSONObject parentObject = new JSONObject(result);
String maxPrice = parentObject.getString("max");
String minPrice = parentObject.getString("min");
String avg = parentObject.getString("average");
tvMaxPrice.setText(maxPrice);
tvMinPrice.setText(minPrice);
tvAvg.setText(avg);
you have two option.
1st option
return your whole json string like
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
return finalJson;
then process your json on your onPostExecute like
protected void onPostExecute (String result){
super.onPostExecute(result);
JSONObject parentObject = new JSONObject(result);
String maxPrice = parentObject.getString("max");
maxPrice.setText(result);
String minPrice = parentObject.getString("min");
minPrice.setText(result);
String avgPrice = parentObject.getString("avg");
avgPrice.setText(result);
}
or
2nd option is
You have to try like this
String result = "";
String maxPrice = parentObject.getString("max");
String avgPrice = parentObject.getString("avg");
String minPrice = parentObject.getString("min");
result = maxPrice+","+avgPrice+","+minPrice;
return result;
then split it on your onPostExecute
protected void onPostExecute (String result){
super.onPostExecute(result);
String[] separated = result.split(",");
maxPrice.setText(separated[0]);
minPrice.setText(separated[2]);
avgPrice.setText(separated[1]);
}
I've been following a tutorial which provided an example website to use in the json request, however when i put in my own website to scrape data from, nothing happens.
Here is my code;
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
public class JSONTask extends AsyncTask<String,String, String>{
#Override
protected String doInBackground(String ... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("movie");
String mostGames = finalObject.getString("year");
return ChampionName + mostGames;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
tvData.setText(result);
}
}
}
Screen of when it works on left and screen when it doesnt work on right.
So yeah, this is what i know i have to change
new JSONTask().execute("http://api.champion.gg/champion/Ekko");
and
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("WHAT DO I PUT HERE");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("WHAT DO I PUT HERE");
String mostGames = finalObject.getString("WHAT DO I PUT HERE");
From this URL - http://api.champion.gg/champion/Ekko/ , i want to get lets say the first two fields "key":"Ekko","role":"Top", so if anyone could give me a hand, that would be great!
According to the JSON returned form your link http://api.champion.gg/champion/Ekko/
You have to start to parse your string response as JSONArray
JSONArray parentObject = new JSONArray(finalJson);
then start to loop through this array to get JSONObject
JSONObject jsonObject = parentObject.getJSONObject(yourLoopIndex);
Inside each JSONObject you can get any value. by using the key in the original JSON string.
I have parsed the JSON Data in a listview and now I want to make it available offline.
Is there a way to save the JSON data at the phone so that you can see the data if your phone is offline?
Does someone knows an example?
EDIT works now:
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void, Void, JSONArray> {
InputStream is = null;
String result = "";
JSONArray jArray = null;
ProgressDialog pd;
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
pd.dismiss();
ArrayList<String> list= new ArrayList<String>();
try {
for(int i=0;i<result.length();i++) {
JSONObject jb = result.getJSONObject(i) ;
String name = jb.getString("name")+" "+jb.getString("Art");
list.add(name);
}
} catch(Exception e) {
e.printStackTrace();
}
setListAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, list));
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "State",
"Loading...", true);
}
#Override
protected JSONArray doInBackground(Void... arg0) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("***");
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();
writeToFile(result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
jArray = new JSONArray(readFromFile());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
}
You have two ways. Either you create a database and save all of the data there and retrieve it back when you want to. Or if the data you have is not that much and you don't want to deal with databases, then you write the json string to a text file in the memory card and read it later when you are offline.
And for the second case, every time you go online, you can retrieve the same json from your web service and over write it to the old one. This way you can be sure that you have the latest json saved to the device.
this class will help you cache strings in files with a key to retrieve later on. the string can be a json string and key can be the url you requested and also an identifier for the url if you are using post method.
public class CacheHelper {
static int cacheLifeHour = 7 * 24;
public static String getCacheDirectory(Context context){
return context.getCacheDir().getPath();
}
public static void save(Context context, String key, String value) {
try {
key = URLEncoder.encode(key, "UTF-8");
File cache = new File(getCacheDirectory(context) + "/" + key + ".srl");
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(cache));
out.writeUTF(value);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void save(Context context, String key, String value, String identifier) {
save(context, key + identifier, value);
}
public static String retrieve(Context context, String key, String identifier) {
return retrieve(context, key + identifier);
}
public static String retrieve(Context context, String key) {
try {
key = URLEncoder.encode(key, "UTF-8");
File cache = new File(getCacheDirectory(context) + "/" + key + ".srl");
if (cache.exists()) {
Date lastModDate = new Date(cache.lastModified());
Date now = new Date();
long diffInMillisec = now.getTime() - lastModDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);
diffInSec /= 60;
diffInSec /= 60;
long hours = diffInSec % 24;
if (hours > cacheLifeHour) {
cache.delete();
return "";
}
ObjectInputStream in = new ObjectInputStream(new FileInputStream(cache));
String value = in.readUTF();
in.close();
return value;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
how to use it :
String string = "cache me!";
String key = "cache1";
CacheHelper.save(context, key, string);
String getCache = CacheHelper.retrieve(context, key); // will return 'cache me!'
Once you download the data you could persist the data on the mobile, using a database or a system of your preference.
You can check the different options here: data-storage
using SharedPreferences should be prepared to sqlite (unless of course you have a database structure). For caching and storing data pulled from the internet, I recommend robospice: https://github.com/octo-online/robospice. It's a very well done library, easy to use, and should be used any time you download data from the internet or have a long-running task.
You can use those two methods two store you JSON file as a string in your SharedPreferences and retrieve it back:
public String getStringProperty(String key) {
sharedPreferences = context.getSharedPreferences("preferences", Activity.MODE_PRIVATE);
String res = null;
if (sharedPreferences != null) {
res = sharedPreferences.getString(key, null);
}
return res;
}
public void setStringProperty(String key, String value) {
sharedPreferences = context.getSharedPreferences("preferences", Activity.MODE_PRIVATE);
if (sharedPreferences != null) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
CupsLog.i(TAG, "Set " + key + " property = " + value);
}
}
Just use setStringProperty("json", "yourJsonString") to save and getStringProperty("json") to retrieve.
How to Cache Json data to be available offline?
You can use gson to parse JSON data more easily.
In your build.gradle file add this dependency.
compile 'com.google.code.gson:gson:2.8.0'
Then create a POJO class to parse JSON data.
Example POJO class:
public class AppGeneralSettings {
#SerializedName("key1")
String data;
public String getData() {
return data;
}
}
To parse a json string from internet use this snippet
AppGeneralSettings data=new Gson().fromJson(jsonString, AppGeneralSettings.class);
Then add a helper class to store and retrieve JSON data to and from preferences.
Example: Helper class to store data
public class AppPreference {
private static final String FILE_NAME = BuildConfig.APPLICATION_ID + ".apppreference";
private static final String APP_GENERAL_SETTINGS = "app_general_settings";
private final SharedPreferences preferences;
public AppPreference(Context context) {
preferences = context.getSharedPreferences(FILE_NAME, MODE_PRIVATE);
}
public SharedPreferences.Editor setGeneralSettings(AppGeneralSettings appGeneralSettings) {
return preferences.edit().putString(APP_GENERAL_SETTINGS, new Gson().toJson(appGeneralSettings));
}
public AppGeneralSettings getGeneralSettings() {
return new Gson().fromJson(preferences.getString(APP_GENERAL_SETTINGS, "{}"), AppGeneralSettings.class);
}
}
To save data
new AppPreference().setGeneralSettings(appGeneralSettings).commit();
To retrieve data
AppGeneralSettings appGeneralSettings = new AppPreference().getGeneralSettings();
You can cache your Retrofit responses, so when you make the same request second time, Retrofit will take it from it's cache:
https://medium.com/#coreflodev/understand-offline-first-and-offline-last-in-android-71191e92b426, https://futurestud.io/tutorials/retrofit-2-activate-response-caching-etag-last-modified. After that you'l need to parse that json again
I want to fetch json data from this link: link
& here is my code for that:
private static String url = "https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,%20commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url=%27https://www.facebook.com/BillionHands%27";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_SHARE = "share_count";
private static final String TAG_LIKE = "like_count";
private TextView LikeTv;
public String like;
JSONArray data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_us);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing each json item in variable
String share = c.getString(TAG_SHARE);
like = c.getString(TAG_LIKE);
Log.i("Like Count",like);
} catch (JSONException e) {
e.printStackTrace();
}
LikeTv = (TextView) findViewById(R.id.tvLike);
LikeTv.setText(like);
Now I am getting "JSONException: no value for data" Please help... whats wrong in my code..
Well....
I got your problem solution...
The method you wrote getJSONFromUrl()..
I am sure it contains HttpPost object..
change that to HttpGet and it will start working...
EDIT
Here is the code I tried with
public class MainActivity extends Activity {
private static String url = "https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,%20commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url=%27https://www.facebook.com/BillionHands%27";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_SHARE = "share_count";
private static final String TAG_LIKE = "like_count";
private TextView LikeTv;
public String like;
JSONArray data = null;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONfromURL(url);
try {
// Getting Array of Contacts
Log.d("JSON ","DATA "+json);
data = json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing each json item in variable
String share = c.getString(TAG_SHARE);
like = c.getString(TAG_LIKE);
Log.i("Like Count",like);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
class JSONParser
{
public JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
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 get data string ",
"Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag create object ",
"Error parsing data " + e.toString());
}
return jArray;
}
}
The "data" element in your JSON isn't an array, it is a JSONobject. So instead of:
JSONArray data = json.getJSONArray(TAG_DATA);
Try this:
JSONObject data = json.getJSONObject(TAG_DATA);
From the JSONObject, you can get items like TAG_SHARE and TAG_LIKE.
Good luck!
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