CRM workflow to send a report attachment to users - reporting-services

I have written some code to send an email attachment through CRM to a specific user, using a workflow, the attachment is a transcript report which contains 2 sub reports in order to get some data about students. The problem that i have is that the email is not delivered and the attachment breaks indicating this:
"Data retrieval failed for the subreport, 'Subreport2', located at:
/StudentReports/StudentAddress. Please check the log files for more
information."
The log files contain no useful information. Here is the code:
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.Workflow;
using NUP.CRM.DAL;
using NUP.CRM.DAL.Utility;
using NUP.CRM.Utilities;
using System.Collections.Generic;
using System.Workflow.ComponentModel;
namespace NUP.CRM.WorkFlows
{
/// <summary>
/// Sends transcript of a given assessment board and ac. year as attachment to email
/// </summary>
[CrmWorkflowActivity("Send email with Report Attached", "NUP")]
public class SendReport : Activity
{
public static DependencyProperty AcademicYearProperty = DependencyProperty.Register("AcademicYear", typeof(string), typeof(SendReport));
public static DependencyProperty AssBoardProperty = DependencyProperty.Register("AssBoard", typeof(string), typeof(SendReport));
public static DependencyProperty EmailAddressTypeProperty = DependencyProperty.Register("EmailAddressType", typeof(string), typeof(SendReport));
public static DependencyProperty EmailBodyProperty = DependencyProperty.Register("EmailBody", typeof(string), typeof(SendReport));
public static DependencyProperty IsPositiveProperty = DependencyProperty.Register("IsPositive", typeof(CrmBoolean), typeof(SendReport));
public static DependencyProperty ReportNameProperty = DependencyProperty.Register("ReportName", typeof(string), typeof(SendReport));
public static DependencyProperty ReportPathProperty = DependencyProperty.Register("ReportPath", typeof(string), typeof(SendReport));
public static DependencyProperty SenderProperty = DependencyProperty.Register("Sender", typeof(Lookup), typeof(SendReport));
public static DependencyProperty SendFromAddressProperty = DependencyProperty.Register("SendFromAddress", typeof(string), typeof(SendReport));
public static DependencyProperty SubjectProperty = DependencyProperty.Register("Subject", typeof(string), typeof(SendReport));
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
IWorkflowContext context = executionContext.GetService<IContextService>().Context;
ICrmService service = context.CreateCrmService();
byte[] report = ReportUtility.GetReport(
ReportPath,
ReportUtility.Formats.PDF,
new string[] { "contactid", "AcYear", "IsPositive", "AssBoard" },
new string[] {
context.PrimaryEntityId.ToString(),
AcademicYear.ToString(),
IsPositive.Value.ToString(),
AssBoard }
);
string addressToUse = DynamicEntityUtility.GetContactEmailOfType(service, context.PrimaryEntityId, EmailAddressType);
EmailUtility emailUtility =
new EmailUtility(service, context.UserId, context.PrimaryEntityId, addressToUse);
List<EmailUtility.Attachment> attachments =
new List<EmailUtility.Attachment>()
{
new EmailUtility.Attachment(ReportName, report)
};
emailUtility.Send(Subject, attachments);
return ActivityExecutionStatus.Closed;
}
[CrmInput("AcademicYear")]
public string AcademicYear
{
get
{
return (string)base.GetValue(AcademicYearProperty);
}
set
{
base.SetValue(AcademicYearProperty, value);
}
}
[CrmInput("AssBoard")]
public string AssBoard
{
get
{
return (string)base.GetValue(AssBoardProperty);
}
set
{
base.SetValue(AssBoardProperty, value);
}
}
[CrmInput("EmailAddressType")]
public string EmailAddressType
{
get
{
return (string)base.GetValue(EmailAddressTypeProperty);
}
set
{
base.SetValue(EmailAddressTypeProperty, value);
}
}
[CrmInput("EmailBody")]
public string EmailBody
{
get
{
return (string)base.GetValue(EmailBodyProperty);
}
set
{
base.SetValue(EmailBodyProperty, value);
}
}
[CrmInput("IsPositive")]
public CrmBoolean IsPositive
{
get
{
return (CrmBoolean)base.GetValue(IsPositiveProperty);
}
set
{
base.SetValue(IsPositiveProperty, value);
}
}
[CrmInput("ReportName")]
public string ReportName
{
get
{
return (string)base.GetValue(ReportNameProperty);
}
set
{
base.SetValue(ReportNameProperty, value);
}
}
[CrmInput("ReportPath")]
public string ReportPath
{
get
{
return (string)base.GetValue(ReportPathProperty);
}
set
{
base.SetValue(ReportPathProperty, value);
}
}
[CrmReferenceTarget("systemuser"), CrmInput("Sender")]
public Lookup Sender
{
get
{
return (Lookup)base.GetValue(SenderProperty);
}
set
{
base.SetValue(SenderProperty, value);
}
}
[CrmInput("SendFromAddress")]
public string SendFromAddress
{
get
{
return (string)base.GetValue(SendFromAddressProperty);
}
set
{
base.SetValue(SendFromAddressProperty, value);
}
}
[CrmInput("Subject")]
public string Subject
{
get
{
return (string)base.GetValue(SubjectProperty);
}
set
{
base.SetValue(SubjectProperty, value);
}
}
}
}

