Why can't I use the delete function of SQLiteDatabase on Android - android-sqlite

I'm trying to use the delete function of SQLiteDataBase to delete my data, but it always shows me Unfortunately.
This is my method:
private void del(){
String id = editId.getText().toString();
SQLiteDatabase db = dbhelper.getWritableDatabase();
db.delete(TABLE_NAME, _ID + "=" + id, null);
cleanEditText();
}
However, if I use db.execSQL("DELETE from friends"); instead of the delete function, it works, and deletes all the data.
How can I make the delete function work?
The LogCat say the following:
11-29 23:55:02.597: E/AndroidRuntime(29207): FATAL EXCEPTION: main
11-29 23:55:02.597: E/AndroidRuntime(29207): android.database.sqlite.SQLiteException: no such column: Adam: , while compiling: DELETE FROM friends WHERE _id=Adam
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.database.sqlite.SQLiteStatement.acquireAndLock(SQLiteStatement.java:266)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:88)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.database.sqlite.SQLiteDatabase.delete(SQLiteDatabase.java:1747)
11-29 23:55:02.597: E/AndroidRuntime(29207): at com.tonycube.demo.SQLiteDemoActivity.del(SQLiteDemoActivity.java:163)
11-29 23:55:02.597: E/AndroidRuntime(29207): at com.tonycube.demo.SQLiteDemoActivity.onClick(SQLiteDemoActivity.java:86)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.view.View.performClick(View.java:3574)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.view.View$PerformClick.run(View.java:14293)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.os.Handler.handleCallback(Handler.java:605)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.os.Handler.dispatchMessage(Handler.java:92)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.os.Looper.loop(Looper.java:210)
11-29 23:55:02.597: E/AndroidRuntime(29207): at android.app.ActivityThread.main(ActivityThread.java:4441)
11-29 23:55:02.597: E/AndroidRuntime(29207): at java.lang.reflect.Method.invokeNative(Native Method)
11-29 23:55:02.597: E/AndroidRuntime(29207): at java.lang.reflect.Method.invoke(Method.java:511)
11-29 23:55:02.597: E/AndroidRuntime(29207): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
11-29 23:55:02.597: E/AndroidRuntime(29207): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
11-29 23:55:02.597: E/AndroidRuntime(29207): at dalvik.system.NativeStart.main(Native Method)
This is the Helper:
public class DBHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "demo.db";
private final static int DATABASE_VERSION = 1;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
final String INIT_TABLE = "CREATE TABLE " + TABLE_NAME + " (" +
_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
NAME + " CHAR, " +
TEL + " CHAR, " +
EMAIL + " CHAR);";
db.execSQL(INIT_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
Then, this is my click function:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAdd:
add();
break;
case R.id.btnDel:
del();
break;
case R.id.btnUpdate:
update();
break;
default:
break;
}
show();
showInList();
}
The result will be this.
http://i.imgur.com/Y2TEf.png

"I'm trying to use the delete function of SQLiteDataBase to delete my data, but it always show me" -- always shows you what? What error (if any) do you get when you run your code?
Here's an example of using delete:
db.delete(TABLE_NAME, _ID + " = ?", new String[] { Integer.toString(id) });
You should always used parameterised queries to help mitigate SQL injection attacks.
You say db.execSQL("DELETE from friends"); works but this is a completely different query and doesn't select by ID -- perhaps your _ID constant is wrong.

Replace
db.delete(TABLE_NAME, _ID + "=" + id, null);
with the following line
db.delete(TABLE_NAME, _ID + "=" + "'"+id+"'", null);
Let me know the result

Related

Hibernate, postgres CTE and native SQL query mapping ARRAY[]::BYTEA[] with addScalar

