I am trying to insert the information from an excel file to mysql, I am using the extension of springbatch excel to read the file but when trying to insert the mysql it gives an error apparently it does not send the information i shared my batch.config
#Configuration
#EnableBatchProcessing
public class SpringBatchConfig {
#Bean
#Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
public Pagare pagare() {
return new Pagare();
}
#Bean
#Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
public ItemProcessor<Pagare, Pagare> itemProcessor() {
return new PagareItemProcessor();
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/pagare");
dataSource.setUsername("root");
dataSource.setPassword("");
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(new ClassPathResource("org/springframework/batch/core/schema-drop-mysql.sql"));
databasePopulator.addScript(new ClassPathResource("org/springframework/batch/core/schema-mysql.sql"));
DatabasePopulatorUtils.execute(databasePopulator, dataSource);
return dataSource;
}
#Bean
public BeanWrapperFieldSetMapper<Pagare> beanWrapperFieldSetMapper() {
BeanWrapperFieldSetMapper<Pagare> fieldSetMapper = new BeanWrapperFieldSetMapper<>();
fieldSetMapper.setPrototypeBeanName("pagare");
return fieldSetMapper;
}
#Bean
ItemReader<Pagare> pagareReader() {
PoiItemReader<Pagare> reader = new PoiItemReader<>();
reader.setResource(new ClassPathResource("pagares.xlsx"));
reader.setRowMapper(excelRowMapper());
return reader;
}
private RowMapper<Pagare> excelRowMapper() {
return new RowMapperImpl();
}
#Bean
public BeanPropertyItemSqlParameterSourceProvider<Pagare> beanPropertyItemSqlParameterSourceProvider() {
return new BeanPropertyItemSqlParameterSourceProvider<>();
}
#Bean
public ItemWriter<Pagare> JdbcBatchItemWriter(DataSource dataSource,
BeanPropertyItemSqlParameterSourceProvider<Pagare> sqlParameterSourceProvider) {
JdbcBatchItemWriter<Pagare> jdbcBatchItemWriter = new JdbcBatchItemWriter<>();
jdbcBatchItemWriter.setDataSource(dataSource);
jdbcBatchItemWriter.setItemSqlParameterSourceProvider(sqlParameterSourceProvider);
jdbcBatchItemWriter.setSql("insert into pagare(operacion,id,contrato,tipo,analista,fechaCargaDocumento,estadoOperacion,fechaCambioEstado) values (:operacion, :id, :contrato, :tipo, :analista, :fechaCargaDocumento, :estadoOperacion, :fechaCambioEstado)");
return jdbcBatchItemWriter;
}
#Bean
public Job jobCsvMysql(JobBuilderFactory jobBuilderFactory, Step step) {
return jobBuilderFactory.get("jobCsvMysql").incrementer(new RunIdIncrementer()).flow(step).end().build();
}
#Bean
public Step step1(StepBuilderFactory stepBuilderFactory,
ItemReader<Pagare> pagareReader, ItemWriter<Pagare> writer, ItemProcessor<Pagare, Pagare> processor) {
return stepBuilderFactory.get("step1").<Pagare, Pagare>chunk(6)
.reader(pagareReader).processor(processor).writer(writer).build();
}
}
org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [insert into pagare(test1,id,test3,test4,test5,test6,test7,test8) values (?, ?, ?, ?, ?, ?, ?, ?)]; Column 'id' cannot be null; nested exception is java.sql.BatchUpdateException: Column 'test2' cannot be null
I tried changing the values of my bd and my model and I have the same result, the reason why I use BeanPropertyItemSqlParameterSourceProvider is because my parameters of the insert are equal to those of my property of my model that I leave below
public class Pagare {
private String operacion;
private String rut;
private String contrato;
private String tipo;
private String analista;
private String fechaCargaDocumento;
private String estadoOperacion;
private String fechaCambioEstado;
public String getOperacion() {
return operacion;
}
public void setOperacion(String operacion) {
this.operacion = operacion;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getAnalista() {
return analista;
}
public void setAnalista(String analista) {
this.analista = analista;
}
public String getFechaCargaDocumento() {
return fechaCargaDocumento;
}
public void setFechaCargaDocumento(String fechaCargaDocumento) {
this.fechaCargaDocumento = fechaCargaDocumento;
}
public String getEstadoOperacion() {
return estadoOperacion;
}
public void setEstadoOperacion(String estadoOperacion) {
this.estadoOperacion = estadoOperacion;
}
public String getFechaCambioEstado() {
return fechaCambioEstado;
}
public void setFechaCambioEstado(String fechaCambioEstado) {
this.fechaCambioEstado = fechaCambioEstado;
}
public String getRut() {
return rut;
}
public void setRut(String rut) {
this.rut = rut;
}
public String getContrato() {
return contrato;
}
public void setContrato(String contrato) {
this.contrato = contrato;
}
#Override
public String toString() {
return "Pagare [operacion=" + operacion + ", rut=" + rut + ", contrato=" + contrato + ",tipo=" + tipo + ",analista=" + analista + ",fechaCargaDocumento=" + fechaCargaDocumento + ",estadoOperacion=" + estadoOperacion + ",fechaCambioEstado=" + fechaCambioEstado + "]";
}
my item processor is this
private static final Logger LOG = LoggerFactory.getLogger(PagareItemProcessor.class);
#Override
public Pagare process(Pagare pagare) throws Exception {
LOG.info("Processing " + pagare);
final String initCapAnalista = pagare.getAnalista().substring(0, 1).toUpperCase()
+ pagare.getAnalista().substring(1);
final String initCapTipo = pagare.getTipo().substring(0, 1).toUpperCase()
+ pagare.getTipo().substring(1);
Pagare transformedPagare = new Pagare();
transformedPagare.setOperacion(pagare.getOperacion());
transformedPagare.setAnalista(initCapAnalista);
transformedPagare.setTipo(initCapTipo);
return transformedPagare;
}
}
this picture of console when read the file and error
Since you are using named parameters in your INSERT statement, you need to inject a NamedParameterJdbcTemplate into your writer. Also make sure that the parameter names match the property names of the Pagare type (which you did not share).
Related
im getting this error idk why
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='client'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'client' on field 'image': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile#42df4d2d]; codes [typeMismatch.client.image,typeMismatch.image,typeMismatch.[B,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [client.image,image]; arguments []; default message [image]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'byte[]' for property 'image'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'byte' for property 'image[0]': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile']
Entity :
#Entity
#Table(name = "Client")
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="idClient")
private Long idClient;
#Column(name="nom")
private String nomClient;
#Column(name="prenom")
private String prenomClient;
#Column(name="datedenaissance")
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Temporal(TemporalType.DATE)
private Date datedenaissanceClient;
#Column(name="typepiece")
private String typepieceClient;
#Column(name="numeropiece")
private int numeropieceClient;
#Column(name="numerotel")
private Long numerotelClient;
#Column(name="email")
private String emailClient;
#Column(name="adresse")
private String adresseClient;
#Column(name="rendezvous")
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Temporal(TemporalType.DATE)
private Date rendezvous;
#Column(name="temps")
#DateTimeFormat(pattern = "hh:mm")
#Temporal(TemporalType.TIME)
private Date temps;
#Column(name="tempsfin")
#DateTimeFormat(pattern = "hh:mm")
#Temporal(TemporalType.TIME)
private Date tempsfin;
#OneToMany(cascade = CascadeType.ALL, mappedBy="clients")
private List<Compte> comptes;
#Lob
#Column(name="image")
private byte[] image;
public static long getSerialversionuid() {
return serialVersionUID;
}
public Long getIdClient() {
return idClient;
}
public void setIdClient(Long idClient) {
this.idClient = idClient;
}
public String getNomClient() {
return nomClient;
}
public void setNomClient(String nomClient) {
this.nomClient = nomClient;
}
public String getPrenomClient() {
return prenomClient;
}
public void setPrenomClient(String prenomClient) {
this.prenomClient = prenomClient;
}
public Date getDatedenaissanceClient() {
return datedenaissanceClient;
}
public void setDatedenaissanceClient(Date datedenaissanceClient) {
this.datedenaissanceClient = datedenaissanceClient;
}
public String getTypepieceClient() {
return typepieceClient;
}
public void setTypepieceClient(String typepieceClient) {
this.typepieceClient = typepieceClient;
}
public Date getTempsfin() {
return tempsfin;
}
public void setTempsfin(Date tempsfin) {
this.tempsfin = tempsfin;
}
public int getNumeropieceClient() {
return numeropieceClient;
}
public void setNumeropieceClient(int numeropieceClient) {
this.numeropieceClient = numeropieceClient;
}
public Long getNumerotelClient() {
return numerotelClient;
}
public void setNumerotelClient(Long numerotelClient) {
this.numerotelClient = numerotelClient;
}
public String getEmailClient() {
return emailClient;
}
public void setEmailClient(String emailClient) {
this.emailClient = emailClient;
}
public String getAdresseClient() {
return adresseClient;
}
public void setAdresseClient(String adresseClient) {
this.adresseClient = adresseClient;
}
public Date getRendezvous() {
return rendezvous;
}
public void setRendezvous(Date rendezvous) {
this.rendezvous = rendezvous;
}
public Date getTemps() {
return temps;
}
public void setTemps(Date temps) {
this.temps = temps;
}
public List<Compte> getComptes() {
return comptes;
}
public void setComptes(List<Compte> comptes) {
this.comptes = comptes;
}
public Client(Long idClient, String nomClient, String prenomClient, Date datedenaissanceClient,
String typepieceClient, int numeropieceClient, Long numerotelClient, String emailClient,
String adresseClient, Date rendezvous, Date temps, Date tempsfin, List<Compte> comptes, byte[] image) {
super();
this.idClient = idClient;
this.nomClient = nomClient;
this.prenomClient = prenomClient;
this.datedenaissanceClient = datedenaissanceClient;
this.typepieceClient = typepieceClient;
this.numeropieceClient = numeropieceClient;
this.numerotelClient = numerotelClient;
this.emailClient = emailClient;
this.adresseClient = adresseClient;
this.rendezvous = rendezvous;
this.temps = temps;
this.tempsfin = tempsfin;
this.comptes = comptes;
this.image = image;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
#Override
public String toString() {
return "Client [idClient=" + idClient + ", nomClient=" + nomClient + ", prenomClient=" +
prenomClient
+ ", datedenaissanceClient=" + datedenaissanceClient + ", typepieceClient=" +
typepieceClient
+ ", numeropieceClient=" + numeropieceClient + ", numerotelClient=" + numerotelClient +
", emailClient="
+ emailClient + ", adresseClient=" + adresseClient + ", rendezvous=" + rendezvous + ",
temps=" + temps
+ ", tempsfin=" + tempsfin + ", comptes=" + comptes + ", image=" + Arrays.toString(image)
+ "]";
}
public Client() {
super();
// TODO Auto-generated constructor stub
}
public Client(Long idClient, String nomClient, String prenomClient, Date datedenaissanceClient,
String typepieceClient, int numeropieceClient, Long numerotelClient, String emailClient,
String adresseClient, Date rendezvous, Date temps, List<Compte> comptes) {
super();
this.idClient = idClient;
this.nomClient = nomClient;
this.prenomClient = prenomClient;
this.datedenaissanceClient = datedenaissanceClient;
this.typepieceClient = typepieceClient;
this.numeropieceClient = numeropieceClient;
this.numerotelClient = numerotelClient;
this.emailClient = emailClient;
this.adresseClient = adresseClient;
this.rendezvous = rendezvous;
this.temps = temps;
this.comptes = comptes;
}
}
Service :
#Override
public void addClient(Client client){
// TODO Auto-generated method stub
this.clientRepository.save(client);
}
Controller :
#RequestMapping(value = { "/saveClient" }, method = RequestMethod.POST, consumes = {"multipart/form-data"})
public String saveClient(#ModelAttribute("client") Client client,Model model,#ModelAttribute("compte") Compte compte,#ModelAttribute("carte") Carte carte,
#ModelAttribute("agence") Agence agence,MultipartHttpServletRequest request,final #RequestParam("image") MultipartFile file) throws IOException {
compte.setClients(client);
String uploadDirectory = request.getServletContext().getRealPath(uploadFolder);
log.info("uploadDirectory:: " + uploadDirectory);
String fileName = file.getOriginalFilename();
String filePath = Paths.get(uploadDirectory, fileName).toString();
log.info("FileName: " + file.getOriginalFilename());
if (fileName == null || fileName.contains("..")) {
model.addAttribute("invalid", "Sorry! Filename contains invalid path sequence \" + fileName");
}
try {
File dir = new File(uploadDirectory);
if (!dir.exists()) {
log.info("Folder Created");
dir.mkdirs();
}
// Save the file locally
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
stream.write(file.getBytes());
stream.close();
} catch (Exception e) {
log.info("in catch");
e.printStackTrace();
}
byte[] imageData = file.getBytes();
client.setImage(imageData);
Date v = client.getTemps();
//Date dNow = new Date( ); // Instantiate a Date object
Calendar cal = Calendar.getInstance();
cal.setTime(v);
cal.add(Calendar.AM_PM, 0);
cal.add(Calendar.MINUTE, 30);
v = cal.getTime();
client.setTempsfin(v);
clientMetier.addClient(client);
compteMetier.addCompte(compte);
agence.setCompteagence(compte);
compte.setAgencecompte(agence);
agenceMetier.addAgence(agence);
model.addAttribute("compte",compte);
model.addAttribute("agence",agence);
return "compte";
}
HTML:
<form th:action="#{/saveClient}" method="POST"
th:object="${client}" enctype="multipart/form-data">
<div class="p-col-12">
<label class="p1">Image</label>
<input type="file" class="form-control" placeholder="" name="image" id="image" th:field="*{image}">
You should not directly use your entity as the form object as you need to use different types for the image.
Create a separate ClientFormData object to use in the controller that has all the fields of Client, but for image uses MultipartFile:
public class ClientFormData {
// other fields here
private MultipartFile image;
public static ClientFormData fromClient(Client client) {
// copy over fields
}
}
In the controller, get the bytes from the MultipartFile and copy those into your Client entity.
I am newbie to Android Studio and I am making my final year project.
I made a QR code scanner that can retrieve data from HTTP using Rest API.
My question is: I need to send all the JSON data to other activity, based on my research I need to put intent on my button, because of that I need to pass my JsonRequest data to Btn_BuyClicked method so I can send all those to next activity.
I used AndroidHive MovieTickets so Im not changing so much coding.
Please help me. Thank you.
public class TicketResultActivity extends AppCompatActivity {
private static final String TAG = TicketResultActivity.class.getSimpleName();
private Button btnBuy;
private ImageView imgPoster;
private ProgressBar progressBar;
private TicketView ticketView;
private TextView txtDirector;
private TextView txtYear_created;
private TextView txtError;
private TextView txtType_powder;
private TextView txtApa_number;
private TextView txtLocation;
private TextView txtDate_expired;
private Button signOut;
private FirebaseAuth auth;
private class Movie {
String director;
String year_created;
String type_powder;
#SerializedName("released")
boolean isReleased;
String apa_number;
String poster;
String location;
String date_expired;
private Movie() {
}
public String getApa_number() {
return this.apa_number;
}
public String getDirector() {
return this.director;
}
public String getPoster() {
return this.poster;
}
public String getYear_created() {
return this.year_created;
}
public String getType_powder() {
return this.type_powder;
}
public String getLocation() {
return this.location;
}
public String getDate_expired() {
return this.date_expired;
}
public boolean isReleased() {
return this.isReleased;
}
}
NotificationCompat.Builder notification;
private static final int uniqueID = 250298;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_result);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.txtApa_number = (TextView) findViewById(R.id.apa_number);
this.txtDirector = (TextView) findViewById(R.id.director);
this.txtYear_created = (TextView) findViewById(R.id.year_created);
this.txtLocation = (TextView) findViewById(R.id.location);
this.txtDate_expired = (TextView) findViewById(R.id.date_expired);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtType_powder = (TextView) findViewById(R.id.type_powder);
this.btnBuy = (Button) findViewById(R.id.btn_buy);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtError = (TextView) findViewById(R.id.txt_error);
this.ticketView = (TicketView) findViewById(R.id.layout_ticket);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar);
String barcode = getIntent().getStringExtra("code");
if (TextUtils.isEmpty(barcode)) {
Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
finish();
}
searchBarcode(barcode);
}
public void btn_buyClicked(View view) {
notification.setSmallIcon(R.drawable.qrcode);
notification.setTicker("This is the ticker");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Fire Extinguisher Scanner");
Intent intent = new Intent(this, Test.class);
startActivity(new Intent(TicketResultActivity.this, Test.class));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
private void searchBarcode(String barcode) {
MyApplication.getInstance().addToRequestQueue(new JsonObjectRequest(Request.Method.GET, barcode, null, new Listener<JSONObject>() {
public void onResponse(JSONObject response) {
Log.e(TicketResultActivity.TAG, "Ticket response: " + response.toString());
if (response.has("error")) {
TicketResultActivity.this.showNoTicket();
} else {
TicketResultActivity.this.renderMovie(response);
}
}
}, new ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e(TicketResultActivity.TAG, "Error: " + error.getMessage());
TicketResultActivity.this.showNoTicket();
}
}));
}
private void showNoTicket() {
this.txtError.setVisibility(View.VISIBLE);
this.ticketView.setVisibility(View.GONE);
this.progressBar.setVisibility(View.GONE);
}
public void renderMovie(JSONObject response) {
try {
Movie movie = (Movie) new Gson().fromJson(response.toString(), Movie.class);
if (movie != null) {
this.txtApa_number.setText(movie.getApa_number());
this.txtDirector.setText(movie.getDirector());
this.txtYear_created.setText(movie.getYear_created());
this.txtType_powder.setText(movie.getType_powder());
this.txtDate_expired.setText(BuildConfig.FLAVOR + movie.getDate_expired());
this.txtLocation.setText(movie.getLocation());
Glide.with(this).load(movie.getPoster()).into(this.imgPoster);
notification.setContentText("Fire Extinguisher "+ movie.getApa_number()+"successfully remind!");
if (movie.isReleased()) {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
} else {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
}
this.ticketView.setVisibility(View.VISIBLE);
this.progressBar.setVisibility(View.GONE);
return;
}
showNoTicket();
} catch (JsonSyntaxException e) {
Log.e(TAG, "JSON Exception: " + e.getMessage());
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
}
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is my TicketResultActivity.java class UPDATED CODE
private static class Movie implements Parcelable {
String director;
String year_created;
String type_powder;
#SerializedName("released")
boolean isReleased;
String apa_number;
String poster;
String location;
String date_expired;
public Movie() {
}
public Movie(Parcel in) {
director = in.readString();
year_created = in.readString();
type_powder = in.readString();
isReleased = in.readByte() != 0;
apa_number = in.readString();
poster = in.readString();
location = in.readString();
date_expired = in.readString();
}
public String getApa_number(){
return this.apa_number;
}
public String getYear_created() {
return year_created;
}
public String getType_powder() {
return type_powder;
}
public String getDirector() {
return director;
}
public String getPoster() {
return poster;
}
public String getLocation() {
return location;
}
public boolean isReleased() {
return isReleased;
}
public String getDate_expired() {
return date_expired;
}
public void setApa_number(String apa_number){
this.apa_number = apa_number;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(director);
dest.writeString(year_created);
dest.writeString(type_powder);
dest.writeByte((byte) (isReleased ? 1 : 0));
dest.writeString(apa_number);
dest.writeString(poster);
dest.writeString(location);
dest.writeString(date_expired);
}
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
#Override
public int describeContents() {
return 0;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_result);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.txtApa_number = (TextView) findViewById(R.id.apa_number);
this.txtDirector = (TextView) findViewById(R.id.director);
this.txtYear_created = (TextView) findViewById(R.id.year_created);
this.txtLocation = (TextView) findViewById(R.id.location);
this.txtDate_expired = (TextView) findViewById(R.id.date_expired);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtType_powder = (TextView) findViewById(R.id.type_powder);
this.btnBuy = (Button) findViewById(R.id.btn_buy);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtError = (TextView) findViewById(R.id.txt_error);
this.ticketView = (TicketView) findViewById(R.id.layout_ticket);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar);
String barcode = getIntent().getStringExtra("code");
if (TextUtils.isEmpty(barcode)) {
Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
finish();
}
searchBarcode(barcode);
}
public void btn_buyClicked(View view) {
// In activity or fragment
Movie movie = new Movie();
movie.setApa_number("xyz");
Intent intent = new Intent(this, Test.class);
intent.putExtra("parcel_data", movie);
startActivity(intent);
}
private void searchBarcode(String barcode) {
MyApplication.getInstance().addToRequestQueue(new JsonObjectRequest(Request.Method.GET, barcode, null, new Listener<JSONObject>() {
public void onResponse(JSONObject response) {
Log.e(TicketResultActivity.TAG, "Ticket response: " + response.toString());
if (response.has("error")) {
TicketResultActivity.this.showNoTicket();
} else {
TicketResultActivity.this.renderMovie(response);
}
}
}, new ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e(TicketResultActivity.TAG, "Error: " + error.getMessage());
TicketResultActivity.this.showNoTicket();
}
}));
}
private void showNoTicket() {
this.txtError.setVisibility(View.VISIBLE);
this.ticketView.setVisibility(View.GONE);
this.progressBar.setVisibility(View.GONE);
}
public void renderMovie(JSONObject response) {
try {
Movie movie = (Movie) new Gson().fromJson(response.toString(), Movie.class);
if (movie != null) {
this.txtApa_number.setText(movie.getApa_number());
this.txtDirector.setText(movie.getDirector());
this.txtYear_created.setText(movie.getYear_created());
this.txtType_powder.setText(movie.getType_powder());
this.txtDate_expired.setText(BuildConfig.FLAVOR + movie.getDate_expired());
this.txtLocation.setText(movie.getLocation());
Glide.with(this).load(movie.getPoster()).into(this.imgPoster);
if (movie.isReleased()) {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
} else {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
}
this.ticketView.setVisibility(View.VISIBLE);
this.progressBar.setVisibility(View.GONE);
return;
}
showNoTicket();
} catch (JsonSyntaxException e) {
Log.e(TAG, "JSON Exception: " + e.getMessage());
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
}
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is Test.java Class
public class Test extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Movie movie = (Movie) getIntent().getParcelableExtra("parcel_data");
String apa_number = movie.getApa_number();
TextView textView1 = findViewById(R.id.textView2);
textView1.setText(apa_number);
}
}
Use Parcelable is an interface. A class who implements Parcelable can write to and read from a Parcel.
You need to follow 3 points to create a Parcelable class.
A Class must implement Parcelable interface
A Class must have a non-null static field CREATOR of a type that implements Parcelable.Creator interface.
Override writeToParcel method and write member variable in Parcel. Make sure to read variables in the same sequence in which they are written in Parcel. Order of read and write matters.
private class Movie implements Parcelable{
String director;
String year_created;
String type_powder;
#SerializedName("released")
boolean isReleased;
String apa_number;
String poster;
String location;
String date_expired;
public Movie() {
}
// In constructor you will read the variables from Parcel. Make sure to read them in the same sequence in which you have written them in Parcel.
public Movie(Parcel in) {
director = in.readString();
year_created = in.readString();
release_date = in.readString();
poster = in.readString();
}
public String getApa_number() {
return this.apa_number;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
// This is where you will write your member variables in Parcel. Here you can write in any order. It is not necessary to write all members in Parcel.
#Override
public void writeToParcel(Parcel dest, int flags) {
// Write data in any order
dest.writeString(director);
dest.writeString(year_created);
dest.writeString(release_date);
dest.writeString(poster);
}
// This is to de-serialize the object
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>(){
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
Now you can pass a Parcelable object using Intent.
// In activity or fragment
Movie movie = new Movie();
movie.setDirector("xyz");
// now you can set all values like :year created, is released whatever.
// using context and next component class to create intent
Intent intent = new Intent(this, NextActivity.class);
// using putExtra(String key, Parcelable value) method
intent.putExtra(“parcel_data”, movie);
startActivity(intent);
You can access this data in NextActivity –
public class NextActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// Using getParcelableExtra(String key) method
Movie movie = (Movie) getIntent().getParcelableExtra("parcel_data");
String director = movie.getDirector();
}
}
There are so many ways to send data from one activity to another activity. If you Have Primitive or Json string type data then you can directly put that data into the intent.
But if in case you have Model class and you need to pass it. Then you have two ways:
Serializable
Parcelable
But Android recommend to use Parcelable.
You can also add plugin to android studio to generate the parcelable code.
I've make HttpsURLConnection to receive some information about my server.
The result of response is :
{"about":{"title":"NiFi","version":"1.1.0","uri":"https://localhost:443/api/","contentViewerUrl":"/nifi-content-viewer/","timezone":"CET"}}
How is possible to extract all attributes and key/value ?
About.class file
public class About {
private List<AboutObject> about;
public About()
{
// this.about = about;
}
public List<AboutObject> getAbout() {
return this.about;
}
public void setAbout(List<AboutObject> about) {
this.about = about;
}
}
AboutObject.class
public class AboutObject {
private String title;
private String uri;
private String contentViewerUrl;
private String timezone;
public String getTitle()
{
return this.title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getUri()
{
return this.uri;
}
public void setUri(String uri)
{
this.uri = uri;
}
public String getContentViewerUrl()
{
return this.contentViewerUrl;
}
public void setContentViewerUrl(String contentViewerUrl)
{
this.contentViewerUrl = contentViewerUrl;
}
public String getTimeZone()
{
return this.timezone;
}
public void setTimeZone(String timezone)
{
this.timezone = timezone;
}
}
Main.class
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
System.out.println("Contenu de in = " + in.toString());
ObjectMapper mapper = new ObjectMapper();
//Staff objStaff = new Staff();
System.out.println("Object to JSON in file");
mapper.writeValue(new File("output/file.json"), response);
System.out.println("Convert JSON string from file to Object");
//String about = mapper.readValue(new File("output/file.json"), String.class);
About about = mapper.readValue(new File("output/file.json"), About.class);
Error
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of About: no String-argument constructor/factory method to deserialize from String value ('{"about":{"title":"NiFi","version":"1.1.0","uri":"https://localhost:443/api/","contentViewerUrl":"/nifi-content-viewer/","timezone":"CET"}}') at [Source: output/file.json; line: 1, column: 1]
Thanks for you help
The test json you show doesn't have the array wrapper used in your About object. You're also missing the version field in your AboutObject and the timezone field uses the wrong case.
Your example worked when I updated your objects:
public class About {
private AboutObject about;
public AboutObject getAbout() {
return about;
}
public void setAbout(AboutObject about) {
this.about = about;
}
}
public class AboutObject {
private String title;
private String uri;
private String contentViewerUrl;
private String timezone;
private String version;
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getContentViewerUrl() {
return this.contentViewerUrl;
}
public void setContentViewerUrl(String contentViewerUrl) {
this.contentViewerUrl = contentViewerUrl;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
Test:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String obj = "{\"about\":{\"title\":\"NiFi\",\"version\":\"1.1.0\",\"uri\":\"https://localhost:443/api/\",\"contentViewerUrl\":\"/nifi-content-viewer/\",\"timezone\":\"CET\"}}";
About about = mapper.readValue(obj, About.class);
}
Sorry,
if i am asking for lazy solution.
#SpringBootConfiguration
public class RestWebApplication {
public static void main(String[] args) {
SpringApplication.run(RestWebApplication.class, args);
}
}
But when nothing is implemented, I expected
$ curl localhost:8080
{"timestamp":1384788106983,"error":"Not Found","status":404,"message":""}
But Got
<!DOCTYPE html><html><head><title>Apache Tomcat/8.5.9 - Error report</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style> </head><body><h1>HTTP Status 404 - /</h1><div class="line"></div><p><b>type</b> Status report</p><p><b>message</b> <u>/</u></p><p><b>description</b> <u>The requested resource is not available.</u></p><hr class="line"><h3>Apache Tomcat/8.5.9</h3></body></html>
Did i miss something ?
So that i the error page is redirected as JSON Output?
Thanks in credit for your help.
You can try to use #ControllerAdvice that help for custom exception handling in spring.
This is the code I use :
#ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler()
public ResponseEntity<Exception> defaultErrorHandler(Exception e) throws Exception {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
#ExceptionHandler()
public ResponseEntity<ShemoException> defaultErrorHandler(ShemoException e) throws Exception {
return new ResponseEntity<>(e,HttpStatus.NOT_FOUND);
}
This is custom Exception class:
import com.google.gson.JsonSyntaxException;
public class ShemoResponseMessage {
private int returnCode;
private String returnStatus;
private String errorSource;
// constructor
public ShemoResponseMessage() {
returnCode = -1;
returnStatus = null;
errorSource = null;
}
// Constructor with individual response parts
public ShemoResponseMessage(int code, String status, String source) {
returnCode = code;
returnStatus = status;
errorSource = source;
}
public ShemoResponseMessage(String shemoResponse) {
this();
if (shemoResponse == null) {
return;
}
ShemoResponseMessage obj = null;
try {
obj = (ShemoResponseMessage) GsonUtils.createGson().fromJson(shemoResponse,
ShemoResponseMessage.class);
} catch (JsonSyntaxException e) {
returnCode = -1;
returnStatus = "";
errorSource = "";
return;
}
returnCode = obj.returnCode;
returnStatus = obj.returnStatus;
errorSource = obj.errorSource;
}
public ShemoResponseMessage(ShemoException e) {
this(e.getMessage());
}
// Copy constructor
public ShemoResponseMessage(ShemoResponseMessage obj) {
this(obj.getReturnCode(), obj.getReturnStatus(), obj.getErrorSource());
}
// getters
public int getReturnCode() {
return returnCode;
}
public String getReturnStatus() {
return returnStatus;
}
public String getErrorSource() {
return errorSource;
}
// Get the json error message back. Creates a formatted message which can be used for throwing API exceptions
public String getShemoExeption() {
String jsonResponse = GsonUtils.createGson().toJson(this, ShemoResponseMessage.class);
return jsonResponse;
}
}
You can return any message you like
UPDATED
This is my custom exception class you can modify it per your need:
public class ShemoException extends Exception {
private static final long serialVersionUID = 1L;
Integer errorCode;
String errorMessage;
public ShemoException(Exception e) {
super(e);
errorCode = -1;
errorMessage = "";
String classNameMessage = getExceptionClassName(e);
if (e.getMessage() != null)
errorMessage = classNameMessage + ", " + e.getMessage();
else
errorMessage = classNameMessage;
}
private String getExceptionClassName(Exception e) {
String className = new String();
String classNameMessage = new String("");
Class<? extends Exception> eClass = e.getClass();
if (eClass != null) {
className = eClass.getSimpleName();
String words[] = className.split("(?=[A-Z])"); // Split Name by Upper Case for readability
// put the Name back together, now with spaces between words
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (i > 0 && word.length() > 1)
classNameMessage = classNameMessage.concat(" ");
classNameMessage = classNameMessage.concat(word);
}
}
return classNameMessage.trim();
}
public ShemoException(Integer errorCode, String errorMessage) {
super();
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public ShemoException(Integer errorCode, ShemoResponseMessage responseMessage) {
super();
this.errorCode = errorCode;
this.errorMessage = responseMessage.getShemoExeption();
}
public Integer getErrorCode() {
return errorCode;
}
public void setErrorCode(Integer errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
#Override
public String getMessage() {
return getErrorMessage();
}
}
GsonUtils class:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Created by Shemo on 11/24/2015.
*/
public class GsonUtils {
public static String defaultDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ssZ";
private static GsonBuilder gsonBuilder = new GsonBuilder().setDateFormat(defaultDateTimeFormat);
/***
* Creates a GSON instance from the builder with the default date/time format
*
* #return the GSON instance
*/
public static Gson createGson() {
// Create with default params
gsonBuilder = gsonBuilder.setDateFormat(defaultDateTimeFormat);
return gsonBuilder.create();
}
/***
* Creates a GSON instance from the builder specifying custom date/time format
*
* #return the GSON instance
*/
public static Gson createGson(String dateTimeFormat) {
// Create with the specified dateTimeFormat
gsonBuilder = gsonBuilder.setDateFormat(dateTimeFormat);
return gsonBuilder.create();
}
}
GSON library:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
i'm populating my tableview from mysql database but only the column ID is the only one that's populated.
my main:
public void populate() throws Exception{
ObservableList<userdata1> data = FXCollections.observableArrayList();
tableView();
try{
String query = "select * from members";
ps = new Connect().connectDatabase1();
rs = ps.executeQuery(query);
while(rs.next()){
data.add(new userdata1(rs.getInt(1),rs.getString(2),rs.getInt(3)));
tblView.setItems(data);
}
}catch(Exception e){
System.out.print("asdqweasd");
}
}
public void tableView()throws Exception{
tblView.getItems().clear();
tblView.getColumns().clear();
rs = ps.executeQuery("SELECT * FROM members");
ObservableList<userdata1> data = FXCollections.observableArrayList();
TableColumn column1 = new TableColumn("ID");
column1.setMinWidth(85);
column1.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("ID"));
TableColumn column2 = new TableColumn("Name");
column2.setMinWidth(565);
column2.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("comp_name"));
TableColumn column3 = new TableColumn("STATUS");
column3.setMinWidth(123);
column3.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("mem_status"));
tblView.getColumns().addAll(column1,column2,column3);
}
my userdata1:
public class userdata1 {
public SimpleIntegerProperty ID;
public SimpleStringProperty comp_name;
public SimpleIntegerProperty mem_status;
public userdata1(Integer id, String comp_name, Integer mem_status){
this.ID = new SimpleIntegerProperty(id);
this.comp_name = new SimpleStringProperty(comp_name);
this.mem_status = new SimpleIntegerProperty(mem_status);
}
public Integer getID() {
return ID.get();
}
public String getcomp_name(){
return comp_name.get();
}
public Integer getmem_status() {
return mem_status.get();
}
public void setID(Integer id) {
this.ID.set(id);
}
public void setcomp_name(String comp_name ) {
this.comp_name.set(comp_name);
}
public void setmem_status(Integer mem_status) {
this.mem_status.set(mem_status);
}
}
the data mem_status and comp_name is not populating their respective columns
As UserData1 already contains Properties, you can set the according Property to the cellValueFactory:
public class UserData1 {
private StringProperty comp_name;
//additional fields, getters and setters
public StringProperty comp_nameProperty() {
return comp_name;
}
}
setCellValueFactory(cellData -> cellData.getValue().comp_nameProperty());
If you want to stick to the PropertyValueFactory you have to access the fields according to the CamelCase convention:
column2.setCellValueFactory(new PropertyValueFactory<>("comp_name"));
public class UserData1 {
//...
public String getComp_name(){
return comp_name.get();
}
}