Related

Convert POJO to a GSON to JSON

I'm trying to send a JSON post request to https://graph.microsoft.com/v1.0/me/sendMail to send an email.
I created a POJO with getters and setters so I can set the json value dynamically.
SendEmail.java
import java.util.ArrayList;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
public class SendEmail {
public class Body{
public String contentType;
public String content;
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
public class CcRecipient{
public EmailAddress emailAddress;
public void setEmailAddress(SendEmail.EmailAddress emailAddress) {
this.emailAddress = emailAddress;
}
public SendEmail.EmailAddress getEmailAddress() {
return emailAddress;
}
}
public class EmailAddress{
public String address;
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
}
public class Message{
public String subject;
public Body body;
public ArrayList<ToRecipient> toRecipients;
public ArrayList<CcRecipient> ccRecipients;
public void setSubject(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
public void setBody(SendEmail.Body body) {
this.body = body;
}
public SendEmail.Body getBody() {
return body;
}
public void setToRecipients(ArrayList<SendEmail.ToRecipient> toRecipients) {
this.toRecipients = toRecipients;
}
public ArrayList<SendEmail.ToRecipient> getToRecipients() {
return toRecipients;
}
public void setCcRecipients(ArrayList<SendEmail.CcRecipient> ccRecipients) {
this.ccRecipients = ccRecipients;
}
public ArrayList<SendEmail.CcRecipient> getCcRecipients() {
return ccRecipients;
}
}
public class Root{
public Message message;
public String saveToSentItems;
public void setMessage(SendEmail.Message message) {
this.message = message;
}
public SendEmail.Message getMessage() {
return message;
}
public void setSaveToSentItems(String saveToSentItems) {
this.saveToSentItems = saveToSentItems;
}
public String getSaveToSentItems() {
return saveToSentItems;
}
}
public class ToRecipient{
public EmailAddress emailAddress;
public void setEmailAddress(SendEmail.EmailAddress emailAddress) {
this.emailAddress = emailAddress;
}
public SendEmail.EmailAddress getEmailAddress() {
return emailAddress;
}
}
}
Below is the test class. The jsonRequest is empty. How can I put the correct JSON values using my POJO?
Test.java
SendEmail sendEmail = new SendEmail();
SendEmail.Message message = sendEmail.new Message();
message.setSubject("Test subject");
SendEmail.Body body = sendEmail.new Body();
body.setContent("this is a test body on an email");
SendEmail.ToRecipient toRecipient = sendEmail.new ToRecipient();
SendEmail.EmailAddress emailAddress = sendEmail.new EmailAddress();
emailAddress.setAddress("dummyemail#outlook.com");
toRecipient.setEmailAddress(emailAddress);
String accessToken = connectEmail(); System.out.println("ACCESS TOKEN: "+accessToken);
HttpURLConnection connection = null;
Gson gson = new Gson();
String jsonRequest = gson.toJson(toRecipient);
try {
URL url = new URL("https://graph.microsoft.com/v1.0/me/sendMail");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization","Bearer "+accessToken);
connection.setRequestProperty("Content-Type", "application/json");
//connection.setRequestProperty("Accept", "text/plain");
connection.setUseCaches(false);
connection.setDoOutput(true);
try(OutputStream os = connection.getOutputStream()) {
System.out.println("jsonRequest: "+jsonRequest);
os.write(jsonRequest.getBytes());
}
} catch (Exception e) {
System.out.println("EXCEPTION SENDING EMAIL");
}
Below is the sample post request I need to write using values from the POJO.
{
"message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "Text",
"content": "The new cafeteria is open."
},
"toRecipients": [
{
"emailAddress": {
"address": "frannis#contoso.onmicrosoft.com"
}
}
],
"ccRecipients": [
{
"emailAddress": {
"address": "danas#contoso.onmicrosoft.com"
}
}
]
},
"saveToSentItems": "false"
}

Can we substitute a function name with variable in C#

