Categories
discuss

In what cases would it be useful to put a command within a Java for-loop update statement? [closed]

I found out yesterday that you can make a Java for-loop that looks like this

for (int j = 0; j < myArray.length; System.out.println(j), j++ ) {

/* code */

}

This looks really unusual to me. When is coding like this acceptable/useful?

Answer

The official java documentation says the following about for-loops:

The general form of the for statement can be expressed as follows:

for(initialization; termination; increment) {
     statement(s) 
}

When using this version of the for statement, keep in mind that:

  1. The initialization expression initializes the loop; it’s executed once, as the loop begins.
  2. When the termination expression evaluates to false, the loop terminates.
  3. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

So while it is possible to have something like System.out.println(j) in your increment part, it is against the coding conventions according to the official documentation.

The reason why it is allowed to have multiple comma-separated statements in the increment part is because you may need to adjust the value of multiple variables during the execution of the for loop. So only in this case it is both acceptable and useful to use this syntactic sugar. The following example illustrates this scenario:

for(int i = 0, j = 10; i < 10 && j >= 0; i++, j--) {
   // Statements
}
Categories
discuss

Java driver: how to get the objectId of an updated object with Mongodb’s updateFirst method

I’m trying to get the objectId of an object that I have updated – this is my java code using the java driver:

    Query query = new Query();
    query.addCriteria(Criteria.where("color").is("pink"));
    Update update = new Update();
    update.set("name", name);
    WriteResult writeResult = mongoTemplate.updateFirst(query, update, Colors.class);

    Log.e("object id", writeResult.getUpsertedId().toString());

The log message returns null. I’m using a mongo server 3.0 on mongolab as I’m on the free tier so it shouldn’t return null. My mongo shell is also:

MongoDB shell version: 3.0.7

Is there an easy way to return the object ID for the doc that I have just updated? What is the point of the method getUpsertedId() if I cannot return the upsertedId?

To do what I want, I currently have to issue two queries which is highly cumbersome:

    //1st query - updating the object first
    Query query = new Query();
    query.addCriteria(Criteria.where("color").is("pink"));
    Update update = new Update();
    update.set("name", name);
    WriteResult writeResult = mongoTemplate.updateFirst(query, update, Colors.class);
    //2nd query - find the object so that I can get its objectid
    Query queryColor = new Query();
    queryColor.addCriteria(Criteria.where("color").is("pink"));
    queryColor.addCriteria(Criteria.where("name").is(name));
    Color color = mongoTemplate.findOne(queryColor, Color.class);
    Log.e("ColorId", color.getId());

As per David’s answer, I even tried his suggestion to rather use upsert on the template, so I changed the code to the below and it still does not work:

    Query query = new Query();
    query.addCriteria(Criteria.where("color").is("pink"));
    Update update = new Update();
    update.set("name", name);
    WriteResult writeResult = mongoTemplate.upsert(query, update, Colors.class);

    Log.e("object id", writeResult.getUpsertedId().toString());

Answer

Simon, I think its possible to achieve in one query. What you need is a different method called findAndModify().

In java driver for mongoDB, it has a method called findOneAndUpdate(filter, update, options).

This method returns the document that was updated. Depending on the options you specified for the method, this will either be the document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be returned. Its not required to pass options, in that case it will return the document that was updated before update operation was applied.

A quick look at the mongoTemplate java driver docs here: http://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/FindAndModifyOptions.html tells me that you can use the method call:

public <T> T findAndModify(Query query,
                           Update update,
                           FindAndModifyOptions options,
                           Class<T> entityClass)

You can also change the FindAndModifyOptions class to take on an ‘upsert’ if the item was not found in the query.If it is found, the object will just be modified.

Categories
discuss

Android – Syncano SDK not working

I am developing an android application that uses syncano to send data to a syncano server but the data refuses to send. We have verified that the conditions for our send work, but it does not work. Here is the activity that is used to send the data:

package com.crash.beacon;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import com.crash.beacon.Book;
import com.syncano.library.Syncano;
import com.syncano.library.api.Response;