I am trying to execute the following common table expression as a native SQL query in hibernate. Although this is a CTE starting with "WITH" clause, I have seen other examples where this was working with native SQL. I am executing this query on a table called node with the following 2 field
#Id
#Type(type = "uuid-binary")
#Column(name="ID", unique = true, nullable=false)
protected UUID id;
#Type(type = "uuid-binary")
#Column(name="PARENT_ID", nullable=true)
private UUID parentId;
This query has been taken from the official PostgreSQL wiki from here
and just modified a little bit i.e. i have removed the restriction
"WHERE parent_id IS NULL".
If I execute this query in pgAdmin4, then I get a success and I know it works as it should. i.e. I get the expected output that look like this:
Notice the type of the second column called ancestors is "bytea[]" (Not to be confused with byte[]).
It seems that I am not able to map this i.e. i thing that the problem is the mapping of the array of bytea i.e. " ARRAY[]::BYTEA[]" and the following
.addScalar("ancestors")
Session session = getSessionFactory().openSession();
session.beginTransaction();
String sql_query =
" WITH RECURSIVE tree AS ("
+ " SELECT id, ARRAY[]::BYTEA[] AS ancestors"
+ " FROM node "
+ " UNION ALL"
+ " SELECT node.id, tree.ancestors || node.parent_id"
+ " FROM node, tree"
+ " WHERE node.parent_id = tree.id"
+ " ) SELECT * FROM tree WHERE decode(:Argument1, 'hex') = ANY(tree.ancestors)"
;
Query<Object[]> query = session.createNativeQuery(sql_query)
.addScalar("id", org.hibernate.type.StandardBasicTypes.BINARY.INSTANCE)
.addScalar("ancestors")
;
String nodeIdHex = UUIDOperations.uuidToHex(node.getID() );
query.setParameter("Argument1", nodeIdHex, org.hibernate.type.StringType.INSTANCE);
List<Object[]> objectCollection = (List<Object[]>) query.list();
session.getTransaction().commit();
session.close();
return objectCollection;
When i execute this i get the following error :
Hibernate: WITH RECURSIVE tree AS ( SELECT id, ARRAY[]:BYTEA[] AS ancestors FROM node UNION ALL SELECT node.id, tree.ancestors || node.parent_id FROM node, tree WHERE node.parent_id = tree.id ) SELECT * FROM tree decode(?, 'hex') = ANY(tree.ancestors)
2018-12-11 09:11:38.200 WARN pc --- [ main] o.h.e.j.s.SqlExceptionHelper : SQL Error: 0, SQLState: 42601
2018-12-11 09:11:38.202 ERROR pc --- [ main] o.h.e.j.s.SqlExceptionHelper : ERROR: syntax error at or near ":"
Position: 45
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1514)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy238.findAllSubNodesRecursively(Unknown Source)
....
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
....
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
....
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505)
... 58 more
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
Position: 45
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:106)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60)
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.hibernate5.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:230)
at org.springframework.orm.hibernate5.HibernateExceptionTranslator.convertHibernateAccessException(HibernateExceptionTranslator.java:102)
at org.springframework.orm.hibernate5.HibernateExceptionTranslator.translateExceptionIfPossible(HibernateExceptionTranslator.java:77)
....
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
... 49 more
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
Position: 45
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:106)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60)
... 72 more
I suspect that the problem is in the " ARRAY[]::BYTEA[]" mapping but i just have no idea how to map that correctly.
I have tried to create a special user type that will help me map that but it does not seem help me in this case or i have implemented it the wrong way.
Type byteArrayType = new CustomType(new ByteaArrayUserType());
Query<Object[]> query = session.createNativeQuery(sql_query)
.addScalar("id", org.hibernate.type.StandardBasicTypes.BINARY.INSTANCE)
.addScalar("ancestors", byteArrayType)
;
here is the mapping class below:
import java.io.Serializable;
import java.sql.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
public class ByteaArrayUserType implements UserType {
protected static final int[] SQL_TYPES = { Types.ARRAY };
#Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return this.deepCopy(cached);
}
#Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
return (byte[][]) this.deepCopy(value);
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == null) {
return y == null;
}
return x.equals(y);
}
#Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
#Override
public boolean isMutable() {
return true;
}
#Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
#Override
public Class<byte[][]> returnedClass() {
return byte[][].class;
}
#Override
public int[] sqlTypes() {
return new int[] { Types.ARRAY };
}
#Override
public Object nullSafeGet(
ResultSet resultSet,
String[] names,
SharedSessionContractImplementor session, Object owner
)throws HibernateException, SQLException {
if (resultSet.wasNull()) {
return null;
}
if (resultSet.getArray(names[0]) == null) {
return new byte[0];
}
Array array = resultSet.getArray(names[0]);
byte[][] javaArray = (byte[][]) array.getArray();
return javaArray;
}
#Override
public void nullSafeSet(PreparedStatement statement,
Object value, int index,
SharedSessionContractImplementor session
)throws HibernateException, SQLException {
Connection connection = statement.getConnection();
if (value == null) {
statement.setNull(index, SQL_TYPES[0]);
} else {
byte[][] castObject = (byte[][]) value;
Array array = connection.createArrayOf("byte", castObject);
statement.setArray(index, array);
}
}
}
The reason i believe this has to do with the ARRAY[]::BYTEA is because if i simplify the query to something simple as :
SELECT id, ARRAY[]::BYTEA[] AS ancestors
FROM node
I still get the same error , however this time it says
[ main] o.h.e.j.s.SqlExceptionHelper : SQL Error: 0, SQLState: 42601
[ main] o.h.e.j.s.SqlExceptionHelper : ERROR: syntax error at or near ":"
Position: 20
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
so what is wrong with that ":" colon. This time only the position is different i.e. 20 instead of 45 on the previous exception

