This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
My app craches when i try to update my database it gives me the following problem
attempt to invoke virtual method 'android.database.cursor com.leoni.bd.Gestion_db.FindDate(java.lang.String)' on a null object reference
i couldn't find the null object i tried many things but it didn't work ! i need help please !
this is my Gestion_db.java class
private SQLiteDatabase _myDbm;
public Gestion_db(Context pContext) {
SqliteCreator s = new SqliteCreator(pContext, Stat.DB_NAME, null, 1);
_myDbm = s.getWritableDatabase();
}
public void close() {
_myDbm.close();
}
public Cursor FindDate(String Attribute) {
String query = "SELECT * FROM " +Stat.TABLE_NAME +" WHERE ? LIKE '%?%' ";
return _myDbm.rawQuery(query, new String[] {Stat.COL_DATE,Attribute});
}
this is the method from my Controle.java activity wich contain the cursor
//header of the activity
private Gestion_db _myGestionDB;
private String _myRecognizedText = null;
// Mise à jour de la base de données quelque soit l'action
private void MiseAJour() {
String dateCourante = new SimpleDateFormat("yyyy:MM:dd",Locale.getDefault()).format(new Date());
Boolean existe=false;
Cursor c = _myGestionDB.FindDate(dateCourante);
if (c.getCount() != 0) {
c.moveToFirst();
while (!c.isAfterLast()) {
String ldate = c.getString(c.getColumnIndex(Stat.COL_DATE));
String lMatricule = c.getString(c.getColumnIndex(Stat.COL_TEXTE_OCR));
if (ldate.equals(dateCourante)&& lMatricule.equals(_myRecognizedText)) {
existe=true;
break;
}
c.moveToNext();
}
}
if (existe){
UpdateHeure(_myHeure);
}else{
AddVoyage();
}
}
this ic Stat.java class wich contains some Strings
public class Stat {
public static final String DB_NAME = "leoni.db";
public static final String URL_CHECK = "http://192.168.1.6/check.php";
public static final String GET_URL = "http://192.168.1.6/getChauffeurs.php";
public static final String COL_ID = "_id";
// Gestion des déplacements
public static final String TABLE_NAME = "gestion_des_deplacements";
public static final String COL_TEXTE_OCR = "texte_ocr";
public static final String COL_DATE = "date";
public static final String COL_HEURE_DEPART = "heure_depart";
public static final String COL_HEURE_ARRIVEE = "heure_arrive";
public static final String CREATE_TABLE_DEPLACEMENTS = "CREATE TABLE "
+ Stat.TABLE_NAME + " (" + Stat.COL_ID
+ " INTEGER PRIMARY KEY autoincrement," + Stat.COL_TEXTE_OCR
+ " VARCHAR(40)" + "," + Stat.COL_CHAUFFEUR + " VARCHAR(50)" + ","
+ Stat.COL_DATE + " VARCHAR(50)" + "," + Stat.COL_HEURE_DEPART
+ " VARCHAR(30)" + "," + Stat.COL_HEURE_ARRIVEE + " VARCHAR(30));";
// Gestion des chauffeurs
public static final String COL_MATRICULE = "matricule";
public static final String COL_CHAUFFEUR = "chauffeur";
}
Your stacktrace gives you all the needed information:
com.leoni.bd.Gestion_db.FindDate(java.lang.String)' on a null object reference
What is says is that object of type Gestion_db is null. So you look in your code for this object, and you have only one instance of it _myGestionDB, as noted by #ρяσѕρєя.
The error message identifies the method that is the subject of the problematic invocation as com.leoni.bd.Gestion_db.FindDate(java.lang.String). It follows, therefore, that the type of the expression on which the invocation is performed must be com.leoni.bd.Gestion_db or one of its subtypes.
The only candidate in the code you posted is instance variable _myGestionDB. The code you posted does not give any particular reason to think the value would be non-null. Instance variables of reference type are initialized to null by default if they have no initializer. If you fail to set its value to something else prior to invoking the method you show, then it will still be null when the method invocation attempt occurs.
Related
I am working on a Java class that contains a ton of numeric fields. Most of them would begin with something like 'CMTH' or 'FYTD'. Is it possible to initialize all fields of the same type that begin or end with a certain value. For example I have the following fields:
CMthRepCaseACR CMthRepUnitACR CMthRecCaseACR CMthRecUnitACR CMthHecCaseACR CMthHecUnitACR FYTDHecCaseACR FYTDHecUnitACR CMthBBKCaseACR CMthBBKUnitACR CMthPIHCaseACR .
I am trying to figure if it is possible to initialize all fields to zero that end with an 'ACR' or begin with an 'Cmth"
I know I can do something like cmtha = cmthb = cmthc = 0 but I was wondering there was a command where you can some kind of mask to initialize
Thanks
Assuming that you cannot change that said Java class (and e.g. use a collection or map to store the values) your best bet is probably reflection (see also: Trail: The Reflection API). Reflection gives you access to all fields of the class and you can then implement whatever matching you'd like.
Here's a short demo to get you started, minus error handling, sanity checks and adaptions to your actual class:
import java.util.stream.Stream;
public class Demo {
private static class DemoClass {
private int repCaseACR = 1;
private int CMthRepUnit = 2;
private int foo = 3;
private int bar = 4;
#Override
public String toString() {
return "DemoClass [repCaseACR=" + repCaseACR + ", CMthRepUnit=" + CMthRepUnit + ", foo=" + foo + ", bar="
+ bar + "]";
}
}
public static void main(String[] args) {
DemoClass demoClass = new DemoClass();
System.out.println("before: " + demoClass);
resetFields(demoClass, "CMth", null);
System.out.println("after prefix reset: " + demoClass);
resetFields(demoClass, null, "ACR");
System.out.println("after suffix reset: " + demoClass);
}
private static void resetFields(DemoClass instance, String prefix, String suffix) {
Stream.of(instance.getClass().getDeclaredFields())
.filter(field ->
(prefix != null && field.getName().startsWith(prefix))
|| (suffix != null && field.getName().endsWith(suffix)))
.forEach(field -> {
field.setAccessible(true);
try {
field.set(instance, 0);
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO handle me
}
});
}
}
Output:
before: DemoClass [repCaseACR=1, CMthRepUnit=2, foo=3, bar=4]
after prefix reset: DemoClass [repCaseACR=1, CMthRepUnit=0, foo=3, bar=4]
after suffix reset: DemoClass [repCaseACR=0, CMthRepUnit=0, foo=3, bar=4]
Note: Both links are seriously dated but the core functionality of reflection is still the same.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm confused with the objects and constructor in Java. I query from a SQLiteDatabase but I couldn't get the correct object/answer. I know my codes look messy and I need to clean it up but I don't know where to start...
public static class QObject {
public String word;
public String definition;
public QObject(String word, String definition) {
this.word = word;
this.definition = definition;
}
public QObject getAnswer(String message) {
QObject quizObject = null;
String query = "select * from " + TABLE_NAME + " where " + COL_WORD + " = '" + message + "'";
Cursor cursor = this.getDbConnection().rawQuery(query, null);
if(cursor.moveToFirst()) {
do {
String myword = cursor.getString(cursor.getColumnIndexOrThrow(COL_WORD));
String mydefinition = cursor.getString(cursor.getColumnIndexOrThrow(COL_DEFINITION));
quizObject = new QObject(word, definition);
} while (cursor.moveToNext());
}
cursor.close();
return quizObject;
}
private SQLiteDatabase getDbConnection() {
return dbHelper.getReadableDatabase();
}
}
}
public void searchName(View view) {
String word = null;
String definition = null;
DatabaseTable db = new DatabaseTable(this);
DatabaseBackend dbBackend = new DatabaseBackend(MainActivity.this);
DatabaseObject dbo = new DatabaseObject(this);
DatabaseB.QObject quizobject = new DatabaseB.QObject(word, definition);
DatabaseB.QObject allQuizQuestions = quizobject.getAnswer(message);
String answer = allQuizQuestions.definition;
TextView textView = findViewById(R.id.textView2);
textView.setText(answer);
}
The error message is null object reference:
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
...
Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.justkitting.orion.databasetest.MainActivity$DatabaseB$QObject.definition' on a null object reference
at com.justkitting.orion.databasetest.MainActivity.searchName(MainActivity.java:139)
at java.lang.reflect.Method.invoke(Native Method)
...
Many many thanks.
Your exception is thrown at this line: String answer = allQuizQuestions.definition; and it means that allQuizQuestions is null. So in the line above (DatabaseB.QObject allQuizQuestions = quizobject.getAnswer(message);) you get null from getAnswer(message) method. And this can happen if cursor.moveToFirst() returns false and you never call this line of code: quizObject = new QObject(word, definition);.
One more thing I found: constructor in this line quizObject = new QObject(word, definition); is not using Strings you found in your DB, but values of word and definition from QObject class, which are null at this point. You should use myword and mydefinition instead.
Can you post the code with the line numbers(If you are on eclipse right click on the far left side of the editor and select 'show line numbers' ). it looks like you are calling a method on an object which is null. You night need to do a null check before method invocation
How to store 2 integer in array list from result set and how to retrieve it.
I am trying to store the 2 integer to my array list and i don't know if get it correctly because when I am trying to retrieve it, it prints something like this
'tryCheckout$checkout#4f4fffa4' Thanks guys. This is my code so far.
public class checkout{
public int roomtypeid,itemid;
}
ArrayList<checkout> returncheckout = new ArrayList<checkout>();
try{
*String query ="select ri.item_id, ri.roomtype_id from roomtype_tb as rt , roomtypeitem_tb as ri , room_tb as r , reserverooms_tb as rr where rt.roomtype_id = r.roomtype_id and rt.roomtype_id = ri.roomtype_id and ri.roomtype_id = r.roomtype_id and r.room_id = rr.room_id and rr.reservation_id = 10";
PreparedStatement pst =conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next())
{
checkout out = new checkout();
out.roomtypeid = rs.getInt("ri.roomtype_id");
out.itemid = rs.getInt("ri.item_id");
returncheckout.add(out);
}
returncheckout.forEach(System.out::println);
}catch(Exception e)
{
e.printStackTrace();
}*
I didn't see your checkout class. Now I do. Change it to
public class checkout{
public int roomtypeid,itemid;
#Override
public String toString()
{
return "roomtypeid =" + roomtypeid + ", itemid=" + itemid;
}
}
In your checkout class override the toString() method. That is a special method that gets called when an object gets passed to System.out.println. It will look something like this:
#Override
public String toString()
{
return "roomType=" + roomType + ", id=" + id;//Not sure what your variables are. You will need to change this line
}
I think your code is doing what you want, you just need the toString() method to print the result out like you want it.
Java is actually returning the memory address for the object checkout. That is the weird numbers that are output to the screen. Add something like this to the checkout class.
public class checkout{
public int roomtypeid, itemid;
#Override
public String toString()
{
return "Room Type ID: " + roomtypeid + " Item ID: " + itemid";
}
}
The toString() method is called when the object is printed.
I am trying to run my code but every time it throws me this exception
no such column: codigo
This is my code, and the place where it happens.
PolideportivoDAO.java
if (init){
//CategoriaSocial categoria = null;
List<CategoriaSocial> listaDeCategorias = new Vector<CategoriaSocial>();
//Categoria Social
if (CategoriaDAO.getInstance(context).obtenerTodosLasCategorias().size() == 0){
listaDeCategorias.add(CategoriaDAO.getInstance(context).crearCategoriaNueva("1", "Miembro A",
"Miembro con todos los privilegios, pase diario y uso de la piscina"));
listaDeCategorias.add(CategoriaDAO.getInstance(context).crearCategoriaNueva("2", "Miembro B",
"Permiso para uso de las instalaciones tres veces a la semana"));
listaDeCategorias.add(CategoriaDAO.getInstance(context).crearCategoriaNueva("3", "Miembro C",
"Permiso para uso de las instalaciones solo fin de semana de 8 am a 16 pm"));
}
CategoriaDAO.java
public List<CategoriaSocial> obtenerTodosLasCategorias() {
List<CategoriaSocial> categorias = new Vector<CategoriaSocial>();
Cursor cursor = db.query(ICategoriaSQLiteHelper.TABLA_CATEGORIA_SOCIAL,
ICategoriaSQLiteHelper.columnasCategoria, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
CategoriaSocial categoria = crearCategoriaDesdeCursor(cursor);
categorias.add(categoria);
cursor.moveToNext();
}
cursor.close();
return categorias;
}
ICategoriaSQLiteHelper.java
package com.example.polideportivo1;
public class ICategoriaSQLiteHelper{
public static final String TABLA_CATEGORIA_SOCIAL = "Categoria";
public static final String COLUMNA_ID = "id";
public static final String COLUMNA_CODIGO = "codigo";
public static final String COLUMNA_CATEGORIA = "nombre";
public static final String COLUMNA_DESCRIPCION = "descripcion";
public static final String[] columnasCategoria =
{ ICategoriaSQLiteHelper.COLUMNA_ID,
ICategoriaSQLiteHelper.COLUMNA_CODIGO,
ICategoriaSQLiteHelper.COLUMNA_CATEGORIA,
ICategoriaSQLiteHelper.COLUMNA_DESCRIPCION,
};
public static String TABLA_CATEGORIA_SOCIAL_CREACION = "CREATE TABLE "
+ TABLA_CATEGORIA_SOCIAL + "(" + COLUMNA_ID + " INTEGER primary key autoincrement, "
+ COLUMNA_CODIGO + " TEXT not null unique,"
+ COLUMNA_CATEGORIA + " TEXT not null,"
+ COLUMNA_DESCRIPCION + " TEXT"
+ ");";
}
The code samples you posted are not sufficient to see where the exception occurs, so I suppose it happens here:
Cursor cursor = db.query(ICategoriaSQLiteHelper.TABLA_CATEGORIA_SOCIAL ...
and that 1) the table exists 2) it doesn't contain a column named "codigo" (the value of ICategoriaSQLiteHelper.COLUMNA_CODIGO).
Aren't you trying to run your code an old table Categoria that was created a while ago, and that was not containing a column codigoat that time?
If this is so, removing that old table, and creating a new one - this time using TABLA_CATEGORIA_SOCIAL_CREACION as in your above samples - should solve the issue.
The error message says it quite clearly.
You are attempting to access a field in your database that is not there.
I have books.xml file which contains author name and book titles. I am using the following code snippet to query books.xml.
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr
= xpath.compile("//book[author= 'Larry Niven']/title/text()");
Now instead of directly putting the name in the query if I want to pass it while the program is running as a String variable how to do it. Just putting the string variable name is not working!
The problem here is when you have an author like the infamous Larry "Basher" O'Niven.
In this case, you will need to escape the variable, as in this naive implementation:
public static String escape(String s) {
Matcher matcher = Pattern.compile("['\"]")
.matcher(s);
StringBuilder buffer = new StringBuilder("concat(");
int start = 0;
while (matcher.find()) {
buffer.append("'")
.append(s.substring(start, matcher.start()))
.append("',");
buffer.append("'".equals(matcher.group()) ? "\"'\"," : "'\"',");
start = matcher.end();
}
if (start == 0) {
return "'" + s + "'";
}
return buffer.append("'")
.append(s.substring(start))
.append("'")
.append(")")
.toString();
}
This can be demonstrated with this code:
String xml =
"<xml><foo bar=\"Larry "Basher" O'Niven\">Ringworm</foo></xml>";
String query =
String.format("//foo[#bar=%s]", escape("Larry \"Basher\" O'Niven"));
System.out.println(query);
String book = XPathFactory.newInstance()
.newXPath()
.evaluate(query, new InputSource(new StringReader(xml)));
System.out.println(query + " > " + book);
You can in fact use both custom functions and variables in XPath -but a quick hack might be more productive for many uses.
Below is some code I developed as a learning tool for our students. It lets you do this:
// create some variable we want to use in the xpath
xPathVariableAndFunctionResolver.newVariable("myNamespace", "id", "xs:string", "l2"); // myNamespace is declared in the namespace context with prefix 'my'
// create an XPath expression
String expression = "//did:Component[#id=$my:id]"; // variable $namespace:name
XPathExpression findComponents = xPathFunctionAndVariableOperator.compile(expression);
// execute the XPath expression against the document
NodeList statements = (NodeList)findComponents.evaluate(document, XPathConstants.NODESET);
And much the same with XPath functions. The code, first a wrapper for the normal XPath evalutation:
public class XPathOperator {
protected XPath xPath;
protected XPathFactory xPathFactory;
private Hashtable<String, XPathExpression> compiled = new Hashtable<String, XPathExpression>();
protected void initFactory() throws XPathFactoryConfigurationException {
xPathFactory = XPathFactory.newInstance(XPathConstants.DOM_OBJECT_MODEL);
}
protected void initXPath(NamespaceContext context) {
xPath = xPathFactory.newXPath();
xPath.setNamespaceContext(context);
}
public XPathOperator(NamespaceContext context) throws XPathFactoryConfigurationException {
initFactory();
initXPath(context);
}
public Object evaluate(Document document, String expression, QName value) throws XPathExpressionException {
// create an XPath expression - http://www.zvon.org/xxl/XPathTutorial/General/examples.html
XPathExpression findStatements = compile(expression);
// execute the XPath expression against the document
return (NodeList)findStatements.evaluate(document, value);
}
public XPathExpression compile(String expression) throws XPathExpressionException {
if(compiled.containsKey(expression)) {
return (XPathExpression) compiled.get(expression);
}
XPathExpression xpath = xPath.compile(expression);
System.out.println("Compiled XPath " + expression);
compiled.put(expression, xpath);
return xpath;
}
}
Then we add the concept of custom variables and functions, of course with namespaces:
public class XPathFunctionAndVariableOperator extends XPathOperator {
public XPathFunctionAndVariableOperator(NamespaceContext context, XPathVariableResolver xPathVariableResolver, XPathFunctionResolver xPathFunctionResolver) throws XPathFactoryConfigurationException {
super(context);
xPath.setXPathVariableResolver(xPathVariableResolver);
xPath.setXPathFunctionResolver(xPathFunctionResolver);
}
}
Which would not be much fun without the variable and function resolvers:
public class XPathVariableAndFunctionResolver implements XPathVariableResolver, XPathFunctionResolver {
private Hashtable functions = new Hashtable();
private Hashtable variables = new Hashtable();
private SchemaDVFactory factory = SchemaDVFactory.getInstance();
public XPathFunction resolveFunction(QName functionName, int arity) {
Hashtable table = (Hashtable)functions.get(functionName.getNamespaceURI());
if(table != null) {
XPathFunction function = (XPathFunction)table.get(functionName.getLocalPart());
if(function == null) {
throw new RuntimeException("Function " + functionName.getLocalPart() + " does not exist in namespace " + functionName.getNamespaceURI() + "!");
}
System.out.println("Resolved function " + functionName + " with " + arity + " argument(s)");
return function;
}
throw new RuntimeException("Function namespace " + functionName.getNamespaceURI() + " does not exist!");
}
/**
*
* Adds a variable using namespace and name, primitive type and default value
*
* #param namespace
* #param name
* #param datatype one of the built-in XML datatypes
* #param value
* #throws InvalidDatatypeValueException if value is not of correct datatype
*/
#SuppressWarnings("unchecked")
public void newVariable(String namespace, String name, String datatype, String value) throws InvalidDatatypeValueException {
int index = datatype.indexOf(":");
if(index != -1) {
datatype = datatype.substring(index+1);
}
XSSimpleType builtInType = factory.getBuiltInType(datatype);
if(builtInType == null) {
throw new RuntimeException("Null type for " + datatype);
}
ValidationState validationState = new ValidationState();
ValidatedInfo validatedInfo = new ValidatedInfo();
builtInType.validate(value, validationState, validatedInfo);
System.out.println("Defined variable " + name + " as " + datatype + " with value " + value);
Hashtable table;
if(!variables.containsKey(namespace)) {
table = new Hashtable();
variables.put(namespace, table);
} else {
table = (Hashtable)variables.get(namespace);
}
table.put(name, new Object[]{validatedInfo, builtInType});
}
public void newVariableValue(String namespace, String name, String value) throws InvalidDatatypeValueException {
ValidationState validationState = new ValidationState();
Hashtable table;
if(!variables.containsKey(namespace)) {
throw new RuntimeException("Unknown variable namespace " + namespace);
} else {
table = (Hashtable)variables.get(namespace);
}
Object[] bundle = (Object[])table.get(name);
ValidatedInfo validatedInfo = (ValidatedInfo)bundle[0];
XSSimpleType builtInType = (XSSimpleType)bundle[1];
builtInType.validate(value, validationState, validatedInfo); // direct reference transfer of value
System.out.println("Assigned value " + validatedInfo.normalizedValue + " to variable " + name);
}
public Object resolveVariable(QName variableName) {
Hashtable table;
if(!variables.containsKey(variableName.getNamespaceURI())) {
throw new RuntimeException("Unknown variable namespace " + variableName.getNamespaceURI());
} else {
table = (Hashtable)variables.get(variableName.getNamespaceURI());
}
Object[] bundle = (Object[])table.get(variableName.getLocalPart());
if(bundle != null) {
ValidatedInfo var = (ValidatedInfo)bundle[0];
if(var != null) {
switch(var.actualValueType) { // some types omitted, customize your own
case XSConstants.INTEGER_DT:
case XSConstants.DECIMAL_DT:
case XSConstants.INT_DT:
case XSConstants.LONG_DT:
case XSConstants.SHORT_DT:
case XSConstants.BYTE_DT:
case XSConstants.UNSIGNEDBYTE_DT:
case XSConstants.UNSIGNEDINT_DT:
case XSConstants.UNSIGNEDLONG_DT:
case XSConstants.UNSIGNEDSHORT_DT:
return new Integer(var.normalizedValue);
case XSConstants.DATE_DT:
case XSConstants.DATETIME_DT:
case XSConstants.GDAY_DT:
case XSConstants.GMONTH_DT:
case XSConstants.GMONTHDAY_DT:
case XSConstants.GYEAR_DT:
case XSConstants.GYEARMONTH_DT:
case XSConstants.DURATION_DT:
case XSConstants.TIME_DT:
return new Date(var.normalizedValue);
case XSConstants.FLOAT_DT:
return new Float(Float.parseFloat(var.normalizedValue));
case XSConstants.DOUBLE_DT:
return new Double(Double.parseDouble(var.normalizedValue));
case XSConstants.STRING_DT:
case XSConstants.QNAME_DT:
return var.normalizedValue;
default:
throw new RuntimeException("Unknown datatype " + var.actualValueType + " for variable " + variableName + " in namespace " + variableName.getNamespaceURI());
}
}
}
throw new RuntimeException("Could not resolve value " + variableName + " in namespace " + variableName.getNamespaceURI());
}
public void addFunction(String namespace, String name, XPathFunction function) {
Hashtable table;
if(!functions.containsKey(namespace)) {
table = new Hashtable();
functions.put(namespace, table);
} else {
table = (Hashtable)functions.get(namespace);
}
table.put(name, function);
}
}
The functions obviously cannot be contained within the above, since typically running custom code (i.e. the whole point is that you write your own class), so go with something like
public abstract class XPathFunctionImpl implements XPathFunction {
/**
* This function is called by the XPath expression as it implements the interface XPathFunction
*/
protected int numberArguments;
public Object evaluate(List args) throws XPathFunctionException {
if(args.size() == numberArguments) {
return evaluateImpl(args);
}
throw new RuntimeException("Illegal number of arguments for " + this);
}
public abstract Object evaluateImpl(List args) throws XPathFunctionException;
}
And then the implement/subclass your own logic in evaluateImpl(..) somehow.
This sure makes the String appending seem quite ... attractive ;) Note: This code is several years old and there might exist a better way of doing all this.
If you want a ready-made implementation you can use commons JXPath which supports declaration of variables:
http://commons.apache.org/jxpath/users-guide.html#Variables
String rawXPath = "//book[author= '" + larrysName + "']/title/text()";
or
String rawXPath = String.format("//book[author= '%s']/title/text()", larrysName);
where larrysName is a variable of type String coming from somewhere.