Menu
  • HOME
  • TAGS

PreparedStatement.executeUpdate() doesn't insert in sqlite database

Tag: java,database,sqlite

i'm trying to make a DAO class for my Java project. I've a SQLite Database with only one table "USER". The schema is:

    CREATE TABLE USER(
username VARCHAR(20) NOT NULL PRIMARY KEY,
password VARCHAR NOT NULL,
total_matches INTEGER DEFAULT 0,
victories INTEGER DEFAULT 0,
times_alien INTEGER DEFAULT 0,
times_human INTEGER DEFAULT 0,
total_steps INTEGER DEFAULT 0,
humans_killed INTEGER DEFAULT 0,
aliens_killed INTEGER DEFAULT 0,
kills_as_human INTEGER DEFAULT 0,
kills_as_alien INTEGER DEFAULT 0,
total_escapes INTEGER DEFAULT 0,
total_broken_hatches INTEGER DEFAULT 0,
total_noises INTEGER DEFAULT 0,
online_status VARCHAR(5) NOT NULL DEFAULT "false");

My UserDAOImpl class has findAll(), findByNickname(String nickname), insert, update, delete methods.

I use PreparedStatementto prevent SQL Injection.

My Issue is that if I call my insert(User toInsert) method and then cycle through the findAll() result, I can see the right insertion.

But if I go to the Terminal and open the DB with the SQLite command line, when I execute "SELECT * FROM USER", the previous insertion doesn't shows.

The DB Class:

/**
 * The Class DB.
 * Gives a connection to the game Database.
 */
public class DB {

/**  the singleton instance of the Database. */
    private static DB instance = new DB();

    /**  the path to the database. */
    private static final String DBPath = "db/eftaios_DB.db";



    /**
     * Istantiates a new Database.
     */
    private DB(){
        /*
         * 
         */
    }

    /**
     * Create a connection between this class and the database files.
     *
     * @return the database connection.
     * @throws SQLException the SQL exception
     */
    public Connection connect() throws SQLException{
        Connection dbConnection = null;
        try {

            Class.forName("org.sqlite.JDBC");
            String dbPath = DB.class.getClassLoader().getResource(DBPath).getPath();
            dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbPath);

        } catch (ClassNotFoundException e) {
            /*
             * do nothing, the class is imported in the maven dependencies
             */
        } catch (SQLException e) {
            throw new SQLException();
        }
        return dbConnection;
    }

The DAO Class is:

/**
 * The class UserDAOImpl implements the UserDAOInterface
 * It implements a DAO (Data Access Object) for the User table.
 * It gives access to the User table on the Database.
 * With this class you can perform queries like find, insert, delete and update on the USER table.
 */
public class UserDAOImpl implements UserDAOInterface {

    /**  the database connection used to query it. */
    private Connection dbConnection;

    /**  the result of a query to the database. */
    private ResultSet queryResult;

    /**  the statement to execute to perform db queries. */
    private Statement queryStatement;

    /**  the prepared statement to execute mysql injection secure queryes. */
    private PreparedStatement queryPreparedStatement;

    /**  the name of the database user's table. */
    private static final String USER_TABLE = "USER";