Unit testing Spring Boot MultiPartFile PDF Upload Rest Controller using MockMvc

Good day Pals,
I am new to Springboot and having problems testing my PDF uploader spring controller endpoint.
The rest endpoint works when tested via postman, but not in my unit test.
I am using a spring boot application with the following key components and problem is:
org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:251)
2016-06-09 19:03:03,359 4198 [main] DEBUG o.s.t.c.w.ServletTestExecutionListener - Resetting RequestContextHolder for test context [DefaultTestContext#646be2c3 testClass = PDFUploadControllerTest, testInstance = x.y.z.rest.controller.PDFUploadControllerTest#2b44d6d0, testMethod = testHandleFileUpload#PDFUploadControllerTest, testException = java.lang.AssertionError: Status expected:<200> but was:<400>, mergedContextConfiguration = [WebMergedContextConfiguration#797badd3 testClass = PDFUploadControllerTest, locations = '{}', classes = '{class x.y.z.rest.PresentationConfiguration, class x.y.z.rest.controller.MockDomainConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]].
java.lang.AssertionError: Status
Expected :200
Actual :400
Please, see some code and stacktrace below ... I have been banging my head on the wall all day, debugging using all online references but NO luck ....
Your help will be most appreciated. Thanks
Application
#EnableAutoConfiguration()
public class Application {
public static void main(String[] args) {
SpringApplication.run(
new Object[]{
DomainConfiguration.class,
PresentationConfiguration.class
},
args);
}
}
DomainConfiguration
#Configuration
#EnableAutoConfiguration()
#ComponentScan(basePackages = {
"x.y.z.rest.domain",
"x.y.z.rest.service",
"x.y.z.rest.util",
"x.y.z.rest.repository"
})
public class DomainConfiguration {
#Autowired(required = true)
public void configeJackson(ObjectMapper jackson2ObjectMapper) {
jackson2ObjectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
PresentationConfiguration
#Configuration
#ComponentScan(basePackages = {"x.y.z.rest.controller"})
public class PresentationConfiguration {
}
## RestController
#RestController
public class PDFUploadController {
#Autowired
public void setUploadService(UploadService uploadService) {
this.uploadService = uploadService;
}
private UploadService uploadService;
#RequestMapping(value="/upload", method=RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public #ResponseBody String handleFileUpload(
#RequestParam("file") MultipartFile file,#RequestParam String a,#RequestParam String b,#RequestParam String c, #RequestParam String d,#RequestParam String e) throws Exception{
java.io.InputStream inputStream =null;
if (!file.isEmpty() && checkContentType(file.getContentType())) {
try {
DBObject dbObject = new BasicDBObject();
//populate DBObject
inputStream = file.getInputStream();
uploadService.uploadFile(inputStream,file.getOriginalFilename(),file.getContentType(),dbObject);
return "success";
} catch (Exception e) {
return "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage();
}
finally {
if(inputStream!=null) {
inputStream.close();
}
}
} else {
return "You failed to upload " + file.getOriginalFilename() + " as it is an invalid file.";
}
}
}
##### Unit Test Class for Controller
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = {
PresentationConfiguration.class,
MockDomainConfiguration.class})
#WebAppConfiguration
public class PDFUploadControllerTest {
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
private UploadService uploadService;
private MockMvc mockMvc;
#Autowired
private ObjectMapper mapper;
private RestDocumentationResultHandler document;
#Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.build();
}
#After
public void resetMocks() {
reset(uploadService);
}
#Test
public void testHandleFileUpload() throws Exception {
FileInputStream fileInputStream = null;
MockMultipartFile mockMultipartFile = null;
try {
File file = new File("//Users//olatom//Desktop//testFile4Upload.pdf");
// create FileInputStream object
fileInputStream = new FileInputStream(file);
System.out.println("# File input stream for PDF : " + fileInputStream);
byte fileContent[] = new byte[(int) file.length()];
// Reads up to certain bytes of data from this input stream into an array of bytes.
fileInputStream.read(fileContent);
//create string from byte array
String pdfContent = new String(fileContent);
//mockMultipartFile = new MockMultipartFile("upload", file.getName(), "multipart/form-data", fileInputStream);
mockMultipartFile = new MockMultipartFile("file", fileInputStream);
HashMap<String, String> contentTypeParams = new HashMap<String, String>();
contentTypeParams.put("boundary", "265001916915724");
MediaType mediaType = new MediaType("multipart", "form-data", contentTypeParams);
//mockMvc.perform(fileUpload("/upload")
// .file(mockMultipartFile)
// .param("a", "1234").param("b", "PX1234").param("c", "100").param("d", "120")
// .contentType(MediaType.MULTIPART_FORM_DATA))
// .andExpect(status().isOk());
// mockMvc.perform(fileUpload("/upload")).andExpect(status().isOk());
//mockMvc.perform(fileUpload("/upload").file(mockMultipartFile)).andExpect(status().isOk());
mockMvc.perform(
fileUpload("/upload")
.content(mockMultipartFile.getBytes())
.param("a", "1234").param("b", "PX1234").param("c", "100").param("d", "120")
.contentType(mediaType)
)
.andExpect(status().isOk());
} catch (FileNotFoundException e) {
System.out.println("File not found" + e);
} catch (IOException ioe) {
System.out.println("IO Exception while reading file " + ioe);
} catch (Exception exc) {
} finally {
// close the streams using close method
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
}
}
####### MockDomainConfiguration #####
/**
* Create Mockito mocks for the service classes.
* For this to work the #EnableAutoConfiguration annotation below also has to exclude JPA Autoconfiguration.
*/
#Configuration
#EnableAutoConfiguration()
public class MockDomainConfiguration {
#Bean
public UploadService mockUploadService() {
return mock(UploadService.class);
}
}
## MY ERROR
When I run the junit test in Intellij I get the following error:
2016-06-09 19:03:03,331 4170 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - DispatcherServlet with name '' processing POST request for [/upload]
2016-06-09 19:03:03,342 4181 [main] DEBUG o.s.b.a.e.m.EndpointHandlerMapping - Looking up handler method for path /upload
2016-06-09 19:03:03,343 4182 [main] DEBUG o.s.b.a.e.m.EndpointHandlerMapping - Did not find handler method for [/upload]
2016-06-09 19:03:03,343 4182 [main] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /upload
2016-06-09 19:03:03,344 4183 [main] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Returning handler method [public java.lang.String x.y.z.rest.controller.PDFUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception]
2016-06-09 19:03:03,344 4183 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'PDFUploadController'
2016-06-09 19:03:03,352 4191 [main] DEBUG o.s.w.s.m.m.a.ServletInvocableHandlerMethod - Error resolving argument [0] [type=org.springframework.web.multipart.MultipartFile]
HandlerMethod details:
Controller [x.y.z.rest.controller.PDFUploadController]
Method [public java.lang.String x.y.z.rest.controller.PDFUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception]
org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:251)
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:96)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:99)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:870)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at x.y.z.rest.controller.PDFUploadControllerTest.testHandleFileUpload(PDFUploadControllerTest.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
2016-06-09 19:03:03,353 4192 [main] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception from handler [public java.lang.String x.y.z.rest.controller.PDFUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
2016-06-09 19:03:03,354 4193 [main] DEBUG o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolving exception from handler [public java.lang.String x.y.z.rest.controller.PDFUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
2016-06-09 19:03:03,354 4193 [main] DEBUG o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolving exception from handler [public java.lang.String x.y.z.rest.controller.PDFUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
2016-06-09 19:03:03,355 4194 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Null ModelAndView returned to DispatcherServlet with name '': assuming HandlerAdapter completed request handling
2016-06-09 19:03:03,355 4194 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Successfully completed request
2016-06-09 19:03:03,359 4198 [main] DEBUG o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext#646be2c3 testClass = PDFUploadControllerTest, testInstance = x.y.z.rest.controller.PDFUploadControllerTest#2b44d6d0, testMethod = testHandleFileUpload#PDFUploadControllerTest, testException = java.lang.AssertionError: Status expected:<200> but was:<400>, mergedContextConfiguration = [WebMergedContextConfiguration#797badd3 testClass = PDFUploadControllerTest, locations = '{}', classes = '{class x.y.z.rest.PresentationConfiguration, class x.y.z.rest.controller.MockDomainConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null], method annotated with #DirtiesContext [false] with mode [null].
2016-06-09 19:03:03,359 4198 [main] DEBUG o.s.t.c.w.ServletTestExecutionListener - Resetting RequestContextHolder for test context [DefaultTestContext#646be2c3 testClass = PDFUploadControllerTest, testInstance = x.y.z.rest.controller.PDFUploadControllerTest#2b44d6d0, testMethod = testHandleFileUpload#PDFUploadControllerTest, testException = java.lang.AssertionError: Status expected:<200> but was:<400>, mergedContextConfiguration = [WebMergedContextConfiguration#797badd3 testClass = PDFUploadControllerTest, locations = '{}', classes = '{class x.y.z.rest.PresentationConfiguration, class x.y.z.rest.controller.MockDomainConfiguration}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]].
java.lang.AssertionError: Status
Expected :200
Actual :400
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:655)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at x.y.z.rest.controller.PDFloadControllerTest.testHandleFileUpload(PDFUploadControllerTest.java:146)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Your help will be most appreciated.

Error in SQLite db creation and Inserting data

When trying to create a database with a single table I encountered the following error. Not able to point the issue causing the error. Although have created the table column, still responding with no such column
Logcat data:
03-16 12:08:35.954 1249-1249/com.example.bharathduraiswamy.comboedittext E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo
{com.example.bharathduraiswamy.comboedittext/com.example.bharathduraiswamy.comboedittext.AddSupplier}: android.database.sqlite.SQLiteException: no such
column: _id (code 1): , while compiling: SELECT _id, supplier_name, supplier_contact_number, supplier_address FROM SUPPLIER
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2313)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5336)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: no such column: _id (code 1): , while compiling: SELECT _id, supplier_name, supplier_contact_number,
supplier_address FROM SUPPLIER
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:886)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:497)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
at com.example.bharathduraiswamy.comboedittext.VivzDatabaseAdapter.getAllRows(VivzDatabaseAdapter.java:78)
at com.example.bharathduraiswamy.comboedittext.AddSupplier.populateListView(AddSupplier.java:271)
at com.example.bharathduraiswamy.comboedittext.AddSupplier.onCreate(AddSupplier.java:71)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
            at android.app.ActivityThread.access$600(ActivityThread.java:156)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:5336)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)
