Hi I'm using Codename One and Parse Server to save database in my Mobile App, but I wanna put each result of the query inside a button, because I need to click on each element of the List. ParseQuery.getQuery("List") "List" is the ID referenced in the database and "Title" return String.
//Method:
public Container retrieveList(String content) {
Container list = new Container(BoxLayout.y());
ParseObject po = null;
try {
po = ParseObject.fetch(content /*class name*/, "nsC2NdmCuQ" /*objectId*/);
} catch (ParseException e) {
Dialog.show("Err", "Oops! Database is not available at the moment" + e.getCode(), "OK", null);
}
Label title = new Label("Book's Title: " + po.getString("Title"));
list.addComponent(title);
return list;
}
//MENU:
public void listMenu() {
final Form listMenu = new Form("Welcome to the List Menu");
listMenu.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
ParseQuery<ParseObject> query = ParseQuery.getQuery("List");
query.whereExists("Title");
List<ParseObject> results = null;
Container dumpList = null;
listMenu.add(dumpList).removeAll();
ParseServerDAO ps = new ParseServerDAO();
try {
results = query.find();
int index = 0;
for(;index < results.size();) {
dumpList = ps.retrieveList(//How to get each element from results?);
//Add each element of results to a button.
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Oops! Try later, server is not working right now.", "", "OK", null);
}
listMenu.add(dumpList);
}
If you want a list of buttons you should probably do something like this:
public MultiButton retrieveListItem(String content, ActionListener l) {
ParseObject po = null;
try {
po = ParseObject.fetch(content /*class name*/, "nsC2NdmCuQ" /*objectId*/);
} catch (ParseException e) {
Dialog.show("Err", "Oops! Database is not available at the moment" + e.getCode(), "OK", null);
}
MultiButton title = new MultiButton("Book's Title: " + po.getString("Title"));
title.addActionListener(l);
title.putClientProperty("ParseObject", po);
return title;
}
Notice you can use Button, MultiButton, SpanButton etc. for various use cases.
Notice that in the action listener you would want to invoke getActualComponent() on the event object and not getComponent().
E.g. event handling code:
public void actionPerformed(ActionEvent ev) {
MultiButton mb = ev.getActualComponent();
ParseObject po = (ParseObject)mb.getClientProperty("ParseObject");
}
Related
I'm confused on how can I connect my android mobile to Laravel I've tried different ways but returns me an Java.ioFileNotFoundException:http://122.168...
I found out that the problem is the CSRF-TOKEN when I've tried disabling the CSRF-TOKEN in my laravel it works , what I tried I fetch first my CSRF-TOKEN and submit it with CSRF-TOKEN when buttons click but it didn't work either.
I used Plugin for Advanced-HttpURLConnection GITHUB LINK link
This is what I tried
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
FetchData fetchData = new FetchData("http://122.168.1.3/app/refreshtokens");
if (fetchData.startFetch()) {
if (fetchData.onComplete()) {
String fetchResult = fetchData.getResult();
try {
//getting the token from fetch data
JSONObject jsonObject = new JSONObject(fetchResult);
String csrfToken = jsonObject.getString("csrfToken");
String[] field = new String[3];
field[0] = "id_no";
field[1] = "password";
field[2] = "X-CSRF-TOKEN";
//Creating array for data
String[] data = new String[3];
data[0] = id_no;
data[1] = password;
data[2] = csrfToken;
PutData putData = new PutData("http://122.168.1.3/app/auth", "POST", field, data);
if (putData.startPut()) {
if (putData.onComplete()) {
String result = putData.getResult();
//just want to getData when success
Toast.makeText(getApplicationContext(), "Testt " + result, Toast.LENGTH_SHORT).show();
}
}
//End Write and Read data with URL
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error catch " + e, Toast.LENGTH_SHORT).show();
}
}
}}
});
I have created a simple address book program which allows the user to add and update a record. There is also a jtable on the address book which shows the user all the records in the address Book. I have recently added logic where the user updates an existing record and the table refreshes. But if I then click on the updated record or any record in the Jtable to display into the Jtext field I get a I get an Array Out of Bounds error.
Code for getting records from the Database
public void addTable() throws Exception {
tableModel = new DefaultTableModel();
xtable = new JTable(tableModel);
tableModel.addColumn("ID");
tableModel.addColumn("First Name");
tableModel.addColumn("Surname");
tableModel.addColumn("Address Line 1");
tableModel.addColumn("Address Line 2");
tableModel.addColumn("Address Line 3");
tableModel.addColumn("City");
tableModel.addColumn("Post Code");
tableModel.addColumn("Email Address");
tableModel.addColumn("Phone Number");
db.connectDb();
String outQuery = "SELECT * FROM Contacts";
db.myFs = db.st.executeQuery(outQuery);
while (db.myFs.next()) {
String id = db.myFs.getString("ContactID");
String fName = db.myFs.getString("FirstName");
String sName = db.myFs.getString("Surname");
String adOne = db.myFs.getString("AddressLineOne");
String adTwo = db.myFs.getString("AddressLineTwo");
String adThree = db.myFs.getString("AddressLineThree");
String cCity = db.myFs.getString("City");
String pCode = db.myFs.getString("PostCode");
String eAddress = db.myFs.getString("EmailAddress");
String eName = db.myFs.getString("PhoneNumber");
tableModel.insertRow(0, new Object[] { id, fName,sName, adOne, adTwo, adThree, cCity,
pCode, eAddress, eName });
}
db.st.close();
db.con.close();
pane = new JScrollPane(xtable);
pane.setBounds(700, 100, 400, 100);
panel.add(pane);
}
Code to display record into JTextField
public void fetchRec() {
xtable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
String col0 = (String) xtable.getValueAt(xtable.getSelectedRow(),0);
String col1 = (String) xtable.getValueAt(xtable.getSelectedRow(),1);
String col2 = (String) xtable.getValueAt(xtable.getSelectedRow(),2);
String col3 = (String) xtable.getValueAt(xtable.getSelectedRow(),3);
String col4 = (String) xtable.getValueAt(xtable.getSelectedRow(),4);
String col5 = (String) xtable.getValueAt(xtable.getSelectedRow(),5);
String col6 = (String) xtable.getValueAt(xtable.getSelectedRow(),6);
String col7 = (String) xtable.getValueAt(xtable.getSelectedRow(),7);
String col8 = (String) xtable.getValueAt(xtable.getSelectedRow(),8);
String col9 = (String) xtable.getValueAt(xtable.getSelectedRow(),9);
idLabelField.setText(col0);
firstNameLabelField.setText(col1);
surNameLabelField.setText(col2);
addressLineOneField.setText(col3);
addressLineTwoField.setText(col4);
addressLineThreeField.setText(col5);
cityField.setText(col6);
postCodeField.setText(col7);
emailAddressField.setText(col8);
phoneNumberField.setText(col9);
}
});
}
Code to Update a record in the Db
public void updateButton() {
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
number = Integer.parseInt(idLabelField.getText());
setID(number);
setFirstName(firstNameLabelField.getText());
setSurName(surNameLabelField.getText());
setAddressLineOne(addressLineOneField.getText());
setAddressLineTwo(addressLineTwoField.getText());
setAddressLineThree(addressLineThreeField.getText());
setCity(cityField.getText());
setPostCode(postCode.getText());
setEmailAddress(emailAddressField.getText());
setPhoneNumber(phoneNumberField.getText());
try {
db.updateDB(getID(),getFirstName(), getSurName(), getAddressLineOne(), getAddressLineTwo(),
getAddressLineThree(), getCity(), getPostCode(), getEmailAddress(), getPhoneNumber());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
addTable();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
The error i am getting is Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 8
First of all don't use a null layout and setBounds(). Swing was designed to be used for layout managers.
I have recently added logic where the user updates an existing record and the table refreshes.
I would guess the problem is that you keep creating new components (ie. JTable and JScrollPane) and then add the components to the screen.
The problem is you never remove the previous components so you have multiple instances of each component being painted on the frame and your variables don't reference the visible components.
So the solution is create your JTable and JScrollPane and add the components to the frame when you first create the frame. Then, when you "referesh" the data you just create a new DefaultTableModel and use the setModel(...) method to update the table.
Or you can use setRowCount(0) of your current DefaultTableModel to remove all the current data and then use use the addRow(...) method to repopulate the model with the dat in the ResultSet.
How do you add multiple records (rows) to TableView Through TextField..?
So far i could managed to add a record to TableView through TextField, but when i change TextField values and hit ADD button, it removes previously added record and shows the new Record in TableView.
// Code For Inserting Records to TableView Through TextField //
private void Add_details(){
try {
String Customer = txtCustomer.getText().trim();
String Mobile = txtMobile.getText().trim();
String Item = txtItem.getText().trim();
int unit_price = Integer.parseInt(txtUnitPrice.getText().trim());
int qty = Integer.parseInt(txtQty.getText().trim());
TableItems t = new TableItems();
ObservableList <TableItems> curnt_row = FXCollections.observableArrayList();
t.setCustomer(Customer);
t.setMobile(Mobile);
t.setItem(Item);
t.setUnit_price(String.valueOf(unit_price));
t.setQty(String.valueOf(qty));
t.setTotal(String.valueOf(total));
curnt_row.add(t);
tblItems.setItems(curnt_row);
col_customer.setCellValueFactory(new PropertyValueFactory<>("customer"));
col_mobile.setCellValueFactory(new PropertyValueFactory<>("mobile"));
col_item.setCellValueFactory(new PropertyValueFactory<>("item"));
col_qty.setCellValueFactory(new PropertyValueFactory<>("qty"));
col_unitprice.setCellValueFactory(new PropertyValueFactory<>("unit_price"));
col_total.setCellValueFactory(new PropertyValueFactory<>("total"));
}catch (NumberFormatException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
// CORDING FOR GET SELECTED ITEM FROM TABLEVIEW //
// I WANT TO GET ALL ITEMS,
// NOT ONLY SELECTED ITEM SO THAT I COULD PERFORM BATCH INSERTION
private void Get_table_values(){
/* LAMDA EXPRESSION */
tblItems.getSelectionModel().selectedItemProperty().addListener
((obs, oldSelection, newSelection) -> {
if (newSelection != null) {
TableView.TableViewSelectionModel selectionModel = tblItems.getSelectionModel();
ObservableList selectedCells = selectionModel.getSelectedCells();
TablePosition tablePosition = (TablePosition) selectedCells.get(0);
Object val = tablePosition.getTableColumn().getCellData(newSelection);
String S_value = val.toString();
}
});
}
You're replacing the entire items list, instead of simply adding a single item. The new list starts empty and the only item you add is the one created in the Add_details method. Add the items the existing list instead:
private final ObservableList <TableItems> curnt_row = FXCollections.observableArrayList();
...
// TableView initialisation
tblItems.setItems(curnt_row);
col_customer.setCellValueFactory(new PropertyValueFactory<>("customer"));
col_mobile.setCellValueFactory(new PropertyValueFactory<>("mobile"));
col_item.setCellValueFactory(new PropertyValueFactory<>("item"));
col_qty.setCellValueFactory(new PropertyValueFactory<>("qty"));
col_unitprice.setCellValueFactory(new PropertyValueFactory<>("unit_price"));
col_total.setCellValueFactory(new PropertyValueFactory<>("total"));
...
private void Add_details(){
try {
String Customer = txtCustomer.getText().trim();
String Mobile = txtMobile.getText().trim();
String Item = txtItem.getText().trim();
int unit_price = Integer.parseInt(txtUnitPrice.getText().trim());
int qty = Integer.parseInt(txtQty.getText().trim());
TableItems t = new TableItems();
t.setCustomer(Customer);
t.setMobile(Mobile);
t.setItem(Item);
t.setUnit_price(String.valueOf(unit_price));
t.setQty(String.valueOf(qty));
t.setTotal(String.valueOf(total));
curnt_row.add(t);
} catch (Exception e) {
e.printStackTrace();
}
}
For getting all items, simply use getItems or use the list you know is assigned to the items property, e.g. in the above example the curnt_row field.
okay guys, here is the thing, I have one application consuming ODATA service, in SMP server, I'm getting this Data like this:
public class callService extends AsyncTask<Void, Void, ArrayList<String>>
{
public ArrayList<String> doInBackground(Void... params)
{
ODataConsumer c = ODataJerseyConsumer.create("http://MyUrlService:8080");
List<OEntity> listEntities = c.getEntities("MYENTITYTOCONSUME").execute().toList();
System.out.println("Size" + listEntities.size());
if (listEntities.size() > 0)
{
for (OEntity entity : listEntities)
{
zmob_kunnr.add((String) entity.getProperty("Name1").getValue()
+ " - "
+ entity.getProperty("Kunnr").getValue().toString());
}
}
return zmob_kunnr;
}
protected void onPostExecute(ArrayList<String> result)
{
super.onPostExecute(result);
adapter = new ArrayAdapter<String>(ConsumoKnuur.this, android.R.layout.simple_list_item_1, result);
list.setAdapter(adapter);
}
}
Okay I got this solution from web and could implement as list, and I need to store this entity which one is a List of customers and get the two attributes from this entity and save in my database so:
Entity Customer:Custormer_ID, Customer_Name
Here is my code to call my sqlite:
public void sqlite()
{
sql_obj.open();
sql_obj.deleteAll();
for(int i=0; i < zmob_kunnr.size(); i++)
{
sql_obj.insert(zmob_kunnr.get(i).toString(), zmob_kunnr.get(i).toString() );
}
sql_obj.close();
}
And my SQLite:
private static final String TABLE_CLIENTE = "CREATE TABLE "
+ TB_CLIENTE
+ "(ID_CLIENTE INTEGER PRIMARY KEY AUTOINCREMENT, " //Id for controller my logics
+ " Kunnr TEXT , " //customer ID
+ " Name1 TEXT );"; //customer_name
public long insert(String name1, String Kunnr)
{
ContentValues initialValues = new ContentValues();
initialValues.put("Name1", Name1); //Customer_Name
initialValues.put("Kunnr", Kunnr); //Customer_ID
return database.insert(TB_CLIENTE, null, initialValues);
}
And off course my other methods, that is not important, so whats happening when I run my "for" in the sql call method, I get the size() of the list and the rows of the list and store the entire row in the one column of the database each time, so I got two different tables with the same values,
how can I change solve this problem instead of consume in list I need to consume in array ? or I need to create a method that get the list values and after a ,(coma) , create two differents objects to store these data ??
I took a long look in the internet and didn't find nothing, probably it's because i don't know yet, how so, I don't know for what I'm looking for it, I'm using the odata4j API and here is the link of the documentation, http://odata4j.org/v/0.7/javadoc/
I'm new on programming, so I'm really in trouble with this, any suggestions any helps will be truly, appreciate,
Thanks a lot and have a nice day !!!
You can add each entity to the `ArrayList' array by doing the following:
for (OEntity entity : listEntities) {
zmob_kunnr.add(entity);
}
This will allow you to access the data contained in the entity via getProperty() when inserted into the database.
The following statement is also not needed, as the for each loop runs through every element in the list, thus for (OEntity entity : listEntities) will not execute if the list is empty.
if (listEntities.size() > 0) {
...
}
If you have multiple ODataConsumers, you have two choices, depending on your requirements (if I understand you question correctly):
You can sequentially get each ODataConsumer, get the listEntities, and add it to the zmob_kunnr list, and after the list items are added to the database, clear the zmob_kunnr list, and call doInBackground with a new URL. This is what your current solution allows.
It appears to need to know which property is associated with a URL when reading the values into the DB. You can use a POJO as a holder for the entity and its list of properties. You can now add and remove properties. Note that properties will be removed in the same order they where inserted.
public class OEntityHolder {
private final OEntity entity;
private Queue<String> properties;
public OEntityHolder(OEntity entity) {
this.entity = entity;
this.properties = new LinkedBlockingQueue<>();
}
public OEntity getEntity() {
return this.entity;
}
public void addProperty(String property) {
this.properties.add(property);
}
public void removeProperty() {
this.properties.poll();
}
}
This will require a change to the list holding the entities:
ArrayList<OEntityHolder> zmob_entity_holders = new ArrayList<>();
If you would like to add all the entities from the different URLs at the same time, you will need to have access to all the URLs when doInBackground is called. Something like this:
public ArrayList<OEntityHolder> doInBackground(Void... params) {
String [][] urls = {{"http:MyUrl/ZMOB_FECODSet", "Name1", "Fecod"},
{"http:MyUrl/ZMOB_OTEILSet", "Name2", "Oteil"},
{"http:MyUrl/ZMOB_KUNNRSet", "Name3", "Kunnr"},
{"http:MyUrl/ZMOB_BAULTSet", "Name4", "Bault"}};
for (String [] urlProp:urls) {
//Here you get the list of entities from the url
List<OEntity> listEntities = ODataJerseyConsumer.create(urlProp[0]).getEntities("MYENTITYTOCONSUME").execute().toList();
for (OEntity entity:listEntities) {
OEntityHolder holder = new OEntityHolder(entity);
for (int i = 1; i < urlProp.length; i++)
holder.addProperty(urlProp[i]);
zmob_entity_holders.add(holder);
}
}
//At this point, all of the entities associated with the list of URLS will be added to the list
return zmob_entity_holders;
}
You now have ALL of the entities associated with the list of URLs in zmob_kunnr. Before you can and can insert then into the DB like so:
for (OEntityHolder holder : zmob_entity_holders) {
sql_obj.insert(holder.getEntity().getProperty(holder.removeProperty()).toString(), holder.getEntity().getProperty(holder.removeProperty()).toString());
}
If each entity has a associated name, you can store the names in a map, where the key is the URL and the value the name.
HashMap<String, String> urlEntityNames = new HashMap<>();
urlEntityNames.put("http://MyUrlService:8080", "MYENTITYTOCONSUME");
...//Add more URLs and entity names
You can then, when running through the list of entities, do a look-up in the map to find the correct name:
List<OEntity> listEntities = ODataJerseyConsumer.create(url).getEntities(urlEntityNames.get(url)).execute().toList();
I hope this helps, if I misunderstood you just correct me in the comments.
EDIT: Added list of URLs, holder and DB insert.
I guess i found a solution, but my log cat, is giving an exception to me any updtades about my 2nd doInBackgroundBault (Material),
public class callServiceCliente extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressC = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Clientes", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer ccli = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesKunnr = ccli.getEntities("ZMOB_KUNNRSet").execute().toList();
System.out.println("Size" + listEntitiesKunnr.size());
for (OEntity entityKunnr : listEntitiesKunnr) {
zmob_kunnr.add(entityKunnr);
}
return zmob_kunnr;
}
protected void onPostExecute(ArrayList<OEntity> kunnr) {
super.onPostExecute(kunnr);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int k = 0; k < zmob_kunnr.size(); k++) {
sql_obj.insertCliente(zmob_kunnr.get(k).getProperty("Kunnr").getValue().toString().toUpperCase(), zmob_kunnr.get(k).getProperty("Name1").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
clienteAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, kunnr);
listCliente.setAdapter(clienteAdapter);
} catch (Exception eq) {
}
progressC.dismiss();
new callServiceMaterial().execute();
}
}
public class callServiceMaterial extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressM = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Materiais", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer cmat = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesBault = cmat.getEntities("ZMOB_BAULTSet").filter("IErsda eq '20141101'").execute().toList();
System.out.println("Size" + listEntitiesBault.size());
for (OEntity entityBault : listEntitiesBault) {
zmob_bault.add(entityBault);
}
return zmob_bault;
}
protected void onPostExecute(ArrayList<OEntity> bault) {
super.onPostExecute(bault);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int b = 0; b < zmob_bault.size(); b++) {
sql_obj.insertMaterial(zmob_bault.get(b).getProperty("Matnr").getValue().toString().toUpperCase(), zmob_bault.get(b).getProperty("Maktxt").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
materialAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, bault);
listMaterial.setAdapter(clienteAdapter);
} catch (Exception eq) {
}
progressM.dismiss();
new callServiceProblema().execute();
}
}
public class callServiceProblema extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressProb = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Problemas", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer cprob = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesFecod = cprob.getEntities("ZMOB_FECODSet").execute().toList();
System.out.println("Size" + listEntitiesFecod.size());
for (OEntity entityFecod : listEntitiesFecod) {
zmob_fecod.add(entityFecod);
}
return zmob_fecod;
}
protected void onPostExecute(ArrayList<OEntity> fecod) {
super.onPostExecute(fecod);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int f = 0; f < zmob_fecod.size(); f++) {
sql_obj.insertProblema(zmob_fecod.get(f).getProperty("Fecod").getValue().toString().toUpperCase(), zmob_fecod.get(f).getProperty("Kurztext").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
problemaAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, fecod);
listProblema.setAdapter(problemaAdapter);
} catch (Exception eq) {
}
progressProb.dismiss();
new callServiceProcedencia().execute();
}
}
public class callServiceProcedencia extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressProc = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando base de dados", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer c = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesProcedencia = c.getEntities("ZMOB_OTEILSet").execute().toList();
System.out.println("Size" + listEntitiesProcedencia.size());
for (OEntity entityProcedencia : listEntitiesProcedencia) {
zmob_oteil.add(entityProcedencia);
}
return zmob_oteil;
}
protected void onPostExecute(ArrayList<OEntity> oteil) {
super.onPostExecute(oteil);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int o = 0; o < zmob_oteil.size(); o++) {
sql_obj.insertCliente(zmob_oteil.get(o).getProperty("Fecod").getValue().toString().toUpperCase(), zmob_oteil.get(o).getProperty("Kurztext").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
procedenciaAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, oteil);
// listCliente.setAdapter(clienteAdapter);
} catch (Exception eq) {
}
progressProc.show(Atualizar_Dados.this, "Finalizado", "Base de dados atualizada", true, true).dismiss();
Toast.makeText(Atualizar_Dados.this, "Base de dados atualizada com sucesso", Toast.LENGTH_LONG).show();
}
}
Okay, so here is the solution that i find, and i couldn't insert your solution because, when i put inser.add(entity), they didn't show me the properties but if you have a better way to do what i did, i will really appreciate,
and by the way i need to query this consume by range date in the filter(). like i did here...
List listEntitiesBault = cmat.getEntities("ZMOB_BAULTSet").filter("IErsda eq '20141101'").execute().toList(); but isn't working, so i don't have any ideas why, i saw couple close solution on the internet and saw fields like .top(1) and .first(); that i didn't understand...
thanks a lot !!!
I am trying to add a feature to my android app that allows users to "checkin" with other people tagged to the checkin.
I have the checkins method working no problem and can tag some one by adding the user ID as a parameter (see code below)
public void postLocationTagged(String msg, String tags, String placeID, Double lat, Double lon) {
Log.d("Tests", "Testing graph API location post");
String access_token = sharedPrefs.getString("access_token", "x");
try {
if (isSession()) {
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", access_token);
parameters.putString("place", placeID);
parameters.putString("Message",msg);
JSONObject coordinates = new JSONObject();
coordinates.put("latitude", lat);
coordinates.put("longitude", lon);
parameters.putString("coordinates",coordinates.toString());
parameters.putString("tags", tags);
response = mFacebook.request("me/checkins", parameters, "POST");
Toast display = Toast.makeText(this, "Checkin has been posted to Facebook.", Toast.LENGTH_SHORT);
display.show();
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
This works fine (I've posted it in case it is of help to anyone else!), the problem i am having is i am trying to create a list of the users friends so they can select the friends they want to tag. I have the method getFriends (see below) which i am then going to use to generate an AlertDialog that the user can select from which in turn will give me the id to use in the above "postLocationTagged" method.
public void getFriends(CharSequence[] charFriendsNames,CharSequence[] charFriendsID, ProgressBar progbar) {
pb = progbar;
try {
if (isSession()) {
String access_token = sharedPrefs.getString("access_token", "x");
friends = charFriendsNames;
friendsID = charFriendsID;
Log.d(TAG, "Getting Friends!");
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", access_token);
response = mFacebook.request("me/friends", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
When i look at the response in the log it reads:
"got responce: {"error":{"type":"OAuthException", "message":"(#200) Permissions error"}}"
I have looked through the graphAPI documentation and searched for similar questions but to no avail! I'm not sure if i need to request extra permissions for the app or if this is something your just not allowed to do! Any help/suggestions would be greatly appreciated.
You might need the following permissions:
user_checkins
friends_checkins
read_friendlists
manage_friendlists
publish_checkins
Check the related ones from the API docs. Before that, make sure that which line causes this permission error and try to fix it.
The solution is to implement a RequestListener when making the request to the Facebook graph API. I have the new getFriends() method (see below) which uses the AsyncGacebookRunner to request the data.
public void getFriends(CharSequence[] charFriendsNames,String[] sFriendsID, ProgressBar progbar) {
try{
//Pass arrays to store data
friends = charFriendsNames;
friendsID = sFriendsID;
pb = progbar;
Log.d(TAG, "Getting Friends!");
//Create Request with Friends Request Listener
mAsyncRunner.request("me/friends", new FriendsRequestListener());
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.getMessage());
}
}
The AsyncFacebookRunner makes the the request using the custom FriendsRequestListener (see below) which implements the RequestListener class;
private class FriendsRequestListener implements RequestListener {
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state) {
Log.d(TAG, "FriendListRequestONComplete");
//Create a copy of the response so i can be read in the run() method.
friendData = response;
//Create method to run on UI thread
FBConnectActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
//Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
//Loop through our JSONArray
int friendCount = 0;
String fId, fNm;
JSONObject friend;
for (int i = 0;i<friendArray.length();i++){
//Get a JSONObject from the JSONArray
friend = friendArray.getJSONObject(i);
//Extract the strings from the JSONObject
fId = friend.getString("id");
fNm = friend.getString("name");
//Set the values to our arrays
friendsID[friendCount] = fId;
friends[friendCount] = fNm;
friendCount ++;
Log.d("TEST", "Friend Added: " + fNm);
}
//Remove Progress Bar
pb.setVisibility(ProgressBar.GONE);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Feel free to use any of this code in your own projects, or ask any questions about it.
You can private static final String[] PERMISSIONS = new String[] {"publish_stream","status_update",xxxx};xxx is premissions