    /**
     * To user list.
     *
     * @param qryResult the qry result
     * @return the list
     * @throws SQLException the SQL exception
     */
    private List<User> toUserList(ResultSet qryResult) throws SQLException{
        List<User> result = new ArrayList<User>();
        /* forall user in result, populate the new user and add it to the users list */
        while(qryResult.next()){
            User record = new User();
            record.setNickname(qryResult.getString(User.NICKNAME_COL_NAME));
            record.setPassword(qryResult.getString(User.PASSWORD_COL_NAME));
            record.setAliensKilled(qryResult.getInt(User.ALIENS_KILLED_COL_NAME));
            record.setHumansKilled(qryResult.getInt(User.HUMANS_KILLED_COL_NAME));
            record.setKillsAsAlien(qryResult.getInt(User.KILLS_AS_ALIEN_COL_NAME));
            record.setKillsAsHuman(qryResult.getInt(User.KILLS_AS_HUMAN_COL_NAME));
            record.setOnlineStatus(qryResult.getBoolean(User.ONLINE_STATUS_COL_NAME));
            record.setTimesAlien(qryResult.getInt(User.TIMES_ALIEN_COL_NAME));
            record.setTimesHuman(qryResult.getInt(User.TIMES_HUMAN_COL_NAME));
            record.setTotalBrokenHatches(qryResult.getInt(User.TOTAL_BROKEN_HATCHES_COL_NAME));
            record.setTotalEscapes(qryResult.getInt(User.TOTAL_ESCAPES_COL_NAME));
            record.setTotalMatches(qryResult.getInt(User.TOTAL_MATCHES_COL_NAME));
            record.setTotalNoises(qryResult.getInt(User.TOTAL_NOISES_COL_NAME));
            record.setTotalSteps(qryResult.getInt(User.TOTAL_STEPS_COL_NAME));
            record.setVictories(qryResult.getInt(User.VICTORIES_COL_NAME));
            result.add(record);
        }
        return result;
    }

    /*
     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#findAll()
     */
    @Override
    public List<User> findAll() throws SQLException {

        String findAllQuery = "SELECT * FROM "+USER_TABLE;

        List<User> users = new ArrayList<User>();
        this.dbConnection   = DB.getDatabase().connect();
        this.dbConnection.setAutoCommit(false);
        this.queryStatement = this.dbConnection.createStatement();
        this.queryResult    = this.queryStatement.executeQuery(findAllQuery);

        users = this.toUserList(queryResult);

        this.dbConnection.commit();
        this.queryResult.close();
        this.queryStatement.close();
        this.dbConnection.close();
        return users;
    }

    /*
     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#findByNickname(java.lang.String)
     */
    @Override
    public List<User> findByNickname(String userNickname) throws SQLException {

        String findByNicknameQuery = "SELECT * FROM "+USER_TABLE+" WHERE "+User.NICKNAME_COL_NAME+"=?";

        List<User> users = new ArrayList<User>();
        this.dbConnection = DB.getDatabase().connect();
        this.dbConnection.setAutoCommit(false);

        /* preparing the statement to prevent sql injection */
        this.queryPreparedStatement = this.dbConnection.prepareStatement(findByNicknameQuery);
        this.queryPreparedStatement.setString(1, userNickname);

        /* now get the result */
        this.queryResult = this.queryPreparedStatement.executeQuery();

        users = this.toUserList(queryResult);

        this.dbConnection.commit();
        this.queryPreparedStatement.close();
        this.queryResult.close();
        this.dbConnection.close();

        return users;
    }

    /*
     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#insert(it.polimi.ingsw.deolacremona.server.model.database.User)
     */
    @Override
    public boolean insert(User toInsert) throws SQLException {

            boolean result = false;
            MD5Hasher hasher = new MD5Hasher();
            String md5Password = hasher.md5(toInsert.getPassword());

            String insertQuery = 

                    "INSERT INTO "+USER_TABLE+" ("+User.NICKNAME_COL_NAME+","+User.PASSWORD_COL_NAME+") VALUES (?,?)";

            this.dbConnection = DB.getDatabase().connect();
            this.dbConnection.setAutoCommit(false);

            /* preparing the statement to prevent sql injection */
            this.queryPreparedStatement = this.dbConnection.prepareStatement(insertQuery);
            this.queryPreparedStatement.setString(1, toInsert.getNickname());
            this.queryPreparedStatement.setString(2, md5Password);

            if(this.queryPreparedStatement.executeUpdate()==1)
                result = true;



            this.queryPreparedStatement.close();
            this.dbConnection.commit();
            this.dbConnection.close();

            return result;
    }

