Parse query using loop - java

I'm working on a survey application.the application has a dynamic number of questions and a specific survey code number.
I am trying to use a query to get all the questions matching the survey code number and add them to a list array.
Currently i am trying to use a while loop to do the job but i am getting an error.
here is the code snippet:
//This query is to count the number of Questions that match the surveyCode
ParseQuery<ParseObject> query = ParseQuery.getQuery("Field");
query.whereEqualTo("codeField", value);
query.countInBackground(new CountCallback() {
#Override
public void done(int count, ParseException e) {
if (e == null) {
//The query succeeded
countQeus = count;
//This loop is to get the question and put them into list Array
while(i<countQeus)
{
ParseQuery<ParseObject> query = ParseQuery.getQuery("Field");
query.whereEqualTo("codeField", value);
query.whereEqualTo("quesNumber", i + 1);//i = 0
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
question = list.toString();
list11.add(i, question.toString());
//Log.i("Question is: ",list11.get(i));
}
}
});
i++;
}
} else {
return;
}
}
});
If there is another way to do it without using a loop, i am open for suggestions.
Thanks,

Related

How to query list of objects grouped by their count (by frequency of mentions for last day)

The principe is like in StackOverFlow - every question has tags. And I need to display these tags by frequency of mentions for last day.
public List<TagDto> getAllTagsByCount() {
List<TagDto> tagDtos = new ArrayList<>();
try {
tagDtos = entityManager.createQuery("SELECT t.id, t.name FROM Tag t") // have no idea how to write such query
.unwrap(Query.class)
.setResultTransformer(new ResultTransformer() {
#Override
public Object transformTuple(Object[] objects, String[] strings) {
return TagDto.builder()
.id((Long) objects[0])
.name((String) objects[1])
.build();
}
#Override
public List transformList(List list) {
return list;
}
})
.getResultList();
} catch (Exception e) {
e.printStackTrace();
}
return tagDtos;
}
If u'll need some additional part of code, please let me know
What you are looking for is probably something like the following
List<Tuple> tuple = entityManager.createQuery("SELECT t.name, COUNT(*) FROM Tag t WHERE t.date BETWEEN :yesterday AND :tomorrow GROUP BY t.name")
.setParameter("yesterday", LocalDateTime.now().minus(1, ChronoUnit.DAYS).with(LocalTime.of(0, 0, 0))
.setParameter("tomorrow", LocalDateTime.now().plus(1, ChronoUnit.DAYS).with(LocalTime.of(0, 0, 0))
.getResultList();
You do not seem to have basic SQL knowledge though, so I would recommend you try to learn SQL first.

Array becoming empty after getting out of a for loop

I'm learning to program in Java for Android Studio. I'm working with a Parse.com query downloading information. I store the information inside an array of a costume object called MyData. When I'm storing the information I can log the content of the array and it has the correct info. But latter when I try to use the same array, if I use the .length function it says it's null. And if I try to retrieve any of the information, it's empty.
This I my object:
public class MyData {
Integer gluc;
Integer insulinaV;
Date fec;
Integer alimento;
String comentarios;
public MyData(Integer gluc, Integer insulinaV, Date fec, Integer alimento, String comentarios) {
this.gluc = gluc;
this.insulinaV = insulinaV;
this.fec = fec;
this.alimento = alimento;
this.comentarios = comentarios;
}
public Integer getGluc() {
return gluc;
}
public Integer getInsulinaV() {
return insulinaV;
}
public Date getFec() {
return fec;
}
public Integer getAlimento() {
return alimento;
}
public String getComentarios() {
return comentarios;
}
}
So, to retrieve the information I use array[I].getWhatever(), this is how I store the information:
public void downloadInformation() {
user = ParseUser.getCurrentUser();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Glucosa");
query.whereEqualTo("usuario", user);
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null && objects.size() > 0) {
Log.d("score!", "Objects Retrived");
Log.d("size", String.valueOf(objects.size()));
int i = 0;
indexsize = 0;
for (ParseObject object : objects) {
dataArray = new MyData[objects.size()];
dataArray[i] = new MyData(object.getInt("glucosa"), object.getInt("insulina"), object.getDate("fecha"), object.getInt("Alimentos"), object.getString("Comentarios"));
String alimentosexiste = dataArray[i].getAlimento().toString();
Log.i("Is Empty or Not=", alimentosexiste);
indexsize = indexsize+1;
i++;
}
} else {
Log.d("failed", "error");
}
}
});
}
In my logcat I'm getting "Score! Objects retrieved" and "Size: 22", also I get a list with all 22 elements of the "Is Empty or Not" Log. So far so good.
Then, In my attempt to move from this activity to another, I try to save the dataArray with:
public void saveInformation() {
int j = indexsize;
Log.i("size of index?", String.valueOf(indexsize));
for (int i=0; i<=j; i++) {
Log.i("index", String.valueOf(i));
alimentosVal = dataArray[i].getAlimento();
comentariosVal = dataArray[i].getComentarios();
glucVal = dataArray[i].getGluc();
insulinaVal = dataArray[i].getInsulinaV();
fecVal = dataArray[i].getFec();
}
SQLiteDatabase myGlucosebase = this.openOrCreateDatabase("GlucoseEvents", MODE_PRIVATE, null);
myGlucosebase.execSQL("CREATE TABLE IF NOT EXISTS glucoseevents (alimentos INT(2), comentarios VARCHAR, gluc INT(4), insulinv INT(4), fec DATETIME)");
myGlucosebase.execSQL("INSERT INTO glucoseevents (alimentos, comentarios, gluc, insulinv, fec) VALUES (alimentosVal, comentariosVal, glucVal, insulinaVal, fecVal) ");
}
And even do I printed before the content of the array with index [0] (so I'm sure the information got stored in the array), I get the following error:
Attempt to invoke virtual method 'java.lang.Integer com.parse.starter.MyData.getAlimento()' on a null object reference
I've seen that the problem is that I'm pointing to an empty element, but it was working before, how can I do this?
(Data array is declared at the beginning, below the class name as: MyData[] dataArray;)
Thanks!
dataArray = new MyData[objects.size()]; should be outside the for loop
Your class MyData does not have a "dataArray". At least not in the example code you give above.

How to print values which are parallel to the values In another column?

i used retrofit android With a database server ,
The problem is I have a database on localhost
https://i.stack.imgur.com/mdhOQ.png
I want to create a array So that only within it values
Which is next to the value of the number 8
So that the arrayString contains makarona and asd without Other values
but here it is print makarona and asd and null
i want a array with the corresponding names of number 8
See the code to see arrayString And tried to correct me the code
private void getAllMeal(final int id_) {
api = HttpApi.getInstance();
api.addHeader("Authorization", "MyT23");
// Get iteme from index number .....
getUsersCall = api.getService().getAllChatRooms4();
///----------------------------
getUsersCall.enqueue(new retrofit.Callback<List<Users>>(){
#Override
public void onResponse(retrofit.Response<List<Users>> response, Retrofit retrofit) {
user = response.body();
String [] arrayString = new String[user.size()];
int[] arrayInt = new int[user.size()];
for(int i=0; i<response.body().size(); i++) {
arrayInt[i] = user.get(i).fk_chef;
if(Arrays.asList(arrayInt).contains(id_)){
arrayString[i] = user.get(i).name;
}
Toast.makeText(chef_hello.this,"results names :"+arrayString[i],Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Throwable t) {
//dialog2.dismiss();
//Toast.makeText(chef_hello.this,"Error Throwable xx :",Toast.LENGTH_LONG).show();
// Toast.makeText(Regest_login.this, "XXX", Toast.LENGTH_LONG).show();
}
});
}
So you are trying to connect to Mysql using http ?

httprequesttask returns JSONArray, not the expected JSONObject

I try to get patient information, by sending an ID to the server. I expect the result to be a JSONObject, as only one patient corresponds with the ID. However, what i get is a JSONArray. I have tried to do getJSONObject(0), but it gives this error:
Index 0 out of range [0..0)
Why i is an Array and not an Object, and how do i deal with it?
This is my java code in the activity:
new HttpRequestTask(
"getPatientFull",
new String[]{"ID"},
new String[]{PatientID}, new HttpRequestTask.ResultReceiver() {
#Override
public void processResult(String apiFunctionName, JSONObject result) {
if (result != null) {
try {
if (result.has("error")) {
shorttoast("ERROR: " + result.getString("error") + "saving patient file");
} else {
if (result.has("patient_details")) {
patientName = result.getJSONArray("patient_details").getJSONObject(0).getString("NAME");
shorttoast(patientName);
}
}
} catch (JSONException ex) {
shorttoast("ERROR" + ex.getLocalizedMessage());
}
} else
shorttoast("Retreiving failed");
}
}).execute();
The PatientID is defined earlier in the code (it's an existing patient id).
and this is the php API function that was defined by my teacher:
app.post("/getPatientFull", function (req, res) {
pool.getConnection(function (err, connection) {
connection.query('SELECT * FROM PatientDossier WHERE PATIENT_ID=?',
[req.query.ID],
function (error, results, fields) {
if (error) {
res.status(403).json({"error": error.code});
} else {
res.status(200).json({patient_details:results});
}
});
connection.release();
});
});
The PHP function does not return a single object, it returns an array.
So, you should expect a JSONArray on the Android side.
As to why getJSONObject(0) is giving you an out-of-bounds error, I'm not sure.
Try using the debugger to look at the JSONArray, and see what's in it. It's possible that you searched for a patient id that's not in the database, and the PHP code returned an empty array. Your code should be checking that anyway.
It also looks like maybe "result" is a JSONObject containing the array, under the key "patient_details", in which case, you need to get the value of "patient_details" and index into that array. If you show us the JSON response, it would be easier to tell.

How to Append a column in parse.com database

Hey guys I was looking through parse.com examples and documentation but haven't been able to figure out how to change the value of something that's stored in a column in a parse class(specifically a string that's a number e.g., Column name:ExampleColumn - string - 5) . For example I want to do something like this when a button is clicked
#Override
public void onClick(View arg0) {
ParseQuery<ParseObject> query = new ParseQuery<ParseObject> ("ExampleClass");
ExampleColumn = ExampleColumn + 1; /* obviously this won't work but it shows exactly what i want to do with the column, so that this would make ExampleColumn = 6 */
}
With Parse, you don't work directly with columns. You work with objects. So, if you want to change the value of "a column", you need to
fetch the object (row) you want to change
edit the property on that object
save the object again.
If the column data type is string you have to convert to integer before increment it.
ParseQuery query = new ParseQuery ("ExampleClass");
query.whereEqualTo("objectId",your_object_id);
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("score", "The getFirst request failed.");
} else {
int val=Integer.parseInt(object.getString("exampleColumn"));
val++;
object.put("exampleColumn",val);
object.saveInBackground();
}
}
});

Categories