I have two entities: Movie and Person in my simple Movie App. While I try to add initial data to database something strange is happening. Even though my both entities are very similar, inserting people works fine, while inserting movies result in having 11 (while array of 7 is passed as argument) movie elements with null fields in it:
I/System.out: [Movie{id=23, title='null', genre='null',
posterResource=null}, Movie{id=24, title='null', genre='null',
posterResource=null} ... Movie{id=33, title='null', genre='null',
posterResource=null}]
I/System.out: [Person{id=23, firstName='Brad', lastName='Pitt', age=55,
imgResource=2131165277}, Person{id=24, firstName='Edward',
lastName='Norton', age=49, imgResource=2131165286}, ... , Person{id=33,
firstName='Joaquin', lastName='Phoenix', age=44, imgResource=2131165293}]
Interior of my LocalDataSource, where I insert data:
private AppDatabase mDataBase;
public LocalDataSource(Context mContext) {
mDataBase = AppDatabase.getAppDatabase(mContext);
mDataBase.personDao().deleteAllPeople();
mDataBase.movieDao().deleteAllMovies();
setupTestMovieData();
setupTestActorsData();
setupTestMovieActorRelationship();
System.out.println(getAllMovies());
System.out.println(getAllActors());
}
public List<Movie> getAllMovies(){
return mDataBase.movieDao().loadAllMovie();
}
public List<Person> getAllActors(){
return mDataBase.personDao().loadAllPeople();
}
public List<Person> getActorsFromMovie(long movieId){
return mDataBase.actorMovieJoinDao().getActorsFromMovie(movieId);
}
private void setupTestMovieData() {
MovieDao dao = mDataBase.movieDao();
dao.insertMovie(getTestMovieArray());
}
private Movie[] getTestMovieArray() {
Movie[] movies = new Movie[7];
movies[0] = new Movie("Fight club", "Thriller", R.drawable.fightclub);
movies[1] = new Movie("Prestige", "Thriller",R.drawable.prestige);
movies[2] = new Movie("500 days of Summer","Drama", R.drawable.the500daysofsummer);
movies[3] = new Movie("Seven","Detective", R.drawable.kiler);
movies[4] = new Movie("Inception","Action", R.drawable.pulpfiction);
movies[5] = new Movie("American Hustle","Crime", R.drawable.phantomthread);
movies[6] = new Movie("Her","Drama", R.drawable.dancerinthedark);
return movies;
}
private void setupTestActorsData(){
PersonDao dao = mDataBase.personDao();
dao.insertPeople(getTestActorArray());
}
private Person[] getTestActorArray() {
Person[] actors = new Person[11];
actors[0] = createPerson("Brad", "Pitt", "18/12/1963", R.drawable.bradpitt);
actors[1] = createPerson("Edward", "Norton", "18/8/1969", R.drawable.edwardnorton);
actors[2] = createPerson("Helena", "Bonham-Carter", "26/5/1966", R.drawable.helenabonhamcarter);
actors[3] = createPerson("Joseph", "Gordon-Levitt", "17/2/1981", R.drawable.josephgordonlevitt);
actors[4] = createPerson("Zooey", "Deschanel", "17/1/1980", R.drawable.zooeydeschanel);
actors[5] = createPerson("Christian", "Bale", "30/1/1974", R.drawable.christianbale);
actors[6] = createPerson("Leonardo", "DiCaprio", "11/11/1974", R.drawable.leonardodicaprio);
actors[7] = createPerson("Morgan", "Freeman", "1/6/1937", R.drawable.morganfreeman);
actors[8] = createPerson("Amy", "Adams", "20/8/1974", R.drawable.amyadams);
actors[9] = createPerson("Scarlett", "Johansson", "22/11/1984", R.drawable.scarlettjohansson);
actors[10] = createPerson("Joaquin", "Phoenix", "28/10/1974", R.drawable.joaquinphoenix);
return actors;
}
private Person createPerson(String firstName, String lastName, String date, Integer imgResource){
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
GregorianCalendar gregorianCalendar = new GregorianCalendar();
try {
gregorianCalendar.setTime(sdf.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
return new Person(firstName, lastName, gregorianCalendar, imgResource);
}
Related
I have a class with set and get, and In another class.
However, if I use Classname X = new Classname(); I'll not be able to use previous information set before.
Here's part of the code:
public void BuscarID () throws Exception {
//THIS VOID IS FOR SEARCH
ConsumirWS2 http = new ConsumirWS2();
Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
Cliente2 u = new Cliente2();
Type ClienteType = new TypeToken<Cliente2>() {
}.getType();
int i = Integer.parseInt(InterfaceConsu2.jTextFieldID.getText());
u.setCad_pes_id(i);
String s = Integer.toString(u.getcad_pes_id());
String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Clienteid/get/"+s;
String json = http.sendGet(url, "GET");
u = g.fromJson(json, ClienteType);
System.out.println(json + ("\n"));
System.out.println(u.getcad_pes_nome() +("\n") + u.getCad_pes_apelido() +("\n") + u.getCad_pes_cpf() +("\n") + u.getCad_pes_data()+("\n"));
String Date1 = new SimpleDateFormat("dd-MM-yyyy").format(u.getCad_pes_data());
System.out.println(Date1);
InterfaceConsu2.jTextFieldNOME.setText(u.getcad_pes_nome());
InterfaceConsu2.jTextFieldAPELIDO.setText(u.getCad_pes_apelido());
InterfaceConsu2.jFormattedTextFieldCPF.setText(u.getCad_pes_cpf());
InterfaceConsu2.jFormattedTextFieldDATA.setText(Date1);
InterfaceConsu2.jTextFieldID.setText(s);
}
public void alterar () throws Exception {
//THIS VOID IS FOR EDITING THE INFORMATION GET BEFORE
ConsumirWS2 http = new ConsumirWS2();
Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
Cliente2 u = new Cliente2();
Type ClienteType = new TypeToken<Cliente2>() {
}.getType();
u.setCad_pes_nome(InterfaceConsu2.jTextFieldNOME.getText());
u.setCad_pes_cpf(InterfaceConsu2.jFormattedTextFieldCPF.getText());
u.setCad_pes_apelido(InterfaceConsu2.jTextFieldAPELIDO.getText());
int i = Integer.parseInt(InterfaceConsu2.jTextFieldID.getText());
u.setCad_pes_id(i);
//u.setCad_pes_id(InterfaceConsu2.jTextFieldID.getText());
SimpleDateFormat formatter = new SimpleDateFormat ("dd-MM-yyyy");
java.util.Date utilDate = null;
try {
utilDate = formatter.parse(InterfaceConsu2.jFormattedTextFieldDATA.getText());
} catch (ParseException ex) {
Logger.getLogger(InterfaceConsu2.class.getName()).log(Level.SEVERE, null, ex);
}
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
u.setCad_pes_data(sqlDate);
String json = g.toJson(u, ClienteType);
String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/alterar";
http.sendPost(url, json, "PUT");
}
and then I have the set and get class:
public class Cliente2 {
public String cad_pes_nome;
public String cad_pes_apelido;
private String cad_pes_cpf;
public int cad_pes_id;
public Date cad_pes_data;
public String getcad_pes_nome() {
return cad_pes_nome;
}
public void setCad_pes_nome(String cad_pes_nome) {
this.cad_pes_nome = cad_pes_nome;
}
public String getCad_pes_apelido() {
return cad_pes_apelido;
}
public void setCad_pes_apelido(String cad_pes_apelido) {
this.cad_pes_apelido = cad_pes_apelido;
}
public String getCad_pes_cpf() {
return cad_pes_cpf;
}
public void setCad_pes_cpf(String cad_pes_cpf) {
this.cad_pes_cpf = cad_pes_cpf;
}
public int getcad_pes_id() {
return cad_pes_id;
}
public void setCad_pes_id(int cad_pes_id) {
this.cad_pes_id = cad_pes_id;
}
public Date getCad_pes_data() {
return cad_pes_data;
}
public void setCad_pes_data(Date cad_pes_data) {
this.cad_pes_data = cad_pes_data;
}
}
Because I'm using Classname X = new Classname();, when I try to print my u.getcad_pes_nome or any other get, It's empty, There's a way to call Cliente2 without using Cliente2 u = new Cliente2(); or what I have to change in my classes?
I have an intermediate table that gets information from two other tables from the database (it gets their id), I'd like to show information of the other tables through that intermediate table in each of the others but it show me all of the information.
public showTheatreForm(Resources res, Theatre t) {
Toolbar tb=new Toolbar(true);
current=this;
setToolbar(tb);
getTitleArea().setUIID("Container");
setTitle("modifier actor");
getContentPane().setScrollVisible(false);
super.addSideMenu(res);
Label name = new Label((t.getName()));
Picker datePicker = new Picker();
datePicker.setDate(t.getRdate());
String datestring=(new SimpleDateFormat("yyyy-MM-dd")).format(datePicker.getDate());
Label date = new Label((datestring));
TextField description = new TextField((t.getDescription()));
TextField actors = new TextField((t.getTactor()));
//Label image = new Label((t.getImage()), "Image");
ImageViewer imavu;
try {
imavu = new ImageViewer(getImageFromServer(t.getImage()));
}
catch(Exception e) {
System.out.println(t.getImage());
imavu = new ImageViewer(res.getImage("s.png"));
}
description.setSingleLineTextArea(false);
actors.setSingleLineTextArea(false);
name.setUIID("NewsCenterLine");
date.setUIID("NewsCenterLine");
description.setUIID("NewsCenterLine");
imavu.setUIID("NewsCenterLine");
actors.setUIID("NewsCenterLine");
Label a = new Label("");
Label e = new Label ();
Container content = BoxLayout.encloseY(
e,a, (name),
createLineSeparator(), (actors),
createLineSeparator(),date,
createLineSeparator(), (description),
createLineSeparator(), (imavu)
);
add(content);
show();
}
And this is how I get it from the database:
public ArrayList<Theatre> ShowTheatre (){
ArrayList<Theatre> result=new ArrayList<>();
String url=Statics.BASE_URL+"/theatre/displayTheatre";
req.setUrl(url);
req.addResponseListener(new ActionListener<NetworkEvent>() {
#Override
public void actionPerformed(NetworkEvent evt) {
JSONParser Jsonp;
Jsonp=new JSONParser();
try{
Map<String,Object>mapTheatre= Jsonp.parseJSON(new CharArrayReader(new String(req.getResponseData()).toCharArray()));
List<Map<String,Object>> listofMaps = (List<Map<String,Object>>) mapTheatre.get("root");
for(Map<String,Object> obj : listofMaps)
{
Theatre th=new Theatre();
float id=Float.parseFloat(obj.get("id").toString());
String name=obj.get("name").toString();
String genre=obj.get("genre").toString();
String description=obj.get("description").toString();
String image=obj.get("image").toString();
String trailer=obj.get("trailer").toString();
String poster=obj.get("poster").toString();
String get=obj.get("theatreActors").toString();
th.setId((long)id);
th.setName(name);
th.setTactor(get);
System.out.println(get);
th.setDescription(description);
th.setImage(image);
th.setTrailer(trailer);
th.setPoster(poster);
th.setGenre(genre);
Map<String, Object> dd = (Map<String, Object>) obj.get("rdate");
float ll = Float.parseFloat(dd.get("timestamp").toString());
th.setRdate(new Date(((long) ll * 1000)));
}
result.add(th);
}
} catch (IOException ex) {
System.out.println(
"good");
}
}
});
NetworkManager.getInstance().addToQueueAndWait(req);
return result;
}
Result of the code
This is the result, but I only want to get the "name" and "date" or "description" from the intermediate table
My intermediate table
(the name of the table is theatreActors)
I need to load a big .csv into my database, I have the Price entity that has a reference to a Distributor:
public class Price {
#Id
private String id;
private Date dtComu;
private Double price;
#ManyToOne
#JoinColumn(name = "idDistributor")
private Distributor distributor;
//constrcutor, getters&setters
The csv with Price data that I try to upload has a reference to the Distributor id for each Price. on the ItemReader i have:
public FlatFileItemReader<Price> priceReader() {
FlatFileItemReader<Price> reader = new FlatFileItemReader<>();
reader.setResource(new ClassPathResource("file.csv"));
reader.setLinesToSkip(2);
reader.setRecordSeparatorPolicy(recordSeparatorPolicy);
reader.setLineMapper(new DefaultLineMapper<Price>() {
{
setLineTokenizer(new DelimitedLineTokenizer() {
{
setStrict(false);
setDelimiter(";");
setNames(new String[] { "idDistributor", "price", "dtComu" });
}
});
setFieldSetMapper(customMapper());
}
});
return reader;
}
And my customMapper is:
public class CustomMapper implements FieldSetMapper<Price> {
#Autowired
DistributorRepository repository;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
#Override
public Price mapFieldSet(FieldSet fieldSet) throws BindException {
Distributor distributor = repository.findById(fieldSet.readInt("idDistributor")).orElse(null);
if (distributore == null) {
return null;
}
Price p = new Price();
p.setDistributor(distributor);
p.setPrice(fieldSet.readDouble("price"));
try {
p.setDtComu(formatter.parse(fieldSet.readString("dtComu")));
} catch (ParseException e) {
// TODO Auto-generated catch block
p.setDtComu(new Date());
}
//here i will crate an ID for the Price that i need to always be unique
p.setId(distributor.getIdImpianto()+ fieldSet.readString("dtComu"));
return p; }}
My Writer is as follows:
public JdbcBatchItemWriter<Price> prezzoWriter() {
JdbcBatchItemWriter<price> writer = new JdbcBatchItemWriter<Price>();
writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Prezzo>());
;
writer.setSql("INSERT INTO price (id_distributor, price, dt_comu) "
+ "VALUES (:idDistributor, :price, :dtComu");
writer.setDataSource(dataSource);
return writer;
}
I run the program and it completes without anything being saved. Could I be doing something very wrong? I just started with Sring Batch and have to elaborate something a bit complex..
The JdbcBatchItemWriter knows nothing about the JPA context. You need to use a DataSourceTransactionManager for this to work.
I try to get xml data then I parse it to JSON, I use OkHttp as a connection. I managed to get data from LOG but I can't display it in my RecyclerView, when I LOG to adapter and the result is size 0
I set the response to the model and sharedpreference
The point of the problem is that I just don't understand how to take the response from the presenter then I set it to the adapter in the main Fragment.
public class ParentCategories {
#SerializedName("idkategori")
#Expose
private String idkategori;
#SerializedName("namakategori")
#Expose
private String namakategori;
#SerializedName("fileicon")
#Expose
private String fileicon;
#SerializedName("subkategori")
#Expose
private SubCategories subkategori;
public ParentCategories(Parcel in) {
this.idkategori = in.readString();
this.namakategori = in.readString();
this.fileicon = in.readString();
}
public ParentCategories() {
}
public String getIdkategori() {
return idkategori;
}
public void setIdkategori(String idkategori) {
this.idkategori = idkategori;
}
public String getNamakategori() {
return namakategori;
}
public void setNamakategori(String namakategori) {
this.namakategori = namakategori;
}
public String getFileicon() {
return fileicon;
}
public void setFileicon(String fileicon) {
this.fileicon = fileicon;
}
public SubCategories getSubkategori() {
return subkategori;
}
public void setSubkategori(SubCategories subkategori) {
this.subkategori = subkategori;
}
}
public class CategoriesPresenter {
....
public void onResponse(Call call, Response response) throws IOException {
String mMessage = response.body().string();
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(mMessage);
JSONObject jsonObject = new JSONObject(jsonObj.toString());
JSONObject object = jsonObject.getJSONObject("posh");
String attr2 = object.getString("resultcode");
com.davestpay.apphdi.helper.Log.d("hasil", String.valueOf(object));
if (attr2.equalsIgnoreCase("0000")) {
String idAgen = object.getString("idagen");
int jumlahKategori = object.getInt("jumlahkategori");
JSONArray category = object.getJSONArray("kategori");
List<ParentCategories> parentCategories = new ArrayList<ParentCategories>();
for (int i = 0; i < category.length(); i++) {
ParentCategories categories = new ParentCategories();
JSONObject c = category.getJSONObject(i);
Log.d(TAG, "onResponseC: "+c);
String idKategori = c.getString("idkategori");
String namaKategori = c.getString("namakategori");
Log.d(TAG, "onResponseNamaKategori: "+namaKategori);
String fileIcon = c.getString("fileicon");
JSONObject subCategories = c.getJSONObject("subkategori");
JSONArray subCategory = subCategories.getJSONArray("kategori2");
Log.d(TAG, "onResponseSubCategories: "+subCategory);
for (int subCatPosition = 0; subCatPosition < subCategory.length(); subCatPosition++) {
SecondCategories secondCategories = new SecondCategories();
List<SecondCategories> listSecondCategories = new ArrayList<>();
JSONObject sc = subCategory.getJSONObject(subCatPosition);
String secIdKategori = sc.getString("idkategori");
String secNamaKategori = sc.getString("namakategori");
String secFileIcon = sc.getString("fileicon");
secondCategories.setIdkategori(secIdKategori);
secondCategories.setNamakategori(secNamaKategori);
secondCategories.setFileicon(secFileIcon);
listSecondCategories.add(secondCategories);
}
categories.setIdkategori(idKategori);
categories.setNamakategori(namaKategori);
categories.setFileicon(fileIcon);
parentCategories.add(categories);
Log.d(TAG, "onResponseFinalCategories: "+parentCategories);
}
iCategories.onSuccessCategories(parentCategories);
preferenceHelper.clear(PreferenceHelper.CATEGORIES);
preferenceHelper.putList(PreferenceHelper.CATEGORIES, parentCategories);
} else {
Log.d(TAG, "onResponse: ");
}
} catch (JSONException e) {
com.davestpay.apphdi.helper.Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}
}
}
private void getInit() {
if (preferenceHelper != null) {
idAgen = preferenceHelper.getString(PreferenceHelper.ID_AGEN);
namaAgen = preferenceHelper.getString(PreferenceHelper.NAMA_AGEN);
password = preferenceHelper.getString(PreferenceHelper.PASSWORD);
categories = preferenceHelper.getList(PreferenceHelper.CATEGORIES, ParentCategories[].class);
}
authPresenter = new AuthPresenter(getContext());
presenter = new CategoriesPresenter();
presenter.setBaseView(this);
presenter.onCreate(getContext());
if (authPresenter.isLoggedIn()) {
// kategori.setText(categories.toString());
presenter.getCategories(idAgen, password, counter);
}
kategori = mView.findViewById(R.id.kategori);
categories = new ArrayList<>();
rvMain = mView.findViewById(R.id.rv_categories);
adapter = new CategoriesListViewAdapter(getContext(), categories);
layoutManager = new LinearLayoutManager(getdActivity());
adapter.notifyDataSetChanged();
rvMain.setLayoutManager(layoutManager);
rvMain.setAdapter(adapter);
}
This is the problem.
categories = new ArrayList<>();
Here, you are initialising categories to new ArrayList<>(); It is like you are creating a new arraylist.
Just remove this line.
I want to display two data on listview through the json input. All the code are alter from internet which I got error. I have not clear logic to understand the meaning of the code. Please give me advice and alter my code.
private void displayArrayList(String jsonStr){
String[] from = {"eventName", "date"};
int[] to = {R.id.eventName, R.id.date};
SimpleAdapter simpleAdapter = new SimpleAdapter (
getActivity(),convertToWordArrayList(jsonStr), R.layout.listview_layout,from,to);
simpleAdapter.notifyDataSetChanged();
listView.setAdapter(simpleAdapter);
}
private ArrayList<HashMap<String, ActivityInfo>> convertToWordArrayList(String jsonStr){
JSONObject jsonObject ;
ArrayList<HashMap<String, ActivityInfo>> arrayList = new ArrayList<HashMap<String, ActivityInfo>>();
try{
jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray=jsonObject.getJSONArray("article");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObjRow=jsonArray.getJSONObject(i);
ActivityInfo activityInfo =new ActivityInfo();
activityInfo.eventName = jsonObjRow.getString("eventName");
activityInfo.date = jsonObjRow.getString("date");
HashMap<String, String> map= new HashMap<String, ActivityInfo>();
map.put("eventName", activityInfo.eventName );
map.put("date", activityInfo.date);
JSONArray jsonArray2=jsonObjRow.getJSONArray("content");
for (int j=0;j<jsonArray2.length();j++) {
JSONObject jsonObjRow2 = jsonArray2.getJSONObject(j);
activityInfo.review = jsonObjRow2.getString("review");
}
arrayList.add(activityInfo);
}
}catch (JSONException e){
e.printStackTrace();
}
return arrayList;
}
ActivityInfo class (using the serializable to got the result )
public class ActivityInfo implements Serializable {
String eventName;
String date ;
public void setEventName(String eventName){
this.eventName =eventName ;
}
public String toString(){
return this.eventName;
}
}
Json Response is no problem
{
"article":[
{
"activityId":"5c5d8addd404c",
"eventName":"running",
"date":"2019-02-08",
"content":[
{
"review":"you there"
},
{
"review":"please go away"
},
]
},
{
"activityId":"5c5d8b318df62",
"eventName":"basketball",
"date":"2019-02-13",
"content":[
{
"review":"confirm again"
}
]
},
{
"activityId":"5c5d8b9308018",
"eventName":"playing",
"date":"2019-02-16",
"content":[
{
"review":"provid of you"
}
]
}
]
}
I totally do it like this:
public class menuCreation()
{
public string Category { get; set; }
public string ItemName { get; set; }
public string Price { get; set; }
public string FileName { get; set; }
public menuCreation[] Arr { get; set; }
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string json = (reader.ReadToEnd());
List<menuCreation> items = JsonConvert.DeserializeObject<List<menuCreation>>(json);
Arr = items.ToArray();
}
menuCreation mc = new menuCreation();
foreach (var item in mc.Arr)
{
PictureBox pb = new PictureBox();
pb.Tag = item.ItemName;
pb.Name = item.Price;
}
You can see, I reach itemName with class object.So, you can add listview with this method.
This is your Model Class..
ActivityInfo.java
public class ActivityInfo implements Serializable {
String eventName;
String date;
public void setEventName(String eventName){
this.eventName = eventName ;
}
public String getEventName(){
return this.eventName;
}
public void setDate(String date){
this.date = date;
}
public String getDate(){
return date;
}
}
This will be your final errorfree code..
private void displayArrayList(String jsonStr){
String[] from = {"eventName", "date"};
int[] to = {R.id.eventName, R.id.date};
SimpleAdapter simpleAdapter = new SimpleAdapter (
getActivity(),convertToWordArrayList(jsonStr), R.layout.listview_layout,from,to);
simpleAdapter.notifyDataSetChanged();
listView.setAdapter(simpleAdapter);
}
private ArrayList<HashMap<String,String>> convertToWordArrayList(String jsonStr){
JSONObject jsonObject;
ArrayList<HashMap<String,String>> arrayList = new ArrayList();
try{
jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray=jsonObject.getJSONArray("article");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObjRow=jsonArray.getJSONObject(i);
HashMap<String,String> hashMap=new HashMap<>();//create a hashmap to store the data in key value pair
hashMap.put("eventName",jsonObjRow.getString("eventName"));
hashMap.put("date",jsonObjRow.getString("date"));
JSONArray jsonArray2=jsonObjRow.getJSONArray("content");
/*If you want to get Content Reviews from Json, you need to make another attributes like Content in ActivityInfo Class*/
arrayList.add(hashmap);
}
}catch (JSONException e){
e.printStackTrace();
}
return arrayList;
}