    /*
     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#update(it.polimi.ingsw.deolacremona.server.model.database.User)
     */
    @Override
    public boolean update(User toUpdate) throws SQLException {
        boolean result = false;

        String updateQuery = "UPDATE "+USER_TABLE+" SET "
                + User.ALIENS_KILLED_COL_NAME        +"=?,"
                + User.HUMANS_KILLED_COL_NAME        +"=?,"
                + User.KILLS_AS_ALIEN_COL_NAME       +"=?,"
                + User.KILLS_AS_HUMAN_COL_NAME       +"=?,"
                + User.ONLINE_STATUS_COL_NAME        +"=?,"
                + User.TIMES_ALIEN_COL_NAME          +"=?,"
                + User.TIMES_HUMAN_COL_NAME          +"=?,"
                + User.TOTAL_BROKEN_HATCHES_COL_NAME +"=?,"
                + User.TOTAL_ESCAPES_COL_NAME        +"=?,"
                + User.TOTAL_MATCHES_COL_NAME        +"=?,"
                + User.TOTAL_NOISES_COL_NAME         +"=?,"
                + User.TOTAL_STEPS_COL_NAME          +"=?,"
                + User.VICTORIES_COL_NAME            +"=?"
                + " WHERE "+User.NICKNAME_COL_NAME+"=?";


        /* preparing the sql statement to prevent sql injection */
        this.dbConnection = DB.getDatabase().connect();
        this.dbConnection.setAutoCommit(false);
        this.queryPreparedStatement = this.dbConnection.prepareStatement(updateQuery);
        this.queryPreparedStatement.setInt    (1, toUpdate.getAliensKilled());
        this.queryPreparedStatement.setInt    (2, toUpdate.getHumansKilled());
        this.queryPreparedStatement.setInt    (3, toUpdate.getKillsAsAlien());
        this.queryPreparedStatement.setInt    (4, toUpdate.getKillsAsHuman());
        this.queryPreparedStatement.setBoolean(5, toUpdate.isOnlineStatus());
        this.queryPreparedStatement.setInt    (6, toUpdate.getTimesAlien());
        this.queryPreparedStatement.setInt    (7, toUpdate.getTimesHuman());
        this.queryPreparedStatement.setInt    (8, toUpdate.getTotalBrokenHatches());
        this.queryPreparedStatement.setInt    (9, toUpdate.getTotalEscapes());
        this.queryPreparedStatement.setInt    (10, toUpdate.getTotalMatches());
        this.queryPreparedStatement.setInt    (11, toUpdate.getTotalNoises());
        this.queryPreparedStatement.setInt    (12, toUpdate.getTotalSteps());
        this.queryPreparedStatement.setInt    (13, toUpdate.getVictories());
        this.queryPreparedStatement.setString (14, toUpdate.getNickname());

        if(this.queryPreparedStatement.executeUpdate()==1){
            result = true;
        }


        this.queryPreparedStatement.close();
        this.dbConnection.commit();
        this.dbConnection.close();
        return result;
    }


    /*
     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#updateAdder(it.polimi.ingsw.deolacremona.server.model.database.User)
     */
    @Override
    public boolean updateAdder(User toUpdate) {
        // TODO Auto-generated method stub
        return false;
    }

    /*
     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#delete(it.polimi.ingsw.deolacremona.server.model.database.User)
     */
    @Override
    public boolean delete(User toDelete) throws SQLException {

        boolean result = false;

        String deleteQuery = "DELETE FROM "+USER_TABLE+" WHERE username=?";

        this.dbConnection = DB.getDatabase().connect();
        this.dbConnection.setAutoCommit(false);

        this.queryPreparedStatement = this.dbConnection.prepareStatement(deleteQuery);
        this.queryPreparedStatement.setString(1, toDelete.getNickname());

        if(this.queryPreparedStatement.executeUpdate()==1){
            result = true;
        }

        this.queryPreparedStatement.close();
        this.dbConnection.commit();
        this.dbConnection.close();

        return result;
    }
}

My test main method is:

