I am trying to parse the response I get from my OkHttp3Connection and it always almost always returns me String with value "true" which is names[0] in this example.
Now I try to convert this string to boolean and return true/false depending on the response. Now I guess since the OkHttp3Connection takes some time it doesnt let the query to finish and returns false which is the default value.
What I was trying to say is that this function always returns false no matter what String names[0] is.
public boolean checkIfSongPurhcased(String songName){
final boolean[] songCheckResult = new boolean[1];
OkHttp3Connection.doOkHttp3Connection("", Services_Url_class.GET_SONG_PURCHASED, OkHttp3Connection.Request_type.POST, request_data, new OkHttp3Connection.OkHttp3RequestCallback() {
#Override
public void onSuccess(String result, String userTag) throws JSONException {
JSONObject jsonResult = new JSONObject(result);
JSONArray data = jsonResult.getJSONArray("data");
if(data != null) {
String[] names = new String[data.length()];
for(int i = 0 ; i < data.length() ; i++) {
JSONArray arr = data.getJSONArray(i);
JSONObject dataObj = arr.getJSONObject(0);
Iterator<String> keys = dataObj.keys();
names[i] = dataObj.getString(keys.next());
}
//names[0] is "true"
songCheckResult[0] = Boolean.parseBoolean(names[0]);
}
}
#Override
public void onError(String error, String userTag) {
System.out.println("songy" + error);
}
}
);
//always returns false
return songCheckResult[0];
How can I make it so if names[0] is "true" it would give me true.
You should pass the listener/callback.
First create callback interface like below
public interface OnQueryResultCallback{
void onQueryResult(String songName, boolean status);
}
Then pass listener/callback to your method, here is the modified method.
public void checkIfSongPurhcased(final String songName, final OnQueryResultCallback listener){
OkHttp3Connection.doOkHttp3Connection("", Services_Url_class.GET_SONG_PURCHASED, OkHttp3Connection.Request_type.POST, request_data, new OkHttp3Connection.OkHttp3RequestCallback() {
#Override
public void onSuccess(String result, String userTag) throws JSONException {
JSONObject jsonResult = new JSONObject(result);
JSONArray data = jsonResult.getJSONArray("data");
if(data != null) {
String[] names = new String[data.length()];
for(int i = 0 ; i < data.length() ; i++) {
JSONArray arr = data.getJSONArray(i);
JSONObject dataObj = arr.getJSONObject(0);
Iterator<String> keys = dataObj.keys();
names[i] = dataObj.getString(keys.next());
}
//names[0] is "true"
boolean status = Boolean.parseBoolean(names[0]);
listener.onQueryResult(songName,status);
}
}
#Override
public void onError(String error, String userTag) {
System.out.println("songy" + error);
listener.onQueryResult(songName,false);
}
}
);
}
Then call checkIfSongPurhcased like below
checkIfSongPurhcased("songName", new OnQueryResultCallback(){
public void onQueryResult(String songName, boolean status){
if(status){
// do something on success
}else{
// do something on failure
}
}
});
Try to use getBoolean() rather than getString().
For Eg: names[i] = dataObj.getBoolean(keys.next());
Related
I try to get number of post from arraylist in the class into mainactivity.
But it is wrong .
Here is my code.
public static int countNotify;
public static List<Notification> bindNotifyData(JsonElement list)
{
List<Notification> results= new ArrayList<>();
JsonObject dataJsonObj = list.getAsJsonObject();
// get data api from Json array "updates"
JsonArray notifyJsonArray = dataJsonObj.get("updates").getAsJsonArray();
ArrayList<Notification> notifyList = new ArrayList<>();
countNotify=notifyJsonArray.size();
if(notifyJsonArray != null && notifyJsonArray.size() > 0) {
for(int i = 0; i < notifyJsonArray.size(); i++) {
JsonObject notifyJson = (JsonObject) notifyJsonArray.get(i);
Notification notification = new Notification();
notification.setContent(notifyJson.get("content").getAsString());
// Convert timestamp to Datetime
String timestamp= notifyJson.get("time").getAsString();
notification.setTime(ConvertTimestamp(timestamp));
results.add(notification);
// count numbers of the post in the list json array.
}
}
return results;
}
And in the MainActivity.class
final int count=BindFetchDataHelper.countNotify;
But the value of count always is 0
Try to create a instance of your class
BindFetchDataHelper bindFetchDataHelper = new BindFetchDataHelper ()
and then call final int count=bindFetchDataHelper.countNotify;
I had the same issue, it should work now.
EDIT
Try like this :
public class BindFetchDataHelper {
private static int sTest;
static {
public static int countNotify=0;
}
public static int getcountNotify() {
return countNotify;
}
public static void setcountNotify(int setcountNotify) {
this.countNotify = countNotify;
}
//your others functions
}
And now to access variable or to set it :
BindFetchDataHelper bindFetchDataHelper = new BindFetchDataHelper ()
bindFetchDataHelper.setcountNotify(YOURVALUE); //set
int whatyourwant = bindFetchDataHelper.getcountNotify(); //get
Im trying to download data from a server in the form of a JSON object, parse that object then use the data elsewhere in my app.
Ive created a class which downloads the data (confirmed with a Log.v statement)
The trouble is that i want to display the results in a RecyclerView and the List of objects that i generate after parsing the JSON response does not get generated until after the adapter method is called from my main class.
So my question is, given the code below, how can i ensure that the on response method only exits once the parseResponse method has finished. Currently i am returning the (Null) _releaseList from my requestAndPareseReleaseList method.
public class ParseReleaseJSON extends JSONObject {
String _url;
List<ReleaseInfo> _releaseList = Collections.emptyList();
ParseReleaseJSON(String url) {
super();
_url = url;
}
public List<ReleaseInfo> requestAndParseReleaseList(Context _context){
JsonObjectRequest jsObReq = new JsonObjectRequest(Request.Method.GET, _url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
releaseList = parseResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("err", "nosuccess");
}
});
MySingleton.getInstance(_context).addToRequestQueue(jsObReq);
return _releaseList;
}
private List parseResponse(JSONObject response) {
List<ReleaseInfo> list = new ArrayList<>();
if(response == null || response.length() == 0){
return list;
}
try {
if(response.has("results")){
JSONArray resultsArray = response.getJSONArray("results");
for(int i = 0, j = 6; i < j; i++){
ReleaseInfo release = new ReleaseInfo();
JSONObject tempObj = resultsArray.getJSONObject(i);
release.title = tempObj.getString("title");
release.date = tempObj.getString("date");
list.add(release);
}
return list;
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
}
I would like to combine two separate parsed jsonObjects into a single arraylist, then display the results as Strings?
I would like to store summaryJsonObject & segment in storylineData. When I step through the code using the debugger summaryJsonObject & segment both hold the raw json. The raw json data also shows in the logcat but storylineData remains null & unavailable throughout.
Here is the parsing code.
public class StorylineData {
private static String date;
private ArrayList<SummaryData> summary;
private ArrayList<SegmentData> segments;
private String caloriesIdle;
private String lastUpdate;
public String getDate() {
return date;
}
public ArrayList<SummaryData> getSummary() {
return summary;
}
public ArrayList<SegmentData> getSegments() {
return segments;
}
public String getCaloriesIdle() {
return caloriesIdle;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setDate(String date) {
this.date = date;
}
public void setSummary(ArrayList<SummaryData> summary) {
this.summary = summary;
}
public void setSegments(ArrayList<SegmentData> segments) {
this.segments = segments;
}
public void setCaloriesIdle(String caloriesIdle) {
this.caloriesIdle = caloriesIdle;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public static StorylineData parse(JSONObject jsonObject) {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optString("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = new ArrayList<SummaryData>();
storylineData.segments = new ArrayList<SegmentData>();
JSONArray summariesJsonArray= jsonObject.optJSONArray("summary");
if (summariesJsonArray != null) {
for (int i = 0; i < summariesJsonArray.length(); i++) {
JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i);
if (summaryJsonObject != null) {
storylineData.summary.add(SummaryData.parse(summaryJsonObject));
Log.d("storylineHandler", summaryJsonObject.toString());
}
}
}
JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments");
if (segmentsJsonArray != null) {
for (int i = 0; i < segmentsJsonArray.length(); i++) {
JSONObject segment = segmentsJsonArray.optJSONObject(i);
if (segment != null) {
storylineData.segments.add(SegmentData.parse(segment));
Log.d("storylineHandler", segment.toString());
}
}
}
return storylineData;
}
return null;
}
}
The MainActivity looks like this:
MainActivity
public class MainActivity extends FragmentActivity implements OnClickListener{
..other variables here..
List<StorylineData> storylineData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...other ui elements here...
mEditTextResponse = (TextView) findViewById(R.id.editResponse);
storylineData = new StorylineData();
MovesAPI.init(this, CLIENT_ID, CLIENT_SECRET, CLIENT_SCOPES.....
#Override
public void onClick(View v) {
toggleProgress(true);
switch (mSpinnerAPI.getSelectedItemPosition()) {
... other cases here...
break;
...other cases here...
case 4: // Get Summary Day
MovesAPI.getSummary_SingleDay(summaryHandler, "20150418", null);//Date changed to "20150117"
break;
Other cases here..
case 10: // Get Storyline Day
MovesAPI.getStoryline_SingleDay(storylineHandler, "20150418", null, false);//Date changed to "20150418"
break;
...Other cases here..
}
}
... Other MovesHandlers here...
private JSONObject summaryJsonObject;
private List<StorylineData> storylineList;
private JSONObject summariesJsonArray;
private MovesHandler<ArrayList<StorylineData>> storylineHandler = new MovesHandler<ArrayList<StorylineData>>() {
#Override
public void onSuccess(ArrayList<StorylineData> result) {
toggleProgress(false);
storylineList = (List<StorylineData>) StorylineData.parse(summaryJsonObject);
updateResponse( + storylineData.toString() + "\n" //displays true to layout view
result.add(StorylineData.parse(summariesJsonArray))+ "\n"
+Log.d("call result", result.toString()) + "\n" //displays 60 in layout view & com.protogeo.moves.demos.apps.storyline.StorylineData#52824f88, null]
+ Log.d("Log.d storylineHandler", storylineHandler.toString()) + "\n" ); //returns 78 in layout view & com.protogeo.moves.demos.apps.Mainactivity#234234 to log cat
onFailure code here..
}
};
public void toggleProgress(final boolean isProgrressing) {
togglePregress code here..
}
public void updateResponse(final String message) {
runOnUiThread(new Runnable() {
public List<StorylineData> storylineList;
#Override
public void run() {
mEditTextResponse.setText(message);
if (storylineData!= null) {
for (StorylineData storylineData : storylineList) {
mEditTextResponse.append(("storylineData" + storylineData.toString()));
}
}
}
});
}
}
HttpClass
public static void getDailyStorylineList(final MovesHandler<JSONArray> handler,
final String specificSummary,
final String from,
final String to,
final String pastDays,
final String updatedSince,
final boolean needTrackPoints) {
new Thread(new Runnable() {
#Override
public void run() {
try {
/* Refresh access token if only AuthData.MOVES_REFRESHBEFORE days are there to expire current token */
AuthData.refreshAccessTokenIfNeeded();
/* Exchange the authorization code we obtained after login to get access token */
HashMap<String, String> nameValuePairs = new HashMap<String, String>();
nameValuePairs.put("access_token", AuthData.getAuthData().getAccessToken());
// if (specificSummary != null && specificSummary.length() > 0) nameValuePairs.put("specificSummary", specificSummary);//att
if (from != null && from.length() > 0) nameValuePairs.put("from", from);
if (to != null && to.length() > 0) nameValuePairs.put("to", to);
if (pastDays != null && pastDays.length() > 0) nameValuePairs.put("pastDays", pastDays);
if (updatedSince != null && updatedSince.length() > 0) nameValuePairs.put("updatedSince", updatedSince);
if (needTrackPoints) nameValuePairs.put("trackPoints", "true");
URL url = new URL(MovesAPI.API_BASE + MovesAPI.API_PATH_STORYLINE + (specificSummary != null ? specificSummary : "") + "?" + Utilities.encodeUrl(nameValuePairs));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
if (urlConnection.getResponseCode() != 200) {
/* All other HTTP errors from Moves will fall here */
handler.onFailure(getErrorStatus(Utilities.readStream(urlConnection.getErrorStream()), urlConnection.getResponseCode()), "Server not responded with success ("+ urlConnection.getResponseCode() +")");
return;
}
String response = Utilities.readStream(urlConnection.getInputStream());
Object object = new JSONTokener(response).nextValue();
if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
ArrayList<StorylineData> storylineData = new ArrayList<StorylineData>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject storylineJsonObject = jsonArray.optJSONObject(i);
if (storylineJsonObject != null) {
storylineData.add(StorylineData.parse(storylineJsonObject));
}
}
}
handler.onSuccess(storylineData);
} else {
handler.onFailure(MovesStatus.INVALID_RESPONSE, "Expected a JSONArray from server, but failed");
}
} catch (Exception ex) {
ex.printStackTrace();
handler.onFailure(MovesStatus.UNEXPECTED_ERROR, "An unexpected error occured, please check logcat");
}
}
}).start();
}
MovesHandler
public interface MovesHandler<T> {//T stands for generic type
/**
* Implement this method to get success notifications along with the result
* #param result : Result of the operation completed with this handler
*/
public void onSuccess(ProfileData result);
/**
* Implement this method to get failure notifications along with the {#link MovesStatus} code and a brief message
* #param status : Status code of the failure
* #param message : A brief message about the reason behind failure
*/
public void onFailure(MovesStatus status, String message);
}
If you wanted to have one ArrayList to store both SummaryData and SegmentData, you could just created an ArrayList of Objects, ArrayList<Object>. This would be the more general solution.
The alternative would be having SummaryData and SegmentData inherit the same class or implement the same interface.
Using an extended class, you could have:
class Data {
}
class SegmentData extends Data {
}
class SummaryData extends Data {
}
You could then have an ArrayList that would be able to add both SegmentData and SummaryData objects.
If you wanted to show each item as a String you would need to loop through the list and call the toString() function of each item
ArrayList<Data> dataList;
for (Data d : dataList) {
Log.d("data", d.toString())
}
Just make sure to overwrite the toString() function in SegmentData and SummaryData
EDIT: Showing how to print JsonArray
If you wanted to just print for JsonArrays, you could:
public class StorylineData {
private static String date;
private JSONArray summary;
private JSONArray segments;
private String caloriesIdle;
private String lastUpdate;
public String getDate() {
return date;
}
public JSONArray getSummary() {
return summary;
}
public JSONArray getSegments() {
return segments;
}
public String getCaloriesIdle() {
return caloriesIdle;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setDate(String date) {
this.date = date;
}
public void setSummary(JSONArray summary) {
this.summary = summary;
}
public void setSegments(JSONArray segments) {
this.segments = segments;
}
public void setCaloriesIdle(String caloriesIdle) {
this.caloriesIdle = caloriesIdle;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public static StorylineData parse(JSONObject jsonObject) {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optString("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = jsonObject.optJSONArray("summary");
storylineData.segments = jsonObject.optJSONArray("segments");
return storylineData;
}
return null;
}
#Override
public String toString() {
JSONArray combined = new JSONArray(summary);
combined.put(segment);
return combined.toString();
}
}
In your MainActivity
private StorylineData storylineData;
private MovesHandler<JSONArray> storylineHandler = new MovesHandler<JSONArray>() {
#Override
public void onSuccess(JSONArray result) {
toggleProgress(false);
storylineData = StorylineData.parse(summaryJsonObject);
updateResponse(storylineData.toString()) //displays true to layout view
result.add(storylineData.getSummary());
Log.d("call result", result.toString());
Log.d("Log.d storylineHandler", storylineHandler.toString());
}
};
I am trying this to toggle the value of key1 in but I get the same value all the time. What am I doing wrong here?
boolean jsonText = true;
JSONObject jsonObj = new JSONObject();
public void setjsonObject(boolean val){
this.jsonText = val;
}
public Boolean getjsonObject(){
return this.jsonText;
}
#POST("/hello")
#PermitAll
public String hello(String text) {
try {
if (jsonObj.has("key1")) {
boolean val = !jsonObj.getBoolean("key1");
jsonObj.remove("key1");
jsonObj.put("key1", val);
} else {
jsonObj.put("key1", true);
}
} catch (JSONException e) {
e.printStackTrace();
}
return "some result";
}
Am I resetting the "key1" boolean value somewhere?
you are creating new JSON object every time:
JSONObject jsonObj = new JSONObject();
so it never has any value for "key1" and it is always set to true after your hello code.
I'm new in coding and I have a problem to understand something. I follow the example form Parse.com Doc and wrote this.
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
int object_value = Integer.parseInt(obiect);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
I understand this like:
I send query to server
get obiect with "lxFzCTeOcl" id
if there is no exception I create String object which takes string
form "value" column.
convert String to int
My question is: How can I use object_value for example to make a chart or put it into a table?
Here we will add the array list to your code and start to store an object inside the array every time we call the getData method in your class.
private ArrayList<Integer> dataArray;
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(obiect);
if(dataArray==null)
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
And here I'm just adding a simple example of how to create a simple pie chart using our array list (note that I used the lib AChartEngine http://www.achartengine.org/):
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };
private GraphicalView createPieChart(ArrayList<Integer> data){
GraphicalView chartView;
CategorySeries series = new CategorySeries("PIE");
for (int i = 0; i < VALUES.length; i++) {
series.add(i, data.get(i));
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(series.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
chartView = ChartFactory.getPieChartView(this, series, new DefaultRenderer());
chartView.repaint();
return chartView;
}
Now you can add this GraphicalView to your view.
The returned object is much like a map, with key/value pairs. In your example, the key is "value", which makes it a little confusing, but it would be like this if you wanted all fields:
for (Field field : myInstance.getClass().getDeclaredFields()) {
String name = field.getName();
value = field.get(myInstance).toString();
map.put(name, value);
}