I wanted to check if we can create a function name from variable value in C#. Here is what I am trying. I have a list of strings as below:
private List<string> _pages;
_pages.AddRange(new string[] { "Page1", "Page2", "Page3", "Page4"});
And I have tasks like below:
private async void Sync_Page1() {}
private async void Sync_Page2() {}
private async void Sync_Page3() {}
private async void Sync_Page4() {}
For each of those strings in the list, I need to call a method like below
foreach (string pageName in _pages)
{
Task.Run(async () => { Sync_pageName() }); // where pageName will be the items from list.
}
Tried searching on google but didn't find anything specific. So not sure if that can be done in C# but was wondering if there is a possibility.
Any thoughts?
You can map it to dictionary items which you can invoke :
namespace ConsoleApp1
{
class Program
{
public static void Main(String[] args)
{
PagesExecution pe = new PagesExecution();
pe.Execute();
Console.ReadLine();
}
}
public class PagesExecution
{
//Action<string> a = new Action<string>();
private List<string> _pages = new List<string>();
private Dictionary<string, Action> dictionary = new Dictionary<string, Action>();
public PagesExecution ()
{
}
public void Execute()
{
dictionary.Add("Page1", new Action(Sync_Page1));
dictionary.Add("Page2", Sync_Page2);
dictionary.Add("Page3", Sync_Page3);
dictionary.Add("Page4", Sync_Page4);
_pages.AddRange(new string[] { "Page1", "Page2", "Page3", "Page4"});
foreach (var entry in _pages)
{
dictionary[entry].Invoke();
}
}
public void Sync_Page1()
{
Console.WriteLine("Page1");
}
private void Sync_Page2()
{
Console.WriteLine("Page2");
}
private void Sync_Page3()
{
Console.WriteLine("Page3");
}
private void Sync_Page4()
{
Console.WriteLine("Page4");
}
}
}

I cannot insert to the mysql database with spring batch

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).

Passing a method data to other method in same Activity

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.

store details in windows phone 8 using sqlite?

I want to store information from the NFC tag I read and store in the database and show it all in another page but I am having problem in using implementing sqlite.I cant add the information to the database using sqlite.
Below is my checkin class from where I read from the NFC tag
public partial class Checkin : PhoneApplicationPage
{
private ProximityDevice _device;
private long _subscriptionIdNdef;
public static double Latitud_do { get; set; }
public static double Longtitude_do { get; set; }
public static string latitude { get; set; }
public static string longtitude { get; set; }
public static string Floor_st { get; set; }
public static string Zone_st { get; set; }
History store = new History();
public Checkin()
{
InitializeProximityDevice();
InitializeComponent();
}
private void SetLogStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (LogStatus != null) LogStatus.Text = newStatus; });
}
private void SetFloorStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (FloorStatus != null) FloorStatus.Text = newStatus; });
}
private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
{
MessageBox.Show(" ");
}
private void InitializeProximityDevice()
{
_device = Windows.Networking.Proximity.ProximityDevice.GetDefault();
if (_device != null)
{
_subscriptionIdNdef = _device.SubscribeForMessage("NDEF", MessageReceivedHandler);
}
}
private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
{
var rawMsg = message.Data.ToArray();
var ndefMessage = NdefMessage.FromByteArray(rawMsg);
////// Loop over all records contained in the NDEF message
foreach (NdefRecord record in ndefMessage)
{
if (NdefTextRecord.IsRecordType(record))
{
// Convert and extract URI info
var textRecord = new NdefTextRecord(record);
string[] str = textRecord.Text.Split('|');
var Floor_st = str[0];
var Zone_st = str[1];
var latitude = str[2];
var longtitude = str[3];
Latitud_do = double.Parse(latitude);
Longtitude_do = double.Parse(longtitude);
SetLogStatus("Floor: " + Floor_st + " Zone: " + Zone_st );
SetFloorStatus("Longitude: " + latitude + " Longitude: " + longtitude);
//store.AddDb(Floor_st, Zone_st, Latitud_do, Longtitude_do);
}
}
}
}
Below here is the main dbhelper class for the main sqlite functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
}
below is the class from where I read all the information
public class ReadAllContactsList
{
DbHelper Db_Helper = new DbHelper();
public ObservableCollection<historyTableSQlite> GetAllHistory()
{
return Db_Helper.ReadHistory();
}
}
}
And last is the class where I want to show all the information I have stored
ublic partial class History : PhoneApplicationPage
{
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
public History()
{
InitializeComponent();
}
private void ReadHistoryList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();//Latest contact ID can Display first
}
public void AddInfo(object sender, RoutedEventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.Insert(new historyTableSQlite(
));
}
}
I followed the following post but still struglling
http://bsubramanyamraju.blogspot.com/2014/08/windowsphone-8-sqlite-storing-data-in.html
Thank you for your help in advance