public static void main(String[] args) throws SQLException, UnknownHostException{
        DB database = DB.getDatabase();
        database.connect();

        MD5Hasher h = new MD5Hasher();

        UserDAOImpl d = new UserDAOImpl();

        User s = new User();
        s.setNickname("davide");
        s.setPassword("ciao");

        if(d.insert(s))
            System.out.println("insert");       
//      d.delete(s);

        for(User x : d.findAll()){
            System.out.println("Nickname: "+x.getNickname()+" password: "+x.getPassword()+" matches: "+x.getTotalMatches());
        }
    }

Thank you for your time.

EDIT: when I cut the database and put it into another directory, exit eclipse, move back the database in his previous directory and reopen eclipse, then all the changes that Java done previously are lost. –

Best How To :

SOLVED: In a Maven Project, all the resources are copied into another directory after the "build" command. I was reading the wrong db.

Join files using Apache Spark / Spark SQL

java,apache-spark,apache-spark-sql

If you use plain spark you can join two RDDs. let a = RDD<Tuple2<K,T>> let b = RDD<Tuple2<K,S>> RDD<Tuple2<K,Tuple2<S,T>>> c = a.join(b) This produces an RDD of every pair for key K. There are also leftOuterJoin, rightOuterJoin, and fullOuterJoin methods on RDD. So you have to map both datasets to...

Getting particular view from expandable listview

java,android,listview,android-fragments,expandablelistview

You shouldn't pass your view item form a fragment to an other. You should retrieve the object associated with your group view, pass this object to your second/edition fragment. You can use setTargetFragment(...) and onActivityResult(...) to send the modified text from your second to your first fragment. And then you...

Get network interfaces on remote machine

java,network-programming

No, we cannot by definition. The IP address is needed to hide the mac address from external world. To retrieve it you definitely need some code running on that machine. It means that you need some kind of agent. You can either implement it in Java or use platform specific...

SOAP Client, Following an example

java,soap,saaj

Actually you can generate class with soap ui. And your program can easily call the service using the class created without construct your own request header and body But you need some library. Example java jdk comes with jax-ws lib tutorial: http://www.soapui.org/soap-and-wsdl/soap-code-generation.html...

@RestController throws HTTP Status 406

java,spring,rest,maven

The issue is with the dependencies that you have in pom.xml file. In Spring 4.1.* version the pom.xml dependency for Jackson libraries should include these: <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.4.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.1.1</version> </dependency> You...

Java Scanner not reading newLine after wrong input in datatype verification while loop

java,while-loop,java.util.scanner

You are reading too much from the scanner! In this line while (sc.nextLine() == "" || sc.nextLine().isEmpty()) you are basically reading a line from the scanner, comparing it (*) with "", then forgetting it, because you read the next line again. So if the first read line really contains the...

Bulkheading strategies for Akka actors

java,asynchronous,akka,blocking,future