MainActivity.java data:
DBAdapter myDb;
AutoCompleteTextView customerName;
EditText customerNumber, customerAddress;
customerName = (AutoCompleteTextView) findViewById(R.id.addCustomerName);
customerNumber = (EditText) findViewById(R.id.addCustomerNumber);
customerAddress = (EditText) findViewById(R.id.addCustomerAddress);
openDB();
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
public void addCustomer(MenuItem item) {
if (!TextUtils.isEmpty(customerName.getText().toString()) &&
!TextUtils.isEmpty(customerNumber.getText().toString())) {
myDb.insertCustomer(
customerName.getText().toString(),
customerNumber.getText().toString(),
customerAddress.getText().toString());}
}
DbHelper data: (Edited)
package com.example.bharathduraiswamy.comboedittext;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
/////////////////
//START : CUSTOMER DATA
/////////////////
// Field Names:
public static final String CUSTOMER_ROWID = "customer_id";
public static final String CUSTOMER_NAME = "customer_name";
public static final String CUSTOMER_CONTACT_NUMBER = "customer_contact_number";
public static final String CUSTOMER_CONTACT_ADDRESS = "customer_contact_address";
public static final String[] CUSTOMER_KEYS = new String[] {CUSTOMER_ROWID, CUSTOMER_NAME, CUSTOMER_CONTACT_NUMBER, CUSTOMER_CONTACT_ADDRESS};
// Column Numbers for each Field Name:
public static final int COL_CUSTOMER_ROWID = 0;
public static final int COL_CUSTOMER_NAME = 1;
public static final int COL_CUSTOMER_CONTACT_NUMBER = 2;
public static final int COL_CUSTOMER_CONTACT_ADDRESS = 3;
// DataBase info:
public static final String DATABASE_NAME = "dbLeder";
public static final String CUSTOMER_TABLE = "CUSTOMERLIST";
public static final int DATABASE_VERSION = 3; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + CUSTOMER_TABLE
+ " ("
+ CUSTOMER_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ CUSTOMER_NAME + " VARCHAR(255), "
+ CUSTOMER_CONTACT_NUMBER + " VARCHAR(255), "
+ CUSTOMER_CONTACT_ADDRESS + " VARCHAR(255));";
public final Context context;
public DatabaseHelper myDBHelper;
public SQLiteDatabase db;
/////////////////
//END : CUSTOMER DATA
/////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
//onClick Method for Check - addCustomer
public long insertCustomer(String custName, String custContactNumber, String custContactAddress) {
ContentValues initialValues = new ContentValues();
initialValues.put(CUSTOMER_NAME, custName);
initialValues.put(CUSTOMER_CONTACT_NUMBER, custContactNumber);
initialValues.put(CUSTOMER_CONTACT_ADDRESS, custContactAddress);
// Insert the data into the database.
return db.insert(CUSTOMER_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = CUSTOMER_ROWID + "=" + rowId;
return db.delete(CUSTOMER_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(CUSTOMER_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, CUSTOMER_TABLE, CUSTOMER_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = CUSTOMER_ROWID + "=" + rowId;
Cursor c = db.query(true, CUSTOMER_TABLE, CUSTOMER_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String custName, String custContactNumber, String custContactAddress) {
String where = CUSTOMER_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(CUSTOMER_NAME, custName);
newValues.put(CUSTOMER_CONTACT_NUMBER, custContactNumber);
newValues.put(CUSTOMER_CONTACT_ADDRESS, custContactAddress);
// Insert it into the database.
return db.update(CUSTOMER_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS" + CUSTOMER_TABLE);
onCreate(_db); // Recreates the onCreate()
}
}
}
Nothing strikes me as wrong in your code.
Did you increment the DATABASE_VERSION field to make sure your onUpgradee() method is called ?
If you did that already, maybe try to uninstall the app from your device. That will erase the existing database. If this work, that would probably mean that your onUpgrade() method does not work.
Good luck.
EDIT : Check your onUpgrade() method. You don't have a space after "EXISTS". You need one otherwise the query won't work.
The new Logcat shows that you are having a different error. I think what it tells you is that you should have at least one column called "_id" in your table.
This is sort of a must have when working in SQLite on Android because some of the convenience methods look for this column name.
If you search StackOverflow, you will find some answers tell you that you can Alias this row and don't have to change the design of your table, but I'd say go ahead and change your design.

play.exceptions.JavaExecutionException: Cannot get the object #Id for an object in WAS8

this is my code in controller and here i save my object
public static void newNdsf(Integer cprNumber,String fstCode,Date startDate,
Double amount, Date endDate, String isActive, String userCreated, String msg){
Beneficiary beneficiary = new Beneficiary();
beneficiary.beneficiaryPK = (new BeneficiaryPK(cprNumber, fstCode, startDate));
beneficiary.dateCreated = (new Date());
beneficiary.userCreated = userCreated;
beneficiary.amount = new BigDecimal(amount);
beneficiary.dateLastUpdate = (new Date());
beneficiary.userLastUpdate = userCreated;
beneficiary.endDate = endDate;
if(isActive.charAt(0) == Constants.IN_ACTIVE || isActive.charAt(0) == Constants.ACTIVE)
beneficiary.isActive = isActive.charAt(0);
else
System.out.println("in valid is Active value entered in service");
beneficiary.save();
int count = new CRSServices().savePersonDetails(cprNumber);
System.out.println("Person Data saved from Service : " + count);
msg = msg.concat("Entered Successfully");
renderText(msg);
}
in Models iam overriding the save method to catch some exception
#Override
public <T extends JPABase> T save()
{
long startTs = System.currentTimeMillis();
if (endDate != null && beneficiaryPK != null && beneficiaryPK.startDate != null && endDate.before(beneficiaryPK.startDate)){
throw new RuntimeException("startdate_after_end_date");
}
Object result = super.save();
logger.debug("Save Took: {} " , System.currentTimeMillis() - startTs);
return (T) result;
}
this code is working on WAS6
but when i use it in WAS8
it gives me this exception
#6d2l11n03
Internal Server Error (500)
Execution exception (In /app/models/Beneficiary.java around line 221)
ValidationException occured : error during validation of
play.exceptions.JavaExecutionException: error during validation of <unknown>
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:290)
at play.server.ServletWrapper$ServletInvocation.execute(ServletWrapper.java:476)
at play.Invoker$Invocation.run(Invoker.java:187)
at play.server.ServletWrapper$ServletInvocation.run(ServletWrapper.java:467)
at play.Invoker.invokeInThread(Invoker.java:61)
at play.server.ServletWrapper.service(ServletWrapper.java:117)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1214)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:774)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:456)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1027)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:895)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:195)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:452)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:511)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:305)
at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:83)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1659)
Caused by: javax.validation.ValidationException: error during validation of <unknown>
at org.apache.bval.jsr303.ClassValidator.unrecoverableValidationError(ClassValidator.java:633)
at org.apache.bval.jsr303.ClassValidator.validate(ClassValidator.java:161)
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:113)
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:71)
at org.hibernate.action.EntityInsertAction.preInsert(EntityInsertAction.java:177)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:72)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:267)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:259)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:178)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:345)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:791)
at play.db.jpa.JPABase._save(JPABase.java:47)
at play.db.jpa.GenericModel.save(GenericModel.java:187)
at models.Beneficiary.save(Beneficiary.java:221)
at controllers.NdsfService.newNdsf(NdsfService.java:189)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:413)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:408)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:182)
... 27 more
Caused by: play.exceptions.UnexpectedException: Unexpected Error
at play.db.jpa.JPAPlugin$JPAModelLoader.keyValue(JPAPlugin.java:491)
at play.db.jpa.JPABase._key(JPABase.java:96)
at play.db.jpa.JPABase.hashCode(JPABase.java:226)
at org.apache.bval.jsr303.GraphBeanIdentity.hashCode(GraphBeanIdentity.java:123)
at java.util.HashMap.getEntry(HashMap.java:510)
at java.util.HashMap.get(HashMap.java:498)
at org.apache.bval.jsr303.GroupValidationContextImpl.collectValidated(GroupValidationContextImpl.java:133)
at org.apache.bval.jsr303.ClassValidator.validateBeanNet(ClassValidator.java:421)
at org.apache.bval.jsr303.ClassValidator.validate(ClassValidator.java:141)
... 45 more
Caused by: play.exceptions.UnexpectedException: Cannot get the object #Id for an object of type class models.Beneficiary
at play.db.jpa.JPAPlugin$JPAModelLoader.keyField(JPAPlugin.java:511)
at play.db.jpa.JPAPlugin$JPAModelLoader.keyValue(JPAPlugin.java:489)
... 53 more
if anyone can help!!!
Figured this out
in my object
before i have only
#EmbeddedId
public BeneficiaryPK beneficiaryPK;
and this works in WAS 6 but not in WAS 8
so now i added #Id and both annotations are working in WAS 8
#EmbeddedId
#Id
public BeneficiaryPK beneficiaryPK;
hope this is helpfull