public class MainActivity extends AppCompatActivity implements SensorEventListener, LocationListener {
    boolean isEnabled = false;
    Button btn;
    private Syncano syncano;
    String[] listItems = new String[]{"Home", "About", "Website"};
    float lat = 0, lng = 0, alt = 0;
    Sensor accel;
    SensorManager manager;
    float x = 0, y = 0, z = 0;
    DrawerLayout dl;
    private ActionBarDrawerToggle mDrawerToggle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button)findViewById(R.id.crash);
        syncano = new Syncano("api_key", "late-surf-9471");
        gui(isEnabled);
        manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accel = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        // Get the location manager
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, false);

        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
           onLocationChanged(location);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    public void onCrash(View view){
          isEnabled = !isEnabled;
          gui(isEnabled);



    }
    public void gui(boolean state){
        if(state){
            btn.setText("Enabled");
        }
        else{
            btn.setText("Disabled");
        }
    }

    @Override
    protected void onResume(){
        super.onResume();
        manager.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);

    }
    @Override
    protected void onPause(){
        super.onPause();
        manager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        x = event.values[0];
        y = event.values[1];
        z = event.values[2];
        //Demo values
        //For actual deployment, use lat, alt, and lng variables
        float hLat = 39, hLng = -75, hAlt = 25;
        final Book book = new Book();
        book.latitude = lat;
        book.longitutde = lng;
        book.altitude = alt;
        book.force_x = x;
        book.force_y = y;
        book.force_y = z;


        if(isEnabled){
            if(Math.abs(x) > 20 && Math.abs(y) > 20 && Math.abs(z) > 20){
            new Network(book, syncano).execute();
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onLocationChanged(Location location) {
        lat = (float)location.getLatitude();
        lng = (float)location.getLongitude();
        alt = (float)location.getAltitude();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

Network.java

package com.crash.beacon;

import android.os.AsyncTask;
import android.util.Log;

import com.syncano.library.Syncano;
import com.syncano.library.api.Response;

import java.util.List;

/**
 * Created by Tienvo on 11/8/2015.
 */
public class Network extends AsyncTask<String, Void, String> {
    Book b;
    Syncano syn;
    public Network(Book book, Syncano syncano){
        this.b = book;
        this.syn = syncano;
    }
    @Override
    protected String doInBackground(String... params) {
       //Response<Book> responseCreateObject = syn.createObject(b).send();
        Log.d("code", String.valueOf(Response.CODE_SUCCESS));
        Response<List<Book>> responseGetBooks = syn.createObject(b).send();
        return "Executed";
    }
}

Book.java

package com.crash.beacon;

import com.syncano.library.annotation.SyncanoClass;
import com.syncano.library.annotation.SyncanoField;
import com.syncano.library.data.SyncanoObject;
/**
 * Created by tom on 11/7/15.
 */
@SyncanoClass(name = "ltds")
public class Book extends SyncanoObject{
    public static final String FIELD_LAT = "latitude";
    public static final String FIELD_LNG = "longitude";
    public static final String FIELD_ALT = "altitude";
    public static final String FIELD_X =   "force_x";
    public static final String FIELD_Y =   "force_y";
    public static final String FIELD_Z =   "force_z";

    @SyncanoField(name = FIELD_LAT)
    public float latitude;

    @SyncanoField(name = FIELD_LNG)
    public float longitutde;

    @SyncanoField(name = FIELD_ALT)
    public float altitude;

    @SyncanoField(name = FIELD_X)
    public float force_x;

    @SyncanoField(name = FIELD_Y)
    public float force_y;

    @SyncanoField(name = FIELD_Z)
    public float force_z;


}

Answer

That’s how your sending method may look like.
When you create an object, your result code should be HTTP_CODE_CREATED 201 and response type Response<Book>. When you download objects, your response code should be HTTP_CODE_SUCCESS 200 and response type Response<List<Book>>

    @Override
    protected String doInBackground(String... params) {
        // send object to server
        Response<Book> responseCreateObject = syn.createObject(b).send();
        if (responseCreateObject.getHttpResultCode() == Response.HTTP_CODE_CREATED) {
            Log.d(TAG, "Success. Item created.");
        } else {
            Log.d(TAG, "Fail.");
        }

        // get objects from server
        Response<List<Book>> responseGetObjects = syn.getObjects(Book.class).send();
        if (responseGetObjects.getHttpResultCode() == Response.HTTP_CODE_SUCCESS) {
            List<Book> books = responseGetObjects.getData();
            Log.d(TAG, "Success. Items downloaded: " + books.size());
        } else {
            Log.d(TAG, "Fail.");
        }

        return "Executed";
    }

I simplified your code a little, to focus on Syncano connection and it works! It creates an object on your Syncano instance.

package com.chimeraprime.syncano4libcheck;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.syncano.library.Syncano;
import com.syncano.library.annotation.SyncanoClass;
import com.syncano.library.annotation.SyncanoField;
import com.syncano.library.api.Response;
import com.syncano.library.data.SyncanoObject;

import java.util.List;
import java.util.Random;


public class OtherActivity extends AppCompatActivity {
    private Button btn;
    private Syncano syncano;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);

        syncano = new Syncano("<api_key>", "<instance>");
        btn = (Button) findViewById(R.id.crash);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Random rnd = new Random();

                Book book = new Book();
                book.latitude = rnd.nextFloat();
                book.longitutde = rnd.nextFloat();
                book.altitude = rnd.nextFloat();
                book.force_x = rnd.nextFloat();
                book.force_y = rnd.nextFloat();
                book.force_y = rnd.nextFloat();

                new Network(book, syncano).execute();
            }
        });
    }


    public static class Network extends AsyncTask<String, Void, String> {
        Book b;
        Syncano syn;
        String TAG = Network.class.getSimpleName();

        public Network(Book book, Syncano syncano) {
            this.b = book;
            this.syn = syncano;
        }

        @Override
        protected String doInBackground(String... params) {
            // send object to server
            Response<Book> responseCreateObject = syn.createObject(b).send();
            if (responseCreateObject.getHttpResultCode() == Response.HTTP_CODE_CREATED) {
                Log.d(TAG, "Success. Item created.");
            } else {
                Log.d(TAG, "Fail.");
            }

            // get objects from server
            Response<List<Book>> responseGetObjects = syn.getObjects(Book.class).send();
            if (responseGetObjects.getHttpResultCode() == Response.HTTP_CODE_SUCCESS) {
                List<Book> books = responseGetObjects.getData();
                Log.d(TAG, "Success. Items downloaded: " + books.size());
            } else {
                Log.d(TAG, "Fail.");
            }

            return "Executed";
        }
    }

    @SyncanoClass(name = "ltds")
    public class Book extends SyncanoObject {
        public static final String FIELD_LAT = "latitude";
        public static final String FIELD_LNG = "longitude";
        public static final String FIELD_ALT = "altitude";
        public static final String FIELD_X = "force_x";
        public static final String FIELD_Y = "force_y";
        public static final String FIELD_Z = "force_z";

        @SyncanoField(name = FIELD_LAT)
        public float latitude;

        @SyncanoField(name = FIELD_LNG)
        public float longitutde;

        @SyncanoField(name = FIELD_ALT)
        public float altitude;

        @SyncanoField(name = FIELD_X)
        public float force_x;

        @SyncanoField(name = FIELD_Y)
        public float force_y;

        @SyncanoField(name = FIELD_Z)
        public float force_z;
    }
}
Categories
discuss

