ParseObject as a data to the table/chart - java

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

Related

Get number of post in list array from another class. But It doesn't work?

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

Split jsonarray data into multiple list using array value

I want to split an ArrayList according to the existing data, Like as
category etc.
I try nested for loop and add them into list.but It's not working.
String url = "http://27.147.169.230/UpSkillService/UpSkillsService.svc/" + "GetCNCCourseDefByorg/" + 1 +"/" +1;
Ion.with(getApplicationContext())
.load("GET",url)
.setBodyParameter("","")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.d("Result",result);
try {
JSONObject obj =new JSONObject(result);
JSONArray jsonArray = obj.getJSONArray("GetCNCCourseDefByorgResult");
//Arrays.sort(new JSONArray[]{jsonArray});
if(obj.isNull("GetCNCCourseDefByorgResult"))
{
Toast.makeText(getApplicationContext(),"No Course Found",Toast.LENGTH_SHORT).show();
}
else if (!obj.equals(null)) {
String cata="";
Log.d("Resul3", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
final CourseCatagory catagoryModel = new CourseCatagory();
JSONObject course = jsonArray.getJSONObject(i);
CourseList courselist = new CourseList();
if(cata!=course.getString("CategoryName"))
{
Log.d("Catagory",cata);
catagoryModel.setCategoryName(course.getString("CategoryName"));
arrayListcatagory.add(catagoryModel);
for (int j=0;j<jsonArray.length();j++)
{
JSONObject cat1 = jsonArray.getJSONObject(j);
cata=cat1.getString("CategoryName");
Log.d("cat",cata);
if(cat1.getString("CategoryName")==course.getString("CategoryName"))
{
courselist.setCourseName(cat1.getString("CourseName"));
courselist.setCourseCode(cat1.getString("CourseCode"));
courselist.setWishFlag(cat1.getInt("WishFlag"));
Log.d("Course",cat1.getString("CourseName"));
arrayListcourse.add(courselist);
}
else {
}
}
}
catagoryModel.setCourseList(arrayListcourse);
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
}
`
I want as catagory, under catagory course shown which match catagory name.
Accounting>Introduction Accounting,Advance accounting
Finance>Introduction Finance
You can Use HashMap<String,ArrayList<CategoryDetails>> to resolve your Problem.
First Create CategoryDetails POJO class
class CategoryDetails {
private courseName;
private courseCode;
private wishFlag;
//make setter and getter methods for above fields.
}
Then use category Name as key in HashMap to differentiate as mentioned in first line of my answer.
Map<String,ArrayList<CategoryDetails>> listCategory = new HashMap<String,ArrayList<CategoryDetails>>;

Change variable inside async call

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

In which container can I collect Strings to show any of them

I have a LinkedHashMap which fills with data from db with loop "for" string by string and when I try to show the first or the last String, the method can show me only the last String in log. But in application listViewContent is filled fully. So I don't understand why I can't see any string that I want. I need to collect all strings I get from db and compare them in future.
How can I collect all strings and what method should I call to show the string I want to see?Unfortunately I can only retrieve one (and the last instead of the first) string.
Here is my example code :
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FirstMethod();
}
public FirstMethod() {
SecondMethod newMethod = .. // getting data from the second method
}
public SecondMethod() {
public void onResponseReceived(String result) {
try {
...
if (posts != null) {
for (WallPostItem post : posts) { // this loop
//create new map for a post
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put(ATTRIBUTE_NAME_TEXT, post.text);
PictureItem postPicture = new PictureItem();
map.put(ATTRIBUTE_NAME_IMAGE, postPicture);
map.put(ATTRIBUTE_NAME_DATE, post.date);
sAdapter.notifyDataSetChanged();
};
};
...
List<Map.Entry<String, Object>> list = new ArrayList<Map.Entry<String, Object>>(GlobalMap.entrySet());
Map.Entry<String, Object> firstInsertedEntry = list.get(0);
Log.w("FirstEntryOfMap",""+firstInsertedEntry); // this log shows me the last string instead of the first
}
if (isRefresh) {
isRefresh = false;
lvSimple.setSelectionAfterHeaderView();
}
} catch (Exception e) {
Log.d("exceptions", "problem in get wall post task after post execute: " + e.toString());
}
}
You aren't putting your values into a List, you are putting them into a Map (that preserves key order). I would suggest you create a POJO class,
class MyAttribute {
final String postName;
final PictureItem postPicture;
final Date postDate;
public MyAttribute(String postName, PictureItem postPicture, Date postDate) {
this.postName = postName;
this.postPicture = postPicture;
this.postDate = postDate;
}
public String getPostName() {
return postName;
}
public Date getPostDate() {
return postDate;
}
public PictureItem getPostPicture() {
return postPicture;
}
}
Then you could create a
List<MyAttribute> myAttributes = new ArrayList<>();

retrieve real-time data from JBloomberg API

I want to retrieve the time and the real-time last Price as double instead of having an output like
DataChangeEvent{ESA Index,ASK_SIZE: 204==>192}
from the code below
DataChangeListener lst = new DataChangeListener() {
#Override
public void dataChanged(DataChangeEvent e) {
System.out.println(e);
}
};
SubscriptionBuilder builder = new SubscriptionBuilder()
.addSecurity("ESA Index")
.addField(RealtimeField.LAST_PRICE)
.addField(RealtimeField.ASK)
.addField(RealtimeField.ASK_SIZE)
.addListener(lst);
session.subscribe(builder);
Thread.sleep(3000);
Just saw your question so it's probably a little late - but here it is anyway. DataChangeEvent contains the ticker, the field, the new and old price:
DataChangeListener lst = new DataChangeListener() {
#Override public void dataChanged(DataChangeEvent e) {
String ticker = e.getSource();
String field = e.getDataName();
double oldValue = e.getOldValue().asDouble();
double newValue = e.getNewValue().asDouble();
}
};

Categories