I am using streams to paginate a list of offers in spring boot.
Here's my Page :
#Table(name = "PAGE")
#Data
#NoArgsConstructor
public class Page <T>{
// current page
private int pageNumber;
// number of results displayed on each page
private int resultsPerPage;
// total number of results
private int totalResults;
// items to display on the current page
private List<T> items;
public Page(int pageNumber, int resultsPerPage, int totalResults, List<T> items) {
this.pageNumber = pageNumber;
this.resultsPerPage = resultsPerPage;
this.totalResults = totalResults;
this.items = items;
}
}
Here's my service :
#Override
public Page<JobOfferEntity> getAllJobOffersByPage( List<JobOfferEntity> jobOffers, int pageNumber, int resultsPerPage) {
int skipCount = (pageNumber - 1) * resultsPerPage;
int totalResult = jobOffers.size();
List<JobOfferEntity> jobOfferPage = jobOffers
.stream()
.skip(skipCount)
.limit(resultsPerPage)
.collect(Collectors.toList());
Page<JobOfferEntity> page = new Page<JobOfferEntity> (pageNumber, resultsPerPage, totalResult, jobOfferPage);
return page;
}
Here's my controller :
#GetMapping (path = "/pagination")
public Page<JobOfferEntity> getAllByPage(#RequestParam (defaultValue = "1") int pageNumber,
#RequestParam (defaultValue = "8") int resultsPerPage)
{
List<JobOfferEntity> jobOffers = this.jobOfferRepository.findAll() ;
return this.jobOfferService.getAllJobOffersByPage(jobOffers, pageNumber, resultsPerPage);
}
Yet I keep getting this error : java.lang.NullPointerException: null
Anyone can tell why ??
Here's the complete stacktrace :
java.lang.NullPointerException\r\n\tat com.polaris.controllers.recruitment.jobOffer.JobOfferController.getAllByPage(JobOfferController.java:54)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:626)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:733)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter.doFilter(KeycloakAuthenticatedActionsFilter.java:57)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.keycloak.adapters.springsecurity.filter.KeycloakSecurityContextRequestFilter.doFilter(KeycloakSecurityContextRequestFilter.java:61)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter.doFilter(KeycloakPreAuthActionsFilter.java:96)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter.successfulAuthentication(KeycloakAuthenticationProcessingFilter.java:214)\r\n\tat org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:240)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat com.talan.polaris.components.CORSFilter.doFilterInternal(CORSFilter.java:45)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)\r\n\tat org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)\r\n\tat org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter.doFilter(KeycloakAuthenticatedActionsFilter.java:74)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.keycloak.adapters.springsecurity.filter.KeycloakSecurityContextRequestFilter.doFilter(KeycloakSecurityContextRequestFilter.java:92)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter.successfulAuthentication(KeycloakAuthenticationProcessingFilter.java:214)\r\n\tat org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:240)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter.doFilter(KeycloakPreAuthActionsFilter.java:96)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)\r\n\tat org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)\r\n\tat org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)\r\n\tat org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)\r\n\tat org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)\r\n\tat org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\r\n\tat org.keycloak.adapters.tomcat.AbstractAuthenticatedActionsValve.invoke(AbstractAuthenticatedActionsValve.java:67)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)\r\n\tat org.keycloak.adapters.tomcat.AbstractKeycloakAuthenticatorValve.invoke(AbstractKeycloakAuthenticatorValve.java:181)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.base/java.lang.Thread.run(Thread.java:834)\r\n
I am also using keycloak so yeah
The problem was fixed. I only had to add #Autowired to the jobOfferRepositiry in the controller:
#Autowired
private JobOfferRepository jobOfferRepository;
Related
I couldn't find why I am getting this exception. Please help me to find it.
I am using the IBM DB2/AS400 DB engine. I have checked the column names in the database with the names I declared in the java class. They are the same. After this exception, the app is not stopping but it's continued further. somewhere in the app, I am trying to save using the repository (repository.save(dailyErrorVO);) and there it's waiting for a long time and going into some deadlock.
public interface DailyErrorRepository
extends JpaRepository<DailyErrorVO, String>, CrudRepository<DailyErrorVO, String> {
}
#Entity
#Table(name = "T_DAILY_ERROR")
public class DailyErrorVO implements Comparable<DailyErrorVO>, Cloneable, Serializable{
private static final long serialVersionUID = 4917078316183458138L;
private Date EFF_DATE;
private String ERRCODE;
private String ERROR_MESSAGE;
private String EXCEPTION_MESSAGE;
private String EXTRNL_POI;
private String IMPACT_AREA;
#Column(name="LAST_MOD_TIME_DT", nullable = false)
private Timestamp LAST_MOD_TIME_DT;
#Id
#Column(nullable = true)
private String MEMBER_ID;
private String PAY_SEQ;
private String PROG_ID;
#Column(name="PROGRAM", nullable = false)
private String PROGRAM = CommonProperties.PROGRAM_NAME;
#Column(name="RUN_DATE", nullable = false)
private Date RUN_DATE;
private String SQLCODE;
private String SSN;
private String TABLE_NM;
public Date getEFF_DATE() {
return EFF_DATE;
}
public void setEFF_DATE(Date eFF_DATE) {
EFF_DATE = eFF_DATE;
}
public String getERRCODE() {
return ERRCODE;
}
public void setERRCODE(String eRRCODE) {
ERRCODE = eRRCODE;
}
public String getERROR_MESSAGE() {
return ERROR_MESSAGE;
}
public void setERROR_MESSAGE(String eRROR_MESSAGE) {
ERROR_MESSAGE = eRROR_MESSAGE;
}
public String getEXCEPTION_MESSAGE() {
return EXCEPTION_MESSAGE;
}
public void setEXCEPTION_MESSAGE(String eXCEPTION_MESSAGE) {
EXCEPTION_MESSAGE = eXCEPTION_MESSAGE;
}
public String getEXTRNL_POI() {
return EXTRNL_POI;
}
public void setEXTRNL_POI(String eXTRNL_POI) {
EXTRNL_POI = eXTRNL_POI;
}
public String getIMPACT_AREA() {
return IMPACT_AREA;
}
public void setIMPACT_AREA(String iMPACT_AREA) {
IMPACT_AREA = iMPACT_AREA;
}
public Timestamp getLAST_MOD_TIME_DT() {
return LAST_MOD_TIME_DT;
}
public void setLAST_MOD_TIME_DT(Timestamp lAST_MOD_TIME_DT) {
LAST_MOD_TIME_DT = lAST_MOD_TIME_DT;
}
public String getMEMBER_ID() {
return MEMBER_ID;
}
public void setMEMBER_ID(String mEMBER_ID) {
MEMBER_ID = mEMBER_ID;
}
public String getPAY_SEQ() {
return PAY_SEQ;
}
public void setPAY_SEQ(String pAY_SEQ) {
PAY_SEQ = pAY_SEQ;
}
public String getPROG_ID() {
return PROG_ID;
}
public void setPROG_ID(String pROG_ID) {
PROG_ID = pROG_ID;
}
public String getPROGRAM() {
return PROGRAM;
}
public void setPROGRAM(String pROGRAM) {
PROGRAM = pROGRAM;
}
public Date getRUN_DATE() {
return RUN_DATE;
}
public void setRUN_DATE(Date rUN_DATE) {
RUN_DATE = rUN_DATE;
}
public String getSQLCODE() {
return SQLCODE;
}
public void setSQLCODE(String sQLCODE) {
SQLCODE = sQLCODE;
}
public String getSSN() {
return SSN;
}
public void setSSN(String sSN) {
SSN = sSN;
}
public String getTABLE_NM() {
return TABLE_NM;
}
public void setTABLE_NM(String tABLE_NM) {
TABLE_NM = tABLE_NM;
}
#Override
public String toString() {
return "TDailyErrorVO [EFF_DATE=" + EFF_DATE + ", ERRCODE=" + ERRCODE + ", ERROR_MESSAGE=" + ERROR_MESSAGE
+ ", EXCEPTION_MESSAGE=" + EXCEPTION_MESSAGE + ", EXTRNL_POI=" + EXTRNL_POI + ", IMPACT_AREA="
+ IMPACT_AREA + ", LAST_MOD_TIME_DT=" + LAST_MOD_TIME_DT + ", MEMBER_ID=" + MEMBER_ID + ", PAY_SEQ="
+ PAY_SEQ + ", PROG_ID=" + PROG_ID + ", PROGRAM=" + PROGRAM + ", RUN_DATE=" + RUN_DATE + ", SQLCODE="
+ SQLCODE + ", SSN=" + SSN + ", TABLE_NM=" + TABLE_NM + "]";
}
#Override
public int compareTo(DailyErrorVO o) {
return 0;
}
}
com.ibm.as400.access.AS400JDBCSQLSyntaxErrorException: An undefined column name was detected.
at com.ibm.as400.access.JDError.createSQLExceptionSubClass(JDError.java:897) ~[jt400-jdk8-9.5.jar:JTOpen 9.5]
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:421) ~[jt400-jdk8-9.5.jar:JTOpen 9.5]
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:397) ~[jt400-jdk8-9.5.jar:JTOpen 9.5]
at com.ibm.as400.access.JDServerRow.findField(JDServerRow.java:519) ~[jt400-jdk8-9.5.jar:JTOpen 9.5]
at com.ibm.as400.access.AS400JDBCResultSet.findColumn(AS400JDBCResultSet.java:575) ~[jt400-jdk8-9.5.jar:JTOpen 9.5]
at com.ibm.as400.access.AS400JDBCResultSet.getString(AS400JDBCResultSet.java:3424) ~[jt400-jdk8-9.5.jar:JTOpen 9.5]
at com.zaxxer.hikari.pool.HikariProxyResultSet.getString(HikariProxyResultSet.java) ~[HikariCP-3.4.5.jar:?]
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.resultSetSchemaName(SequenceInformationExtractorLegacyImpl.java:124) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:53) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.sequenceInformationList(JdbcEnvironmentImpl.java:403) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:268) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1224) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1255) [hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) [spring-orm-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) [spring-orm-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) [spring-orm-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853) [spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1790) [spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) [spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) [spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) [spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$148/0000000000000000.getObject(Unknown Source) [spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) [spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) [spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) [spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109) [spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) [spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) [spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:405) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at com.benefeds.batch.ABWReversalFileValidationStarter.main(ABWReversalFileValidationStarter.java:9) [classes/:?]
According to the stack trace that you posted, Hibernate is unable to determine the current value of some sequence which happens at boot time. Maybe you configured the wrong dialect or the dialect has a bug. Please share the dialect that you use and the Hibernate version, as well as the exact database name and version. Chances are, you can simply subclass a dialect and fix the bug yourself.
I am new in writing PACT test cases. I have a very simple scenario, a microservice is running on dev server which return true or false based on the Path Variable (its a GET call). How to write a test case that generate PACT? How to set up a broker server for pacts to get publish? For now i am only concerned about the consumer end.
For a start i have written following code?
OrderMsConsumerTest
#ExtendWith(PactConsumerTestExt.class)
#PactTestFor(providerName = "orderms-provider", port = "8888")
public class OrderMsConsumerTest {
private static final String USER_SUBSCRIPTION_URL = "/api/order/order/subscription?userId=1&userSubscriptionId=1";
private static final String SERVER_URL = "ACTUAL_SERVER_ADDRESS";
#BeforeEach
public void setUp(MockServer mockServer) {
Assertions.assertTrue(mockServer != null);
}
#Pact(state = "user order subscription" , provider = "orderms-provider", consumer="orderms-consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {
Map headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=UTF-8");
return builder
.given("Order User Subscription")
.uponReceiving("user id and subscription id")
.path("/api/order/order/subscription?userId=2968&userSubscriptionId=51230")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body("true")
.toPact();
}
#Test
#PactTestFor(pactMethod = "orderUserSubscription")
void shouldPassResponseRecivedForGivenUserIdAndSubscriptionId() throws IOException {
HttpResponse httpResponse = Request.Get(SERVER_URL + USER_SUBSCRIPTION_URL)
.execute().returnResponse();
Assertions.assertTrue(httpResponse.getStatusLine().getStatusCode() == 200);
}
}
When i write click in intellij and run the test i get the following exception as a result?
java.lang.UnsupportedOperationException: No method annotated with #Pact was found on test class OrderMsConsumerTest for provider 'orderms-provider'
at au.com.dius.pact.consumer.junit5.PactConsumerTestExt.lookupPact(PactConsumerTestExt.kt:146)
at au.com.dius.pact.consumer.junit5.PactConsumerTestExt.beforeEach(PactConsumerTestExt.kt:83)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachCallbacks$1(TestMethodTestDescriptor.java:151)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$5(TestMethodTestDescriptor.java:187)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:187)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachCallbacks(TestMethodTestDescriptor.java:150)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:129)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Suppressed: kotlin.TypeCastException: null cannot be cast to non-null type au.com.dius.pact.consumer.junit5.JUnit5MockServerSupport
at au.com.dius.pact.consumer.junit5.PactConsumerTestExt.afterEach(PactConsumerTestExt.kt:162)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAfterEachCallbacks$11(TestMethodTestDescriptor.java:245)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$12(TestMethodTestDescriptor.java:256)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$13(TestMethodTestDescriptor.java:256)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAllAfterMethodsOrCallbacks(TestMethodTestDescriptor.java:255)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAfterEachCallbacks(TestMethodTestDescriptor.java:244)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:141)
... 41 more
I am bit confused here #PactTestFor(providerName = "orderms-provider", port = "8888") i have no broker set up for now so it would automatically run a mock server with a provider name orderms-provider at port 8888? And do i need a run a application on port 8888 and make the actual call and get the test passed? How make test case run as part of my maven build?
#ExtendWith(PactConsumerTestExt.class)
#PactTestFor(providerName = "orderms-provider", port = "8888")
public class OrderMsConsumerTest {
private static final String USER_SUBSCRIPTION_URL = "/api/order/order/subscription?userId=1&userSubscriptionId=1";
private static final String SERVER_URL = "ACTUAL_SERVER_ADDRESS";
#BeforeEach
public void setUp(MockServer mockServer) {
Assertions.assertTrue(mockServer != null);
}
#Pact(state = "user order subscription" , provider = "orderms-provider", consumer="orderms-consumer")
public RequestResponsePact orderUserSubscription(PactDslWithProvider builder) {
Map headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=UTF-8");
return builder
.given("Order User Subscription")
.uponReceiving("user id and subscription id")
.path("/api/order/order/subscription?userId=2968&userSubscriptionId=51230")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body("true")
.toPact();
}
#Test
#PactTestFor(pactMethod = "orderUserSubscription")
void shouldPassResponseRecivedForGivenUserIdAndSubscriptionId() throws IOException {
HttpResponse httpResponse = Request.Get(SERVER_URL + USER_SUBSCRIPTION_URL)
.execute().returnResponse();
Assertions.assertTrue(httpResponse.getStatusLine().getStatusCode() == 200);
}
}
I have existing ListView which filled with some information from SQLite database. I want to store and retrieve images from SQLite database then show it in ListView. I had already build Databasehandler and Adapter for that. But, the problem is when I run my project it get uknown error (code 0): Native could not create new byte[].
-Logcat
11-10 00:32:24.797: E/AndroidRuntime(2295): FATAL EXCEPTION: main
11-10 00:32:24.797: E/AndroidRuntime(2295): android.database.sqlite.SQLiteException: unknown error (code 0): Native could not create new byte[]
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.database.CursorWindow.nativeGetBlob(Native Method)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.database.CursorWindow.getBlob(CursorWindow.java:399)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.database.AbstractWindowedCursor.getBlob(AbstractWindowedCursor.java:45)
11-10 00:32:24.797: E/AndroidRuntime(2295): at kre.db.DatabaseHandler.getAllCard(DatabaseHandler.java:275)
11-10 00:32:24.797: E/AndroidRuntime(2295): at com.example.kre.MyWallet.onActivityCreated(MyWallet.java:58)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:848)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.app.BackStackRecord.run(BackStackRecord.java:635)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.os.Handler.handleCallback(Handler.java:615)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.os.Handler.dispatchMessage(Handler.java:92)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.os.Looper.loop(Looper.java:137)
11-10 00:32:24.797: E/AndroidRuntime(2295): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-10 00:32:24.797: E/AndroidRuntime(2295): at java.lang.reflect.Method.invokeNative(Native Method)
11-10 00:32:24.797: E/AndroidRuntime(2295): at java.lang.reflect.Method.invoke(Method.java:511)
11-10 00:32:24.797: E/AndroidRuntime(2295): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-10 00:32:24.797: E/AndroidRuntime(2295): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-10 00:32:24.797: E/AndroidRuntime(2295): at dalvik.system.NativeStart.main(Native Method)
-MyWallet
package com.example.kre;
import kre.adapter.ListAdapterMyWallet;
import kre.db.DatabaseHandler;
import kre.model.Card;
import kre.model.Category;
import com.example.login.R;
import android.os.Bundle;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
public class MyWallet extends Fragment {
public MyWallet(){}
ArrayList<Card> cardList = new ArrayList<Card>();
List<Category> listCategory;
ListView listView;
ListAdapterMyWallet adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mywallet, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = (ListView) getView().findViewById(R.id.list);
DatabaseHandler db = new DatabaseHandler(getActivity());
/*listCategory = db.getAllCategory();
if(listCategory.size()==0)
{
db.addCategory(new Category("Food"));
db.addCategory(new Category("Shopping"));
db.addCategory(new Category("Health"));
listCategory = db.getAllCategory();
}*/
List<Card> cards = db.getAllCard();
if(cards.size() == 0)
{
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte imageInByte[] = stream.toByteArray();
db.addCard(new Card(imageInByte, "Pizza Hut", 0));
}
for(Card cd : cards){
String log = "ID: " + cd.getId() + "Image: " + cd.getCardImg() + "Name: " + cd.getCardName()
+ "Card Type Id: " + cd.getCardTypeId();
Log.d("Result: ", log);
cardList.add(cd);
}
adapter = new ListAdapterMyWallet(getActivity(), R.layout.list_row_mywallet, cardList);
listView.setAdapter(adapter);
}
}
-ListAdapterMyWallet
package kre.adapter;
import kre.model.Card;
import com.example.login.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
public class ListAdapterMyWallet extends ArrayAdapter<Card> {
Context context;
int layoutResourceId;
ArrayList<Card> cardItems = new ArrayList<Card>();
public ListAdapterMyWallet(Context context, int layoutResourceId ,ArrayList<Card> cardItems) {
super(context, layoutResourceId, cardItems);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.cardItems = cardItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardHolder holder = null;
if(row==null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CardHolder();
holder.txtCardName = (TextView)row.findViewById(R.id.card_name);
holder.imgIcon = (ImageView)row.findViewById(R.id.card_img);
row.setTag(holder);
}else
{
holder = (CardHolder)row.getTag();
}
Card card = cardItems.get(position);
holder.txtCardName.setText(card.getCardName());
//convert byte to bitmap take from contact class
byte[] outImage=card.getCardImg();
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
return row;
}
static class CardHolder
{
ImageView imgIcon;
TextView txtCardName;
}
}
-DatabaseHandler
package kre.db;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import kre.model.Profile;
import kre.model.Card;
import kre.model.Category;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
//Database name
private static final String DATABASE_NAME = "KRE";
//Table names
private static final String TABLE_PROFILE = "profile";
private static final String TABLE_CATEGORY = "category";
private static final String TABLE_CARD = "card";
//Common column names
private static final String KEY_ID = "id";
private static final String KEY_CREATED_AT ="created_at";
//Profile column names
private static final String KEY_IMG = "img";
private static final String KEY_EMAIL = "email";
private static final String KEY_NAME = "name";
private static final String KEY_PHONE = "phone";
//Category column names
private static final String KEY_CATEGORY ="category";
//Card column names
private static final String KEY_CARD_IMG = "card_img";
private static final String KEY_CARD_NAME = "card_name";
private static final String KEY_CARD_TYPE_ID ="card_type_id";
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Category table create statement
private static final String CREATE_TABLE_CATEGORY = "CREATE TABLE " + TABLE_CATEGORY
+ "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_CATEGORY + " TEXT,"
+ KEY_CREATED_AT + " DATETIME" + ")";
//Card table create statement
private static final String CREATE_TABLE_CARD = "CREATE TABLE " + TABLE_CARD
+ "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_CARD_IMG + " BLOB," +
KEY_CARD_NAME + " TEXT," + KEY_CARD_TYPE_ID + " INTEGER," + KEY_CREATED_AT + " DATETIME" + ")";
//Profile table create statement
private static final String CREATE_TABLE_PROFILE = "CREATE TABLE " + TABLE_PROFILE +
"(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_IMG + " BLOB," +
KEY_EMAIL + " TEXT," + KEY_NAME + " TEXT," + KEY_PHONE + " TEXT" + ")";
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_TABLE_CATEGORY);
db.execSQL(CREATE_TABLE_PROFILE);
db.execSQL(CREATE_TABLE_CARD);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVesion, int newVersion){
db.execSQL("DROP TABLE IF EXIST " + TABLE_PROFILE);
db.execSQL("DROP TABLE IF EXIST " + TABLE_CATEGORY);
db.execSQL("DROP TABLE IF EXIST " + TABLE_CARD);
onCreate(db);
}
//Profile
public void addProfile(Profile profile){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMG, profile.getImg());
values.put(KEY_EMAIL, profile.getEmail());
values.put(KEY_NAME, profile.getName());
values.put(KEY_PHONE, profile.getPhone());
db.insert(TABLE_PROFILE, null, values);
db.close();
}
public Profile getProfile(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_PROFILE, new String[]{KEY_ID, KEY_IMG, KEY_EMAIL, KEY_NAME, KEY_PHONE},
KEY_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if(cursor!=null)
cursor.moveToFirst();
Profile profile = new Profile(Integer.parseInt(cursor.getString(0)), cursor.getBlob(1),
cursor.getString(2), cursor.getString(3), cursor.getString(4));
return profile;
}
public List<Profile> getAllProfile(){
List<Profile> profileList = new ArrayList<Profile>();
String selectQuery = "SELECT * FROM " + TABLE_PROFILE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst())
{
do{
Profile profile = new Profile();
profile.setID(Integer.parseInt(cursor.getString(0)));
profile.setImg(cursor.getBlob(1));
profile.setEmail(cursor.getString(2));
profile.setName(cursor.getString(3));
profile.setPhone(cursor.getString(4));
profileList.add(profile);
}while(cursor.moveToNext());
}
return profileList;
}
public int getProfileCounts(){
int count = 0;
String countQuery = "SELECT * FROM " + TABLE_PROFILE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
count = cursor.getCount();
cursor.close();
}
return count;
}
public int updateProfile(Profile profile){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMG, profile.getImg());
values.put(KEY_EMAIL, profile.getEmail());
values.put(KEY_NAME, profile.getName());
values.put(KEY_PHONE, profile.getPhone());
return db.update(TABLE_PROFILE, values, KEY_ID + " = ?", new String[]{String.valueOf(profile.getID())});
}
public void updatePicture(byte[] imageInByte, int id){
SQLiteDatabase db = this.getWritableDatabase();
String strSQL = "UPDATE profile SET img = '"+imageInByte+"' WHERE id = " +id+"";
db.execSQL(strSQL);
db.close();
}
public void deleteProfile(Profile profile){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PROFILE, KEY_ID + "=?", new String[]{String.valueOf(profile.getID())});
db.close();
}
//Category
public void addCategory(Category category){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY, category.getCategory());
values.put(KEY_CREATED_AT, getDateTime());
db.insert(TABLE_CATEGORY, null, values);
db.close();
}
public Category getCategory(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CATEGORY, new String[] { KEY_ID,
KEY_CATEGORY}, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Category category = new Category(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return contact
return category;
}
public List<Category> getAllCategory(){
List<Category> categoryList = new ArrayList<Category>();
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Category category = new Category();
category.setId(Integer.parseInt(cursor.getString(0)));
category.setCategory(cursor.getString(1));
category.setCreatedAt(cursor.getString(2));
categoryList.add(category);
}while(cursor.moveToNext());
}
return categoryList;
}
public int updateCategory(Category category) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY, category.getCategory());
return db.update(TABLE_CATEGORY, values, KEY_ID + " = ?", new String[] { String.valueOf(category.getId())});
}
public void deleteCategory(Category category) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CATEGORY, KEY_ID + " = ?", new String[] { String.valueOf(category.getId())});
db.close();
}
public int getCategoryCount(){
String countQuery = "SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
//Card
public void addCard(Card card){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CARD_IMG, card.getCardImg());
values.put(KEY_CARD_NAME, card.getCardName());
values.put(KEY_CARD_TYPE_ID, Integer.toString(card.getCardTypeId()));
values.put(KEY_CREATED_AT, getDateTime());
db.insert(TABLE_CARD, null, values);
db.close();
}
public List<Card> getAllCardWithCategory(int categoryId){
List<Card> cardList = new ArrayList<Card>();
String selectQuery = "SELECT * FROM " + TABLE_CARD + " WHERE " + KEY_CARD_TYPE_ID + "=" + String.valueOf(categoryId) + ";";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Card card = new Card();
card.setCardId(Integer.parseInt(cursor.getString(0)));
card.setCardImg(cursor.getBlob(1));
card.setCardName(cursor.getString(2));
card.setCardTypeId(Integer.parseInt(cursor.getString(3)));
card.setCreatedAt(cursor.getString(4));
cardList.add(card);
}while(cursor.moveToLast());
}
return cardList;
}
public List<Card> getAllCard(){
List<Card> cardList = new ArrayList<Card>();
String selectQuery = "SELECT * FROM " + TABLE_CARD;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Card card = new Card();
card.setCardId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))));
card.setCardImg(cursor.getBlob(cursor.getColumnIndex(KEY_CARD_IMG)));
card.setCardName(cursor.getString(cursor.getColumnIndex(KEY_CARD_NAME)));
card.setCardTypeId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_CARD_TYPE_ID))));
card.setCreatedAt(cursor.getString(cursor.getColumnIndex(KEY_CREATED_AT)));
cardList.add(card);
}while(cursor.moveToLast());
}
return cardList;
}
//getDateTime function
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
}
when I delete db.addCard method, my program work, but i can't add images into database. Another fragment of my program is to store profile picture and information, whether this is due to lack of memory?
Sorry for my bad English, any help is welcome! Thanks
I am developing my first Android app and had built in mostly based on research. When I try to login my user I get the android.os.NetworkOnMainThreadException error. I have read online that Async should be used to make sure that this error doesn't occur but I have no idea how to do that.
Below is all my code.
My User Login Form Activity:
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.finecalc.library.DatabaseHandler;
import com.finecalc.library.UserFunctions;
public class UserLogin extends Activity {
Button userlogin;
Button back;
Button login;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.inputemail);
inputPassword = (EditText) findViewById(R.id.inputpassword);
login = (Button) findViewById(R.id.login);
//Button register = (Button) findViewById(R.id.register);
back =(Button)findViewById(R.id.back);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
//if (json.getString(KEY_SUCCESS) != null) {
if(json != null && !(json).isNull(KEY_SUCCESS)){
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
DatabaseHandler
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "androidlta_api";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
}
UserFunctions
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class UserFunctions {
private JSONParser jsonParser;
// Testing in localhost using LAMP
private static String loginURL = "http://127.0.0.1/android_api/index.php";
private static String registerURL = "http://127.0.0.1/android_api/index.php";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* #param name
* #param email
* #param password
* */
public JSONObject registerUser(String name, String licencenumber, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("licencenumber",licencenumber));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
JSONParser
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
// Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
My AndroidManifest also includes:
<uses-permission android:name="android.permission.INTERNET" />.
Below is my error:
08-02 04:39:23.410: D/(2642): HostConnection::get() New Host Connection established 0xb97a3b90, tid 2642
08-02 04:39:23.480: W/EGL_emulation(2642): eglSurfaceAttrib not implemented
08-02 04:39:23.480: D/OpenGLRenderer(2642): Enabling debug mode 0
08-02 04:39:29.150: W/EGL_emulation(2642): eglSurfaceAttrib not implemented
08-02 04:39:33.650: D/InputEventConsistencyVerifier(2642): KeyEvent: ACTION_UP but key was not down.
08-02 04:39:33.650: D/InputEventConsistencyVerifier(2642): in android.widget.EditText{b1fa92d8 VFED..CL .F...... 0,82-240,118 #7f07001c app:id/inputpassword}
08-02 04:39:33.650: D/InputEventConsistencyVerifier(2642): 0: sent at 7133734000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=7133734, downTime=7133655, deviceId=0, source=0x101 }
08-02 04:39:38.231: D/dalvikvm(2642): GC_FOR_ALLOC freed 177K, 8% free 2964K/3192K, paused 21ms, total 24ms
08-02 04:39:38.321: D/AndroidRuntime(2642): Shutting down VM
08-02 04:39:38.321: W/dalvikvm(2642): threadid=1: thread exiting with uncaught exception (group=0xb1cd3b20)
08-02 04:39:38.331: E/AndroidRuntime(2642): FATAL EXCEPTION: main
08-02 04:39:38.331: E/AndroidRuntime(2642): Process: com.finecalc.ltafinecalculator, PID: 2642
08-02 04:39:38.331: E/AndroidRuntime(2642): android.os.NetworkOnMainThreadException
08-02 04:39:38.331: E/AndroidRuntime(2642): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
08-02 04:39:38.331: E/AndroidRuntime(2642): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-02 04:39:38.331: E/AndroidRuntime(2642): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
08-02 04:39:38.331: E/AndroidRuntime(2642): at libcore.io.IoBridge.connect(IoBridge.java:112)
08-02 04:39:38.331: E/AndroidRuntime(2642): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-02 04:39:38.331: E/AndroidRuntime(2642): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-02 04:39:38.331: E/AndroidRuntime(2642): at java.net.Socket.connect(Socket.java:843)
08-02 04:39:38.331: E/AndroidRuntime(2642): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
08-02 04:39:38.331: E/AndroidRuntime(2642): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
08-02 04:39:38.331: E/AndroidRuntime(2642): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-02 04:39:38.331: E/AndroidRuntime(2642): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-02 04:39:38.331: E/AndroidRuntime(2642): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-02 04:39:38.331: E/AndroidRuntime(2642): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-02 04:39:38.331: E/AndroidRuntime(2642): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-02 04:39:38.331: E/AndroidRuntime(2642): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-02 04:39:38.331: E/AndroidRuntime(2642): at com.finecalc.library.JSONParser.getJSONFromUrl(JSONParser.java:41)
08-02 04:39:38.331: E/AndroidRuntime(2642): at com.finecalc.library.UserFunctions.loginUser(UserFunctions.java:42)
08-02 04:39:38.331: E/AndroidRuntime(2642): at com.finecalc.ltafinecalculator.UserLogin$1.onClick(UserLogin.java:57)
08-02 04:39:38.331: E/AndroidRuntime(2642): at android.view.View.performClick(View.java:4438)
08-02 04:39:38.331: E/AndroidRuntime(2642): at android.view.View$PerformClick.run(View.java:18422)
08-02 04:39:38.331: E/AndroidRuntime(2642): at android.os.Handler.handleCallback(Handler.java:733)
08-02 04:39:38.331: E/AndroidRuntime(2642): at android.os.Handler.dispatchMessage(Handler.java:95)
08-02 04:39:38.331: E/AndroidRuntime(2642): at android.os.Looper.loop(Looper.java:136)
08-02 04:39:38.331: E/AndroidRuntime(2642): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-02 04:39:38.331: E/AndroidRuntime(2642): at java.lang.reflect.Method.invokeNative(Native Method)
08-02 04:39:38.331: E/AndroidRuntime(2642): at java.lang.reflect.Method.invoke(Method.java:515)
08-02 04:39:38.331: E/AndroidRuntime(2642): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-02 04:39:38.331: E/AndroidRuntime(2642): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-02 04:39:38.331: E/AndroidRuntime(2642): at dalvik.system.NativeStart.main(Native Method)
08-02 04:39:41.111: D/(2670): HostConnection::get() New Host Connection established 0xb97a3cc0, tid 2670
08-02 04:39:41.181: W/EGL_emulation(2670): eglSurfaceAttrib not implemented
08-02 04:39:41.181: D/OpenGLRenderer(2670): Enabling debug mode 0
08-02 04:39:45.771: W/EGL_emulation(2670): eglSurfaceAttrib not implemented
08-02 04:39:48.371: W/EGL_emulation(2670): eglSurfaceAttrib not implemented
08-02 04:39:50.971: D/dalvikvm(2670): GC_FOR_ALLOC freed 123K, 6% free 3018K/3192K, paused 28ms, total 32ms
08-02 04:39:51.581: W/EGL_emulation(2670): eglSurfaceAttrib not implemented
08-02 04:39:51.811: D/dalvikvm(2670): GC_FOR_ALLOC freed 152K, 6% free 3380K/3584K, paused 22ms, total 31ms
08-02 04:40:18.351: W/EGL_emulation(2670): eglSurfaceAttrib not implemented
08-02 04:40:21.741: W/EGL_emulation(2670): eglSurfaceAttrib not implemented
08-02 04:40:23.021: D/AndroidRuntime(2670): Shutting down VM
08-02 04:40:23.021: W/dalvikvm(2670): threadid=1: thread exiting with uncaught exception (group=0xb1cd3b20)
08-02 04:40:23.031: E/AndroidRuntime(2670): FATAL EXCEPTION: main
08-02 04:40:23.031: E/AndroidRuntime(2670): Process: com.finecalc.ltafinecalculator, PID: 2670
08-02 04:40:23.031: E/AndroidRuntime(2670): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.finecalc.ltafinecalculator/com.finecalc.ltafinecalculator.UserRegister}: java.lang.NullPointerException
08-02 04:40:23.031: E/AndroidRuntime(2670): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-02 04:40:23.031: E/AndroidRuntime(2670): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-02 04:40:23.031: E/AndroidRuntime(2670): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-02 04:40:23.031: E/AndroidRuntime(2670): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-02 04:40:23.031: E/AndroidRuntime(2670): at android.os.Handler.dispatchMessage(Handler.java:102)
08-02 04:40:23.031: E/AndroidRuntime(2670): at android.os.Looper.loop(Looper.java:136)
08-02 04:40:23.031: E/AndroidRuntime(2670): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-02 04:40:23.031: E/AndroidRuntime(2670): at java.lang.reflect.Method.invokeNative(Native Method)
08-02 04:40:23.031: E/AndroidRuntime(2670): at java.lang.reflect.Method.invoke(Method.java:515)
08-02 04:40:23.031: E/AndroidRuntime(2670): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-02 04:40:23.031: E/AndroidRuntime(2670): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-02 04:40:23.031: E/AndroidRuntime(2670): at dalvik.system.NativeStart.main(Native Method)
08-02 04:40:23.031: E/AndroidRuntime(2670): Caused by: java.lang.NullPointerException
08-02 04:40:23.031: E/AndroidRuntime(2670): at com.finecalc.ltafinecalculator.UserRegister.onCreate(UserRegister.java:26)
08-02 04:40:23.031: E/AndroidRuntime(2670): at android.app.Activity.performCreate(Activity.java:5231)
08-02 04:40:23.031: E/AndroidRuntime(2670): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-02 04:40:23.031: E/AndroidRuntime(2670): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-02 04:40:23.031: E/AndroidRuntime(2670): ... 11 more
This exception is thrown when application attempts to perform a networking operation in the main thread. Use below code in your onViewCreated to avoid this error else Call your networking operations (getting data from web server) request in thread or Asynch class.
public void onViewCreated(View view, Bundle savedInstanceState)
{
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your codes here
}
}
Try to add this code:
Add this code below the line in you user login activity
setContentView(R.layout.user_login);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Hope this may help you!
Below code used in Kotlin,
minSdkVersion 14
If your minSdkVersion less than 21 from app-level build.gradle then used below one
if (Build.VERSION.SDK_INT > 9) {
val policy = ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
}
minSdkVersion 21
If your minSdkVersion 21 or above from app-level build.gradle then used below one
val policy = ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
use AsyncTask to run long running api call to different thread.
Example Code
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class AsyncExample extends Activity{
private String url="http://www.google.co.in";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiCall();
}
private void apiCall() {
new AsyncCaller().execute();
}
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
}
}
}
I'm playing with Hadoop for the first time, and wrote a MapReducer to take a log file and chunk it down. However, the output is... weird.
It looks like this:
2f09 3133 3134 3838 0a2f 0009 3137 0a2f
0000 1908 efbf bd7b efbf bd44 11ef bfbd
efbf bd2a efbf bdef bfbd 301b 79ef bfbd
5bef bfbd d290 efbf bdef bfbd 5349 efbf
bd5c efbf bd24 32ef bfbd 7bef bfbd 58ef
bfbd efbf bd16 efbf bdef bfbd 20ef bfbd
52ef bfbd 1fd7 ac1b efbf bd21 672b df86
3603 031a 54ef bfbd efbf bd09 310a 2f00
002b efbf bd53 53ef bfbd 2bef bfbd efbf
bd63 6125 efbf bdef bfbd 3c17 024e 4eef
bfbd efbf bd1d 7e72 efbf bd18 efbf bd4b
2332 efbf bdef bfbd 04ef bfbd 1d19 efbf
bd67 5a33 3270 7bef bfbd 75ef bfbd 6def
bfbd 0931 0a2f 0000 46ef bfbd ddb5 efbf
bd4d 62ef bfbd 7751 2048 efbf bdef bfbd
14ef bfbd efbf bdef bfbd 5463 efbf bdef
bfbd 5f12 efbf bdef bfbd 77ef bfbd 5fef
bfbd efbf bdef bfbd 32ef bfbd dd88 efbf
bdd8 b309 310a 2f00 0072 ccbd 0931 0a2f
0000 7457 efbf bdef bfbd 1632 efbf bdef
bfbd 21ef bfbd efbf bdef bfbd 563d 66ef
I did try it with a much smaller file originally, and it came up just fine in readable format. So I'm not entirely sure what the problem is... Has the encoding changed at some point in time while the file was being MapReduced?
I have absolutely no idea, so would appreciate some help to find out what's wrong, and what I can do to fix it, or to prevent it from happening again.
Thanks!
Edit: Added code
Thankfully, it's a nice short file since it's my first one ever... I've removed the imports and stuff to try to make it even shorter.
public class WCSLogParse {
public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private static final Log LOG = LogFactory.getLog(WCSLogParse.class);
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
line = splitToUrl(line);
LOG.info("Line is "+line);
if(line.contains(".")) {
//do nothing
LOG.info("Skipping line");
}
else {
int lastSlash = line.lastIndexOf("/");
line = line.substring(lastSlash);
LOG.info("Command is "+line);
context.write(new Text(line), one);
}
}
private String splitToUrl(String line) {
int subBegin = line.indexOf('/');
int subEnd = line.indexOf(',',subBegin);
if(subBegin == -1 || subEnd == -1) {
return ".";
}
String url = line.substring(subBegin, subEnd);
//handles if it is from a CSV field
if(url.endsWith("\"")) {
url = url.substring(0, (url.length()-1));
}
return url;
}
private String getUrl(String line) {
String[] cols = line.split(",");
return cols[7];
}
};
public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
context.write(key, new IntWritable(sum));
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
System.out.println("the args are "+args.toString());
Job job = new Job(conf, "WCSLogParse");
job.setJarByClass(WCSLogParse.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(Map.class);
job.setCombinerClass(Reduce.class);
job.setReducerClass(Reduce.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.waitForCompletion(true);
}
}
I'm kicking the job off in eclipse with the following arguments:
"/Volumes/Secondary Documents/logs/" "/Volumes/Secondary Documents/logs/output"