SQLite Database Force Closing due to Syntax Error

I am trying to insert into the SQLite Database but it keeps on force closing every time I run my program on the emulator. I think it has something to due with my syntax of my database creation but I have triple checked it and can't find my error. The only other thing I can think of is if I have to add something to the manifest to properly run a SQlite database.
Below is my code for my helper class.
public class dbhelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "swimmers";
public static final String TABLE_SWIMMERS = "sfd table";
public static final String C_ID = "id";
public static final String NAME = "name";
public static final String TEAM = "team";
public static final String NOTES = "notes";
public static final int VERSION = 1;
public dbhelper(Context context)
{
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate (SQLiteDatabase db)
{
String createdb = "create table " + TABLE_SWIMMERS + "(" + C_ID + " integer primary key autoincrement, " + NAME + " text, " + TEAM + " text, " + NOTES + " text); ";
db.execSQL(createdb);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("drop table " + TABLE_SWIMMERS);
onCreate(db);
}
//add new entry
void addSwimmer(Swimmer swimmer){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME, swimmer.getname());
values.put(TEAM, swimmer.getteam());
values.put(NOTES, swimmer.getnotes());
db.insert(TABLE_SWIMMERS, null, values);
db.close();
}
//Getting single swimmer
Swimmer getSwimmer(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_SWIMMERS, new String[] { C_ID, NAME, TEAM, NOTES}, C_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor !=null)
cursor.moveToFirst();
Swimmer swimmer = new Swimmer (Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), null);
return swimmer;
}
public int updateSwimmer(Swimmer swimmer){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME, swimmer.getname());
values.put(TEAM, swimmer.getteam());
values.put(NOTES, swimmer.getnotes());
return db.update(TABLE_SWIMMERS, values, C_ID + " = ?", new String[] { String.valueOf(swimmer.getID()) });
}
//delete single contact
public void deleteSwimmer(Swimmer swimmer){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_SWIMMERS, C_ID + " = ?", new String[] { String.valueOf(swimmer.getID()) });
db.close();
}
//get contacts count
public int getSwimmersCount(){
String countQuery = "SELECT * FROM " + TABLE_SWIMMERS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
Below is my Swimmer class that I made and I am trying to insert a Swimmer into the database.
public class Swimmer {
//private variables
int _id;
String _name;
String _team;
String _notes;
public Swimmer(int id, String name, String team, String notes){
this._id = id;
this._name = name;
this._team = team;
this._notes = notes;
}
public Swimmer(String name, String team, String notes){
this._name = name;
this._team = team;
this._notes = notes;
}
public int getID(){
return this._id;
}
public void setID(int id){
this._id = id;
}
public String getname(){
return this._name;
}
public void setname(String name){
this._name = name;
}
public String getteam(){
return this._team;
}
public void setteam(String team){
this._team = team;
}
public String getnotes(){
return this._notes;
}
public void setnotes(String notes){
this._notes = notes;
}
}
Here is my code to open and insert into the database.
public class CreateNewSwimmerProfile extends Activity {
private dbhelper db;
private final String TAG = "Create New Profile";
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_sfdmain, menu);
return true;
}
#Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.i("createProfileActivity", "Intent Text");
setContentView(R.layout.createprofile);
Intent createprofileintent = getIntent();
db = new dbhelper(this);
}
public void btn_CLICK_addswimmer (View w)
{
Log.i("Insert: ", "Inserting ..");
String name,team,notes;
EditText nameIn = (EditText) findViewById(R.id.editText_name);
EditText teamIn = (EditText) findViewById(R.id.editText_team);
EditText notesIn = (EditText) findViewById(R.id.editText_notes);
name = nameIn.getText().toString();
team = teamIn.getText().toString();
notes = notesIn.getText().toString();
Swimmer test = new Swimmer(name, team, notes);
db.addSwimmer(test);
}
public void btn_CLICK_cancel (View b)
{
Log.i(TAG, "start create new profile activity");
Intent intent = new Intent(this, SFDMain.class);
startActivity(intent);
}
}
And here are my errors when I try to insert the swimmer.
11-27 08:58:36.150: E/AndroidRuntime(643): FATAL EXCEPTION: main
11-27 08:58:36.150: E/AndroidRuntime(643): java.lang.IllegalStateException: Could not execute method of the activity
11-27 08:58:36.150: E/AndroidRuntime(643): at android.view.View$1.onClick(View.java:3591)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.view.View.performClick(View.java:4084)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.view.View$PerformClick.run(View.java:16966)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.os.Handler.handleCallback(Handler.java:615)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.os.Handler.dispatchMessage(Handler.java:92)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.os.Looper.loop(Looper.java:137)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-27 08:58:36.150: E/AndroidRuntime(643): at java.lang.reflect.Method.invokeNative(Native Method)
11-27 08:58:36.150: E/AndroidRuntime(643): at java.lang.reflect.Method.invoke(Method.java:511)
11-27 08:58:36.150: E/AndroidRuntime(643): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-27 08:58:36.150: E/AndroidRuntime(643): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-27 08:58:36.150: E/AndroidRuntime(643): at dalvik.system.NativeStart.main(Native Method)
11-27 08:58:36.150: E/AndroidRuntime(643): Caused by: java.lang.reflect.InvocationTargetException
11-27 08:58:36.150: E/AndroidRuntime(643): at java.lang.reflect.Method.invokeNative(Native Method)
11-27 08:58:36.150: E/AndroidRuntime(643): at java.lang.reflect.Method.invoke(Method.java:511)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.view.View$1.onClick(View.java:3586)
11-27 08:58:36.150: E/AndroidRuntime(643): ... 11 more
11-27 08:58:36.150: E/AndroidRuntime(643): Caused by: android.database.sqlite.SQLiteException: near "table": syntax error (code 1): , while compiling: create table sfd table(id integer primary key autoincrement, name text, team text, notes text);
11-27 08:58:36.150: E/AndroidRuntime(643): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
11-27 08:58:36.150: E/AndroidRuntime(643): at com.sfd.swimming.feedback.display.system.dbhelper.onCreate(dbhelper.java:35)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
11-27 08:58:36.150: E/AndroidRuntime(643): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
11-27 08:58:36.150: E/AndroidRuntime(643): at com.sfd.swimming.feedback.display.system.dbhelper.addSwimmer(dbhelper.java:48)
11-27 08:58:36.150: E/AndroidRuntime(643): at com.sfd.swimming.feedback.display.system.CreateNewSwimmerProfile.btn_CLICK_addswimmer(CreateNewSwimmerProfile.java:50)
11-27 08:58:36.150: E/AndroidRuntime(643): ... 14 more
11-27 08:58:36.420: D/dalvikvm(643): GC_CONCURRENT freed 207K, 4% free 8241K/8519K, paused 22ms+33ms, total 304ms
11-27 08:58:38.680: I/Process(643): Sending signal. PID: 643 SIG: 9
ANY help is greatly appreciated!!
table is a Keyword for SQLite. Try to change your variable TABLE_SWIMMERS from TABLE_SWIMMERS = "sfd table"; to TABLE_SWIMMERS = "sfd"; and it will work.