If I understand this correctly, you kind of have two options here: you listen to a Future being completed or you do something with the result: If you want to listen, you can use some callback like final ExecutionContext ec = system.dispatcher(); future.onSuccess(new OnSuccess<String>() { public void onSuccess(String result) {...

type conversion if flex

java,actionscript-3,flex

You try to cast data type mx.collections:IList to UI component type spark.components:List, which of course leads to exception. Try to follow the error message hint and use mx.collections:IList: screenList.addAll(event.result as IList); ...

How to check if an ExecutionResult is empty in Neo4j

java,neo4j

An execution result is essentially an iterator of a map, its type definition is something like: Iterable<Map<String,Object>> So you can easily just do: result.iterator().hasNext(); I think that its strictly a ResourceIterator, so if you get an iterator you are supposed to close it if you don't exhaust it. Check the...

Get element starting with letter from List

java,android,list,indexof

The indexOf method doesn't accept a regex pattern. Instead you could do a method like this: public static int indexOfPattern(List<String> list, String regex) { Pattern pattern = Pattern.compile(regex); for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s != null && pattern.matcher(s).matches()) { return...

How to do custom rounding of numbers in Java?

java,rounding

Math.floor(x+0.7) should do it. This should work for an arbitrary mantissa. Just add the offset to the next integer to your value and round down. The rounding is done by floor. Here is what the java API says to floor: Returns the largest (closest to positive infinity) double value that...

App Not Downloading Newest Version Of File [Java]

java,caching,download

Use URLConnection.setUseCaches(boolean);. In your case, it would be connection.setUseCaches(false);...

setOnClickListener error Null object

java,android

After super.onCreate(savedInstanceState); insert setContentView(R.layout.YourLayout); you need to make a request to a server in another thread. It might look like public class LoginTask extends AsyncTask<Void, Void, String>{ private String username; private String password; private Context context; public LoginTask(Context context, String username, String password) { this.username = username; this.password = password;...

Get the value of the last inserted record

java,jdbc

You may try this query: select stop_name from behaviour where created_at in (select max(created_at) from behaviour) ...

count items in a column vaadin

java,vaadin

Columns don't contain items, Rows contain items. You can set the visible columns by passing a array to the setVisibleColumns methos of the Table. It could also be a idea, to just colapse the column, not hiding it... Determining if all values of this colum are empty should be simple...

PropertyNotFoundException in jsp

java,jsp

The name of your getter & setter is wrong. By convention it must be: public Integer getSurvey_id() { return survey_id; } public void setSurvey_id(Integer survey_id) { this.survey_id=survey_id; } ...

custom arraylist get distinct

java,android

It's not possible to do this using only the ArrayList. Either implement your own method which can be as simple as: private List<mystatistik> getAllUniqueEnemies(List<mystatistik> list){ List<mystatistik> uniqueList = new ArrayList<mystatistik>(); List<String> enemyIds = new ArrayList<String>(); for (mystatistik entry : list){ if (!enemyIds.contains(entry.getEnemyId())){ enemyIds.add(entry.getEnemyId()); uniqueList.add(entry); } } return uniqueList; } Or...

Java dice roll with unexpected random number

java,if-statement

else { System.out.println(diceNumber); } You are printing the address of diceNumber by invoking its default toString() function in your else clause. That is why you are getting the [email protected] The more critical issue is why it gets to the 'else' clause, I believe that is not your intention. Note: In...

What type of database is the best for storing array or object like data [on hold]

database,node.js,sockets

Redis would probably be fastest, especially if you don't need a durability guarantee - most of the game can be played out using Redis' in-memory datastore, which is probably gonna be faster than writing to any disk in the world. Perhaps periodically, you can write the "entire game" to disk....

WebDriver can't get dropdown menu element (Java)

java,selenium,webdriver,junit4

Your ID is dynamic, so you can't use it. Select will not work in your case, you just need to use two clicks WebElement dropdown = driver.findElement(By.xpath("//div[@class='select-pad-wrapper AttributePlugin']/input")); dropdown.click(); WebElement element = driver.findElement(By.xpath("//div[@class='select-pad-wrapper AttributePlugin']/div/ul/li[text()='Image']")); element.click(); ...

If I export my database with phpmyadmin will it lock my tables or take my database down?

mysql,database,phpmyadmin

The answer is no, tables won't be locked, database won't be down. But, if your database is large and it takes long time to backup it, you can sometimes expect performance degradation(slow SQL queries from your application).

How to call MySQL view in Struts2 or Hibernate

java,mysql,hibernate,java-ee,struts2

You can simply create an Entity, that's mapping the database view: @Entity public class CustInfo { private String custMobile; private String profession; private String companyName; private Double annualIncome; } Make sure you include an @Id in your view as well, if that's an updatable view. Then you can simply use...

error: cannot find symbol class AsyncCallWS Android

java,android,web-services

On the link you post, I see a class like below. Create this class in your project before using it. private class AsyncCallWS extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params) { Log.i(TAG, "doInBackground"); getFahrenheit(celcius); return null; } @Override protected void onPostExecute(Void result) { Log.i(TAG, "onPostExecute"); tv.setText(fahren +...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring

java,spring,jsp,spring-mvc

Say you have a jsp test.jsp under /WEB-INF/jsp/reports From your controller return @RequestMapping("/helloWorld") public String helloWorld(Model model) { model.addAttribute("message", "Hello World!"); return "reports/test"; } ...

Using world coordinates

java,libgdx

You shouldn't use constant a pixel-to-unit conversion, as this would lead to different behavior on different screen sizes/resolutions. Also don't forget about different aspect ratios, you also need to take care about them. The way you should solve this problem is using Viewports. Some of them support virtual screen sizes,...

Foreign key in C#

c#,sql,sql-server,database

You want create relationship in two table Refer this link http://www.c-sharpcorner.com/Blogs/5608/create-a-relationship-between-two-dataset-tables.aspx...

MySQL: Select several rows based on several keys on a given column

mysql,sql,database

If you are looking to find the records matching with both the criteria here is a way of doing it select `item_id` FROM `item_meta` where ( `meta_key` = 'category' and `meta_value` = 'Bungalow' ) or ( `meta_key` = 'location' AND `meta_value` = 'Lagos' ) group by `item_id` having count(*)=2 ...

Numeric literals in Java - octal? [duplicate]

java,literals,octal

-0777 is treated by the compiler as an octal number (base 8) whose decimal value is -511 (-(64*7+8*7+7)). -777 is a decimal number.

Android String if-statement

java,android,string

Correct me if I'm wrong. If you're saying that your code looks like this: new Thread(new Runnable() { public void run() { // thread code if (ready.equals("yes")) { // handler code } // more thread code }).start(); // later on... ready = "yes"; And you're asking why ready = "yes"...

Selenium catch popup on close browser

java,selenium,browser

Instead of using driver.quit() to close the browser, closing it using the Actions object may work for you. This is another way to close the browser using the keyboard shortcuts. Actions act = new Actions(driver); act.sendKeys(Keys.chord(Keys.CONTROL+"w")).perform(); Or, if there are multiple tabs opened in driver window: act.sendKeys(Keys.chord(Keys.CONTROL,Keys.SHIFT+"w")).perform(); ...

Can I install 2 or more Android SDK when using Eclipse

java,android,eclipse,sdk,versions

There shouldn't be any problem if you use the latest SDK version ; actually, this is recommended. However, make sure to set the correct "Target SDK", i.e. the highest android version you have successfully tested your app with, and the "Minimum Required SDK" as well....

why java API prevents us to call add and remove together?

java,list,collections,listiterator

You're reading the wrong documentation: you should read ListIterator's javadoc. It says: Throws: ... IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous Now, if you want a reason, it's rather simple. You're playing...

Get document on some condition in elastic search java API

java,elasticsearch,elasticsearch-plugin

When indexing documents in this form, Elasticsearch will not be able to parse those strings as dates correctly. In case you transformed those strings to correctly formatted timestamps, the only way you could perform the query you propose is to index those documents in this format { "start": "2010-09", "end":...

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]

java,android,eclipse,adt

In your MainActivity.java at line no 34 you are trying to initialize some widget that is not present in your xml layout which you have set it in your setContentView(R.layout.... That;s why you are geting nullpointerexception. EDIT: change your setContentView(R.layout.activity_main) to setContentView(R.layout.fragment_main)...

Android Implicit Intent for Viewing a Video File

java,android,android-intent,uri,avd

Change your onClick method to below code. You should give the option to choose the external player. @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("https://youtu.be/jxoG_Y6dvU8"), "video/*"); startActivity(Intent.createChooser(intent, "Complete action using")); } ...

How can implement long running process in spring hibernate?

java,spring,hibernate

I recommend you to use DeferredResult of Spring. It´s a Future implementation, that use the http long poling technique. http://docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/web/context/request/async/DeferredResult.html So let´s says that you will make a request, and the server it will return you the deferredResult, and then your request will keep it open until the internal process(Hibernate)...

How to block writes to standard output in java (System.out.println())

java,logging,stdout

If you can identify the thread you want to "mute" reliably somehow (e.g. by name), you can setOut to your own stream which will only delegate the calls to the actual System.out if they don't come from the muted thread.

Get current latitude and longitude android

java,android,gps,geolocation,location

See my post at http://gabesechansoftware.com/location-tracking/. The code you're using is just broken. It should never be used. The behavior you're seeing is one of the bugs- it doesn't handle the case of getLastLocation returning null, an expected failure. It was written by someone who kind of knew what he was...

Android set clickable text to go one fragment to another fragment

java,android,android-fragments,spannablestring

If LoginActivity is a fragment class then it would be okay is you use setOnClickListener on textview. But for fragment change you have to change Intent to fragmentTransaction, Use something like, textview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().beginTransaction().replace(R.id.container, new LoginActivity() ).addToBackStack("").commit(); }); But, if you want to...

Reading and modifying the text from the text file in Java

java

I wrote a quick method for you that I think does what you want, i.e. remove all occurrences of a token in a line, where that token is embedded in the line and is identified by a leading dash. The method reads the file and writes it straight out to...

Mysterious claim of a missing { in eclipse

java,eclipse

In Java, you cannot write executable statements directly in class.So this is syntactically wrong: for(int i=0; i<10; i++) { this.colorList[i] = this.allColors[this.r.nextInt(this.allColors.length)]; } Executable statements can only be in methods/constructors/code blocks...

Why am getting this error?: Unknown column 'firstname' in 'field list'

php,database,mysqli

$query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, $firstname, $lastname,$username,$password)"; you need single quote around text feilds in sql queries change above query to $query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, '$firstname', '$lastname','$username','$password')"; ...

BitmapFont class does not have getBound(String) method

java,android,libgdx

After the API 1.5.6 we have a different way to get the String bound. try this GlyphLayout layout = new GlyphLayout(); layout.setText(bitmapFont,"text"); float width = layout.width; float height = layout.height; and it's not recommended to create new GlyphLayout on each frame, create once and use it. ...

Pull information from SQL database and getting login errors

php,sql,database

change $username = "'rylshiel_order"; to $username = "rylshiel_order"; and you should be through. You are passing on an extra single quote here. ...

Finding embeded xpaths in a String

java,regex

Use {} instead of () because {} are not used in XPath expressions and therefore you will not have confusions.

Interpreting hex dump of java class file

java,class,hex

The 000000b0 is not part of the data. It's the memory address where the following 16 bytes are located. The two-digit hex numbers are the actual data. Read them from left to right. Each row is in two groups of eight, purely to asist in working out memory addresses etc....

Javadoc: Do parameter and return need an explicit type description

java,types,javadoc

No, there's no need, the JavaDoc tool parses the Java code and gets the types from there. This article on the Oracle Java site may be useful: How to Write Doc Comments for the Javadoc Tool From the @param part of that article: The @param tag is followed by the...

Logging operations in lightadmin

java,spring,logging,lightadmin

You can use the class AbstractRepositoryEventListener like it's show on the LightAdmin documentation here Add you logger insertion by overiding onAfterSave, onAfterCreate and onAfterDelete into your own RepositoryEventListener. After you just need to register your listener like this public class YourAdministration extends AdministrationConfiguration<YourObject> { public EntityMetadataConfigurationUnit configuration(EntityMetadataConfigurationUnitBuilder configurationBuilder) { return...

Form submit portlet with Spring MVC

java,jsp,spring-mvc,liferay,portlet

Which version of Liferay you are using? if it is > 6.2 GA1 Then in your liferay-portlet.xml file, please add this attribute and recompile and test again. <requires-namespaced-parameters>false</requires-namespaced-parameters> Liferay adds namespace to the request parameters by default. You need to disable it. ...

how to call Java method which returns any List from R Language? [on hold]

java,r,rjava

You can do it with rJava package. install.packages('rJava') library(rJava) .jinit() jObj=.jnew("JClass") result=.jcall(jObj,"[D","method1") Here, JClass is a Java class that should be in your ClassPath environment variable, method1 is a static method of JClass that returns double[], [D is a JNI notation for a double array. See that blog entry for...