JAVAFX : why wait cursor needs a new thread?

I would understand why

 scene.setCursor(Cursor.WAIT);
 long task...
 scene.setCursor(Cursor.DEFAULT);

needs new threads; it works with:

private void set_cursore_attesa(final Scene scene)
{
    Runnable r=new Runnable() {

        @Override
        public void run() {
             scene.setCursor(Cursor.WAIT);
        }
    };
    Thread t=new Thread(r);
    t.start();
}
private void set_cursore_normale(final Scene scene)
{
        Runnable r=new Runnable() {

        @Override
        public void run() {
             scene.setCursor(Cursor.DEFAULT);
        }
    };
    Thread t=new Thread(r);
    t.start();
}

in my function:
set_cursore_attesa(scene);
long task...
set_cursore_normale(scene);

why I can’t use the same thread? I:

  1. set my cursor to WAIT (it goes in GUI queue)
  2. do my long task… (it goes in GUI queue but I expected that cursor changing, that is up in queue, it is executed before this)
  3. reset my cursor to DEFAULT (after my task has finished)

So, my long task doesn’t go in MAIN queue? because, if it goes in main queue, I expected it’s executed after my WAIT cursor that is inserted in queue first. Why this behavior?

Answer

Without the threads, your code is being executed on the FX Application Thread. This is the thread that is (effectively) responsible for rendering the UI to the screen and for processing user input. If you execute a long-running task on this thread, then you prevent any of the normal functionality of the FX Application Thread from occurring until your long-running task is complete. In particular, if you do

scene.setCursor(Cursor.WAIT);
longRunningTask();
scene.setCursor(Cursor.DEFAULT);

then the settings take place in the order you specify, but the scene does not get rerendered until all lines of code are complete. Hence you never actually see any changes to the UI – including the change to the cursor – until after your code is complete. The next time the FX Application Thread has an opportunity to render the scene, the cursor is set to Cursor.DEFAULT, and you never see the wait cursor.

There are two basic rules for multithreading and JavaFX (and the same rules generally apply to most UI toolkits):

  1. Any changes to the UI must be performed on the FX Application Thread
  2. Long-running processes should not be performed on the FX Application Thread (as they make the UI unresponsive)

So your solution is not actually correct, because you violate both of those rules. You should

  1. Set the cursor to WAIT on the FX Application Thread
  2. Start your long running task on a background thread
  3. When the task is complete, set the cursor back to DEFAULT, on the FX Application Thread.

You can do this using a Task:

scene.setCursor(Cursor.WAIT);
Task<Void> task = new Task<Void>() {
    @Override
    public Void call() {
        // long running task here...
        return null ;
    }
};
task.setOnSucceeded(e -> scene.setCursor(Cursor.DEFAULT));
new Thread(task).start();
Categories
discuss

How to remove the blue action bar in android?

I am creating an android app but I have some problem I cant remove this blue heading or I don’t know how its called, or action bar ? I have tried some methods but they didn’t work. enter image description here

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"

    tools:showIn="@layout/activity_main"
    tools:context=".MainActivity"
    android:background="#9AEA30">

    <ImageView
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:id="@+id/imageView"
        android:src="@drawable/discount"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

Answer

The easiest way to remove it is to make your Activity extend the Activity class and not the AppCompatActivity.

That is do something like this:

public class MyActivity extends Activity {

}
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..