How to Append a column in parse.com database - java

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

Related

In the table i need to store the values of the Id which is selected but not able to do that Any Leads

Scenario:
I select Two Ids and gets added in the Table which can been seen in the below screen shot.
Over Here i need to Store the value in a Method and then call that method in other Place.
The Problem is iam not able to get the Values .
Code:
public boolean checkselectedDemandId()
{
String cDemand = "";
cDemand = "//table//tr//td[contains(#class,'mat-column-demandId')]";
List<WebElement> rows = driver.findElements(By.xpath(cDemand));`
for(WebElement row:rows)`
{if(cDemand.length()>0)
{
selectedDemandId = cDemand;
return true;
}`else
{
return false;
}
public String getselectedCreatedDemandId()
{
return selectedDemandId;
}
HTML of the Table:
4384SELTESTTECHMTESSINGAPOREHONGKONG2030-04-092040-06-152055-12-30delete 4383SELTESTTECHMTESSINGAPOREHONGKONG2030-04-092040-06-152055-12-30delete
If you are sure about number of rows, use the following code
List<WebElement> rows = driver.findElements(By.xpath("//table//tr//td[contains(#class,'mat-column-demandId')]"));
String rowOne = rows.get(0).getText();
String rowTwo = rows.get(1).getText();

Showing an Integer tableview in javaFx as a string

I am trying to show a tableview where when the value in the table is a integer like 1 for example I want to display a String. So far I tried to get the cellValue like this:
public void changeView() {
if(intervall.getCellFactory().call(intervall).equals(1)) {
intervall.getCellFactory().call(intervall).setText("Täglich");
}
}
And I am calling the method in my initialize after setting the cellvalue.
public void initializeTable() {
try {
// Ablesen
Statement pStatement = connection.createStatement();
flightList = FXCollections.observableArrayList();
ResultSet myRs = pStatement
.executeQuery("select * from fluglinie where fluggesellschaft =\"" + fluggesellschaft + "\"");
while (myRs.next()) {
flightList.add(new flightRouteAddModel(myRs.getString("startFlughafen"),
myRs.getString("zielFlughafen"), myRs.getString("startDatum"), myRs.getString("flugzeug"),
myRs.getInt("intervall"), myRs.getInt("anzahlEconomy"), myRs.getInt("anzahlBusiness"),
myRs.getFloat("preisEconomy"), myRs.getFloat("preisBusines"), myRs.getFloat("distanz")));
}
} catch (Exception e) {
System.out.println(e);
}
startAirport.setCellValueFactory(new PropertyValueFactory<>("startAirport"));
targetAirport.setCellValueFactory(new PropertyValueFactory<>("targetAirport"));
flightDate.setCellValueFactory(new PropertyValueFactory<>("flightDate"));
airplane.setCellValueFactory(new PropertyValueFactory<>("airPlane"));
intervall.setCellValueFactory(new PropertyValueFactory<>("intervall"));
seatCountEco.setCellValueFactory(new PropertyValueFactory<>("countEconomy"));
seatCountBus.setCellValueFactory(new PropertyValueFactory<>("countBusiness"));
priceEco.setCellValueFactory(new PropertyValueFactory<>("priceEconomy"));
priceBus.setCellValueFactory(new PropertyValueFactory<>("priceBusiness"));
distance.setCellValueFactory(new PropertyValueFactory<>("distance"));
table.setItems(flightList);
changeView();
}
But it is not working can someone maybe take a look at this? I know changing the db would be maybe a better solution but I kinda wanted to try this workaround
The cellFactory returns TableCells. Calling this yourself does not result in a cell that is part of the TableView (or becomes part of it). Any TableCell with a properly impelemented equals method never yields true, if 1 (or any other Integer) is passed.
Assuming you always want to display Täglich instead of 1, the way to go about this is using a custom cellFactory for this column:
intervall.setCellFactory(col -> new TableCell<flightRouteAddModel, Integer>() {
#Override
protected void updateItem(Integer item, boolean empty) {
String text = "";
if (item != null) {
switch(item) {
case 1:
text = "Täglich";
break;
case 7:
text = "Wöchentlich";
break;
default:
text = String.format("Alle %d Tage", item);
break;
}
}
setText(text);
}
});
BTW: Please learn about the java naming conventions. This makes the code easier to read for other people and it should make this more readable even for yourself, since all java APIs (that I know of) use these conventions: Type names start with an uppercase letter.

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.

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.

Parse query using loop

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,

Categories