I need help with this code i can't get a good count with the relation
this is the class for map:
package primero;
// Generated 03-mar-2015 8:46:59 by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
/**
* Estudiantes generated by hbm2java
*/
public class Estudiantes implements java.io.Serializable {
private String dni;
private Estudiantes estudiantes;
private String nombre;
private String direccion;
private String poblacion;
private String telefono;
private Set<Estudiantes> estudianteses = new HashSet<Estudiantes>(0);
private Set<Cursos> cursoses = new HashSet<Cursos>(0);
public Estudiantes() {
}
public Estudiantes(String dni) {
this.dni = dni;
}
public Estudiantes(String dni, Estudiantes estudiantes, String nombre,
String direccion, String poblacion, String telefono,
Set<Estudiantes> estudianteses, Set<Cursos> cursoses) {
this.dni = dni;
this.estudiantes = estudiantes;
this.nombre = nombre;
this.direccion = direccion;
this.poblacion = poblacion;
this.telefono = telefono;
this.estudianteses = estudianteses;
this.cursoses = cursoses;
}
public String getDni() {
return this.dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public Estudiantes getEstudiantes() {
return this.estudiantes;
}
public void setEstudiantes(Estudiantes estudiantes) {
this.estudiantes = estudiantes;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDireccion() {
return this.direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getPoblacion() {
return this.poblacion;
}
public void setPoblacion(String poblacion) {
this.poblacion = poblacion;
}
public String getTelefono() {
return this.telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public Set<Estudiantes> getEstudianteses() {
return this.estudianteses;
}
public void setEstudianteses(Set<Estudiantes> estudianteses) {
this.estudianteses = estudianteses;
}
public Set<Cursos> getCursoses() {
return this.cursoses;
}
public void setCursoses(Set<Cursos> cursoses) {
this.cursoses = cursoses;
}
}
package primero;
// Generated 03-mar-2015 8:46:59 by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
/**
* Cursos generated by hbm2java
*/
public class Cursos implements java.io.Serializable {
private int codCurso;
private String nombre;
private String profesor1;
private String profesor2;
private String profesor3;
private Set<Estudiantes> estudianteses = new HashSet<Estudiantes>(0);
public Cursos() {
}
public Cursos(int codCurso) {
this.codCurso = codCurso;
}
public Cursos(int codCurso, String nombre, String profesor1,
String profesor2, String profesor3, Set<Estudiantes> estudianteses) {
this.codCurso = codCurso;
this.nombre = nombre;
this.profesor1 = profesor1;
this.profesor2 = profesor2;
this.profesor3 = profesor3;
this.estudianteses = estudianteses;
}
public int getCodCurso() {
return this.codCurso;
}
public void setCodCurso(int codCurso) {
this.codCurso = codCurso;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getProfesor1() {
return this.profesor1;
}
public void setProfesor1(String profesor1) {
this.profesor1 = profesor1;
}
public String getProfesor2() {
return this.profesor2;
}
public void setProfesor2(String profesor2) {
this.profesor2 = profesor2;
}
public String getProfesor3() {
return this.profesor3;
}
public void setProfesor3(String profesor3) {
this.profesor3 = profesor3;
}
public Set<Estudiantes> getEstudianteses() {
return this.estudianteses;
}
public void setEstudianteses(Set<Estudiantes> estudianteses) {
this.estudianteses = estudianteses;
}
}
this is the ejercise with the problem
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import primero.*;
public class Main {
public static void main(String[] args) {
//BufferedReader entrada=new BufferedReader(new InputStreamReader(System.in));
SessionFactory sesion = SessionFactoryUtil.getSessionFactory();
Session session = sesion.openSession();
//Transaction tx = session.beginTransaction();
try{
/*
System.out.println("Introduce el codigo del cliente: ");
short num=Short.parseShort(entrada.readLine());
System.out.println("\nDATOS DEL CLIENTE: "+num+"\n");
Clientes cliente = new Clientes();
cliente=(Clientes)session.load(Clientes.class, num);
*/
System.out.println("-------------------------------------------------------");
Estudiantes estu = new Estudiantes();
Query q = session.createQuery("from Estudiantes");
List <Estudiantes> lista = q.list();
Iterator <Estudiantes> iter = lista.iterator();
while(iter.hasNext()){
estu = iter.next();
System.out.println("Dni: "+estu.getDni()+", "+estu.getNombre());
System.out.println("Direccion: "+estu.getDireccion());
System.out.println("Representante: "+estu.getDni()+", "+estu.getNombre());
long count = (long) session.createQuery("select count(*) from Cursos where estudianteses="+estu.getEstudianteses()).uniqueResult();
System.out.println("Numero de cursos: "+count);
//===============================================================
Cursos curs=new Cursos();
Query q1 = session.createQuery("from Cursos");
List <Cursos> lista1 = q1.list();
Iterator <Cursos> iter1 = lista1.iterator();
while(iter1.hasNext()){
curs = iter1.next();
System.out.println(" "+curs.getCodCurso()+" ==> "+curs.getNombre()+": "+curs.getProfesor1()+", "+curs.getProfesor2()+", "+curs.getProfesor3());
}
System.out.println("-------------------------------------------------------");
}
}
catch(ObjectNotFoundException e){
System.out.println("No existe el cliente");
//e.printStackTrace();
}
catch(NullPointerException e){
System.out.println("Los datos son nulos");
//e.printStackTrace();
}
catch(NumberFormatException e){
System.out.println("El numero introducido no es valido");
//e.printStackTrace();
}
//tx.commit();
session.close();
System.exit(0);
}
}
I can't print all the studients for the course. I need help. Thanks.
Set lines = new HashSet(10000); // maybe should be bigger
String line;
This following line should be changed from
long count = (long) session.createQuery("select count(*) from Cursos where estudianteses="+estu.getEstudianteses()).uniqueResult();
to this
long count = (long) session.createSQlQuery("select count(*) from Cursos where estudianteses="+estu.getEstudianteses()).uniqueResult();
It has to be createSqlQuery()
Related
I want to make a method that tells me who is the oldest person in the ArrayList and who is the youngest person. The method will receive the arraylist that i want to apply the method, i have 3 in my code, each one is an contact list.
The method is suppose to return the name of the person, but i don't know how to do it. Familia, Profissional and Amigos are my arraylists and "idade" = age and "nome" = name.
package com.company;
public class Contato {
public String nome;
public int idade;
public String sexo;
public String profissao;
public String telefone;
public String email;
public Contato(String nome, int idade, String sexo, String profissao, String telefone, String email) {
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
this.profissao = profissao;
this.telefone = telefone;
this.email = email;
}
#Override
public String toString() {
return "" +
nome + ',' +
idade + " anos de idade, " +
"do sexo " + sexo + ',' +
profissao + ',' +
" telefone nÂș " + telefone + ", " +
"e-mail:" + email;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getProfissao() {
return profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.company;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class GestaoContatos extends Contato {
ArrayList<Contato> Familia = new ArrayList();
ArrayList<Contato> Amigos = new ArrayList();
ArrayList<Contato> Profissional = new ArrayList();
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
}
public void adicionaContato(String nomeAgenda, Contato contato) {
if( nomeAgenda == "Familia"){
Familia.add(contato);
} else
if(nomeAgenda == "Amigos"){
Amigos.add(contato);
} else
if(nomeAgenda == "Profissional") {
Profissional.add(contato);
} else
System.out.println("IndispnĂvel");
}
public void eliminaContato(String nomeContato) {
for(int i = 0; i < Familia.size(); i++) {
if(getFamilia().contains(nomeContato)) {
Familia.remove(nomeContato);
}
}
}
public void printaLista(String nomeAgenda){
if(nomeAgenda.equals("Familia")) {
Familia.forEach(System.out::println);
}
if(nomeAgenda.equals("Amigos")) {
Amigos.forEach(System.out::println);
}
if(nomeAgenda.equals("Profissional")) {
Profissional.forEach(System.out::println);
}
else {
throw new RuntimeException("Opcao invalida");
}
}
public void tooString() {
var contatos = new ArrayList<Contato>();
Familia.forEach(it -> contatos.add(it));
Amigos.forEach(it -> contatos.add(it));
Profissional.forEach(it -> contatos.add(it));
System.out.println(contatos.toString());
}
public void olderPerson(String nomeAgenda){
int i = 0;
if (nomeAgenda.equals("Amigos")) {
for (i = 0; Familia.size(); i++) {
Familia.stream().filter();
}
}
}
public void geraListaBinaria() throws IOException {
var file = new File("C:\\Users\\Jorge Luiz\\Desktop\\contatos.txt");
var writer = new FileWriter(file.getName());
writer.write(this.getProfissional().toString());
writer.write(this.getFamilia().toString());
writer.write(this.getProfissional().toString());
writer.close();
}
public ArrayList<Contato> getFamilia() {
return Familia;
}
public void setFamilia(ArrayList<Contato> familia) {
Familia = familia;
}
public ArrayList<Contato> getAmigos() {
return Amigos;
}
public void setAmigos(ArrayList<Contato> amigos) {
Amigos = amigos;
}
public ArrayList<Contato> getProfissional() {
return Profissional;
}
public void setProfissional(ArrayList<Contato> profissional) {
Profissional = profissional;
}
}
If you want to return oldest person in one list:
public Contato oldestPerson(String nomeAgenda){
return Familia.stream()
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}
For all lists you can do:
public Contato oldestPerson(){
return Stream.of(Familia, Amigos, Profissional)
.flatMap(Collection::stream) // flatting to one long stream
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade))
.get();
}
EDIT
Based on the comment, we should change a couple of things to achieve what you want. First, we should define a Map<String, List<Contato>> and populate it in the constructor:
private Map<String, List<Contato>> contatoGroups;
private static final String familiaKey = "Familia";
private static final String amogisKey = "Amigos";
private static final String profissionalKey = "Profissional";
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
contatoGroups.put(familiaKey, new ArrayList<>());
contatoGroups.put(amogisKey, new ArrayList<>());
contatoGroups.put(profissionalKey, new ArrayList<>());
}
(Consider using enum instead of String as key in the map)
Then wherever you want to get a group, for example: Familia, you should do:
List<Contato> contatoes = contatoGroups.get(familiaKey);
And then we should change the oldestPerson() like this:
public Contato oldestPerson(String nomeAgenda){ // nomeAgenda could be "Familia", "Amigos"...
List<Contato> selectedGroup = contatoGroups.get(nomeAgenda);
return selectedGroup.stream()
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}
I'm using room for my android database. here i have a many to many relationship between Customer and ServiceProvider class i used this tutorial to do it but after compiling i received this error:
/home/omid/IntelliJIDEAProjects/Accounting/app/build/generated/ap_generated_sources/debug/out/com/omidmsl/accounting/db/CustomerDAO_Impl.java:69: error: incompatible types: cannot be converted to int
if (!_cursor.isNull(null)) {
and it is mentioning to this code CustomerDAO_Impl.java (compiler created this):
package com.omidmsl.accounting.db;
import android.database.Cursor;
import androidx.collection.ArrayMap;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.util.CursorUtil;
import androidx.room.util.DBUtil;
import androidx.room.util.StringUtil;
import com.omidmsl.accounting.models.Business;
import com.omidmsl.accounting.models.Customer;
import com.omidmsl.accounting.models.serviceprovider.CustomerOfServiceProvider;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import java.lang.SuppressWarnings;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
#SuppressWarnings({"unchecked", "deprecation"})
public final class CustomerDAO_Impl implements CustomerDAO {
private final RoomDatabase __db;
public CustomerDAO_Impl(RoomDatabase __db) {
this.__db = __db;
}
#Override
public List<Customer> getCustomers() {
final String _sql = "SELECT * FROM Customer";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfCustomerName = CursorUtil.getColumnIndexOrThrow(_cursor, "customerName");
final int _cursorIndexOfPhoneNumber = CursorUtil.getColumnIndexOrThrow(_cursor, "phoneNumber");
final List<Customer> _result = new ArrayList<Customer>(_cursor.getCount());
while(_cursor.moveToNext()) {
final Customer _item;
_item = new Customer();
final String _tmpCustomerName;
_tmpCustomerName = _cursor.getString(_cursorIndexOfCustomerName);
_item.setCustomerName(_tmpCustomerName);
final String _tmpPhoneNumber;
_tmpPhoneNumber = _cursor.getString(_cursorIndexOfPhoneNumber);
_item.setPhoneNumber(_tmpPhoneNumber);
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
#Override
public List<CustomerOfServiceProvider> getCustomersOfServiceProvider() {
final String _sql = "SELECT * FROM Customer";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
__db.assertNotSuspendingTransaction();
__db.beginTransaction();
try {
final Cursor _cursor = DBUtil.query(__db, _statement, true, null);
try {
final int _cursorIndexOfPhoneNumber = CursorUtil.getColumnIndexOrThrow(_cursor, "phoneNumber");
final ArrayMap<String, ArrayList<Customer>> _collectionCustomers = new ArrayMap<String, ArrayList<Customer>>();
while (_cursor.moveToNext()) {
if (!_cursor.isNull(null)) {
final String _tmpKey = _cursor.getString(null);
ArrayList<Customer> _tmpCustomersCollection = _collectionCustomers.get(_tmpKey);
if (_tmpCustomersCollection == null) {
_tmpCustomersCollection = new ArrayList<Customer>();
_collectionCustomers.put(_tmpKey, _tmpCustomersCollection);
}
}
}
_cursor.moveToPosition(-1);
__fetchRelationshipCustomerAscomOmidmslAccountingModelsCustomer(_collectionCustomers);
final List<CustomerOfServiceProvider> _result = new ArrayList<CustomerOfServiceProvider>(_cursor.getCount());
while(_cursor.moveToNext()) {
final CustomerOfServiceProvider _item;
final Business _tmpServiceProvider;
if (! (_cursor.isNull(_cursorIndexOfPhoneNumber))) {
_tmpServiceProvider = new Business();
final String _tmpPhoneNumber;
_tmpPhoneNumber = _cursor.getString(_cursorIndexOfPhoneNumber);
_tmpServiceProvider.setPhoneNumber(_tmpPhoneNumber);
} else {
_tmpServiceProvider = null;
}
ArrayList<Customer> _tmpCustomersCollection_1 = null;
if (!_cursor.isNull(null)) {
final String _tmpKey_1 = _cursor.getString(null);
_tmpCustomersCollection_1 = _collectionCustomers.get(_tmpKey_1);
}
if (_tmpCustomersCollection_1 == null) {
_tmpCustomersCollection_1 = new ArrayList<Customer>();
}
_item = new CustomerOfServiceProvider();
_item.setServiceProvider(_tmpServiceProvider);
_item.setCustomers(_tmpCustomersCollection_1);
_result.add(_item);
}
__db.setTransactionSuccessful();
return _result;
} finally {
_cursor.close();
_statement.release();
}
} finally {
__db.endTransaction();
}
}
#Override
public List<Customer> getCustomer(final String cName) {
final String _sql = "SELECT * FROM Customer WHERE customerName = ?";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
int _argIndex = 1;
if (cName == null) {
_statement.bindNull(_argIndex);
} else {
_statement.bindString(_argIndex, cName);
}
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfCustomerName = CursorUtil.getColumnIndexOrThrow(_cursor, "customerName");
final int _cursorIndexOfPhoneNumber = CursorUtil.getColumnIndexOrThrow(_cursor, "phoneNumber");
final List<Customer> _result = new ArrayList<Customer>(_cursor.getCount());
while(_cursor.moveToNext()) {
final Customer _item;
_item = new Customer();
final String _tmpCustomerName;
_tmpCustomerName = _cursor.getString(_cursorIndexOfCustomerName);
_item.setCustomerName(_tmpCustomerName);
final String _tmpPhoneNumber;
_tmpPhoneNumber = _cursor.getString(_cursorIndexOfPhoneNumber);
_item.setPhoneNumber(_tmpPhoneNumber);
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
private void __fetchRelationshipCustomerAscomOmidmslAccountingModelsCustomer(final ArrayMap<String, ArrayList<Customer>> _map) {
final Set<String> __mapKeySet = _map.keySet();
if (__mapKeySet.isEmpty()) {
return;
}
// check if the size is too big, if so divide;
if(_map.size() > RoomDatabase.MAX_BIND_PARAMETER_CNT) {
ArrayMap<String, ArrayList<Customer>> _tmpInnerMap = new ArrayMap<String, ArrayList<Customer>>(androidx.room.RoomDatabase.MAX_BIND_PARAMETER_CNT);
int _tmpIndex = 0;
int _mapIndex = 0;
final int _limit = _map.size();
while(_mapIndex < _limit) {
_tmpInnerMap.put(_map.keyAt(_mapIndex), _map.valueAt(_mapIndex));
_mapIndex++;
_tmpIndex++;
if(_tmpIndex == RoomDatabase.MAX_BIND_PARAMETER_CNT) {
__fetchRelationshipCustomerAscomOmidmslAccountingModelsCustomer(_tmpInnerMap);
_tmpInnerMap = new ArrayMap<String, ArrayList<Customer>>(RoomDatabase.MAX_BIND_PARAMETER_CNT);
_tmpIndex = 0;
}
}
if(_tmpIndex > 0) {
__fetchRelationshipCustomerAscomOmidmslAccountingModelsCustomer(_tmpInnerMap);
}
return;
}
StringBuilder _stringBuilder = StringUtil.newStringBuilder();
_stringBuilder.append("SELECT `Customer`.`customerName` AS `customerName`,`Customer`.`phoneNumber` AS `phoneNumber`,_junction.`businessName` FROM `Service` AS _junction INNER JOIN `Customer` ON (_junction.`customerName` = `Customer`.`customerName`) WHERE _junction.`businessName` IN (");
final int _inputSize = __mapKeySet.size();
StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
_stringBuilder.append(")");
final String _sql = _stringBuilder.toString();
final int _argCount = 0 + _inputSize;
final RoomSQLiteQuery _stmt = RoomSQLiteQuery.acquire(_sql, _argCount);
int _argIndex = 1;
for (String _item : __mapKeySet) {
if (_item == null) {
_stmt.bindNull(_argIndex);
} else {
_stmt.bindString(_argIndex, _item);
}
_argIndex ++;
}
final Cursor _cursor = DBUtil.query(__db, _stmt, false, null);
try {
final int _itemKeyIndex = 2; // _junction.businessName;
if (_itemKeyIndex == -1) {
return;
}
final int _cursorIndexOfCustomerName = CursorUtil.getColumnIndex(_cursor, "customerName");
final int _cursorIndexOfPhoneNumber = CursorUtil.getColumnIndex(_cursor, "phoneNumber");
while(_cursor.moveToNext()) {
if (!_cursor.isNull(_itemKeyIndex)) {
final String _tmpKey = _cursor.getString(_itemKeyIndex);
ArrayList<Customer> _tmpRelation = _map.get(_tmpKey);
if (_tmpRelation != null) {
final Customer _item_1;
_item_1 = new Customer();
if (_cursorIndexOfCustomerName != -1) {
final String _tmpCustomerName;
_tmpCustomerName = _cursor.getString(_cursorIndexOfCustomerName);
_item_1.setCustomerName(_tmpCustomerName);
}
if (_cursorIndexOfPhoneNumber != -1) {
final String _tmpPhoneNumber;
_tmpPhoneNumber = _cursor.getString(_cursorIndexOfPhoneNumber);
_item_1.setPhoneNumber(_tmpPhoneNumber);
}
_tmpRelation.add(_item_1);
}
}
}
} finally {
_cursor.close();
}
}
}
and here is the rest of my codes:
Customer.java:
package com.omidmsl.accounting.models;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity(tableName = "Customer")
public class Customer {
public static final String KEY_NAME = "customer_name";
public static final String KEY_PHONE_NUMBER = "phone_number";
#NonNull
#PrimaryKey
private String customerName;
private String phoneNumber;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
CustomerDAO.java:
package com.omidmsl.accounting.db;
import androidx.room.Dao;
import androidx.room.Query;
import androidx.room.Transaction;
import com.omidmsl.accounting.models.Customer;
import com.omidmsl.accounting.models.serviceprovider.CustomerOfServiceProvider;
import java.util.List;
#Dao
public interface CustomerDAO {
#Query("SELECT * FROM Customer")
public List<Customer> getCustomers();
#Transaction
#Query("SELECT * FROM Customer")
public List<CustomerOfServiceProvider> getCustomersOfServiceProvider();
#Query("SELECT * FROM Customer WHERE customerName = :cName")
public List<Customer> getCustomer(String cName);
}
Business.java:
package com.omidmsl.accounting.models;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.*;
#Entity(tableName = "Business")
public class Business {
public static final String KEY_TYPE = "type";
public static final String KEY_NAME = "business_name";
public static final String KEY_PHONE_NUMBER = "phone_number";
private int type;
#PrimaryKey
#NonNull
private String businessName;
private String phoneNumber;
#Ignore
private long costs;
#Ignore
private long buys;
public Business(int type) {
this.type = type;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Business() {
businessName = "";
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public long getCosts() {
return costs;
}
public void setCosts(long costs) {
this.costs = costs;
}
public long getBuys() {
return buys;
}
public void setBuys(long buys) {
this.buys = buys;
}
}
ServiceProviderDAO.java:
package com.omidmsl.accounting.db;
import androidx.room.Dao;
import androidx.room.Query;
import androidx.room.Transaction;
import com.omidmsl.accounting.models.serviceprovider.ServiceProviderOfCustomer;
import java.util.List;
#Dao
public interface ServiceProviderDAO {
#Transaction
#Query("SELECT * FROM Business")
public List<ServiceProviderOfCustomer> getServiceProvidersOfCustomer();
}
CustomersOfServiceProvider.java:
package com.omidmsl.accounting.models.serviceprovider;
import androidx.room.*;
import com.omidmsl.accounting.models.Business;
import com.omidmsl.accounting.models.Customer;
import java.util.List;
public class CustomerOfServiceProvider {
#Embedded
private Business serviceProvider;
#Relation(
parentColumn = "businessName",
entityColumn = "customerName",
associateBy = #Junction(Service.class)
)
private List<Customer> customers;
public Business getServiceProvider() {
return serviceProvider;
}
public void setServiceProvider(Business serviceProvider) {
this.serviceProvider = serviceProvider;
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
please help me
This has nothing to do with the problem described by the original poster, but if you got here via Google search, here is something that might be relevant.
I recently updated Room from 2.4.x to 2.5.x and encountered error: incompatible types: <null> cannot be converted to int.
I had to replace androidx.room.OnConflictStrategy.REPLACE with androidx.room.OnConflictStrategy.Companion.REPLACE to fix.
thank you #ianhanniballake. problem solved!.
in CustomerDAO file i found this problem:
#Transaction
#Query("SELECT * FROM Customer")
public List<CustomerOfServiceProvider> getCustomersOfServiceProvider();
type of this list must be ServiceProvidersOfCustomer:
#Transaction
#Query("SELECT * FROM Customer")
public List<ServiceProviderOfCustomer> getServiceProvidersOfCustomer();
Like #solamour I also upgraded to room 2.5.x but my problem was this line:
#ColumnInfo(name = "elapsedTime", typeAffinity = INTEGER, defaultValue = "0")
And I changed it to:
#ColumnInfo(name = "elapsedTime", typeAffinity = ColumnInfo.Companion.INTEGER, defaultValue = "0")
I'm new at this.
I have something like this:
{
libri.get(i).setUtenteAssegnato(**Utente**); How do i create an Utente instance with user inputs?
}
Utente class:
package Biblioteca;
public class Utente
{
private String nome;
private String cognome;
public Utente (String unNome, String unCognome)
{
this.nome=unNome;
this.cognome=unCognome;
}
public String getNome()
{
return nome;
}
public String getCognome()
{
return cognome;
}
public String toString()
{
return (this.nome + this.cognome);
}
}
This is the Libro class, with setUtenteAssegnato method:
package Biblioteca;
public class Libro
{
private int codice;
private String titolo;
private Utente utenteAssegnato;
public Libro (int unCodice, String unTitolo)
{
this.codice = unCodice;
this.titolo = unTitolo;
this.utenteAssegnato = null;
}
public Utente getUtenteAssegnato()
{
return this.utenteAssegnato;
}
public void setUtenteAssegnato(Utente utenteAssegnato)
{
this.utenteAssegnato = utenteAssegnato;
}
public int getCodice()
{
return codice;
}
public String getTitolo()
{
return titolo;
}
public String toString()
{
return (this.codice + this.titolo + this.utenteAssegnato);
}
}
This is the class i'm having problem with:
package Biblioteca;
import java.util.ArrayList;
import java.util.List;
public class Biblioteca
{
List<Libro> libri = new ArrayList<Libro>();
List<Utente> utenti = new ArrayList<Utente>();
public Biblioteca ()
{
}
public void aggiungiUtente (String unNome, String unCognome)
{
Utente u1 = new Utente (unNome, unCognome);
utenti.add(u1);
}
public void aggiungiLibro(int unCodice, String unTitolo)
{
Libro l1 = new Libro (unCodice, unTitolo);
libri.add(l1);
}
public void creaPrestito (int unCodice, String unCognome)
{
boolean codiceTrovato = false;
boolean cognomeTrovato = false;
int i;
int j;
for (i=0; i<libri.size(); i++)
{
if (libri.get(i).getCodice() == (unCodice))
{
System.out.println("Codice trovato. ");
codiceTrovato = true;
}
else
{
System.out.println("Codice non trovato. ");
}
}
for (j=0; j<utenti.size(); j++)
{
if (utenti.get(j).getCognome().equals(unCognome))
{
System.out.println("Utente trovato. ");
cognomeTrovato = true;
}
else
{
System.out.println("Utente non trovato. ");
}
}
if (codiceTrovato && cognomeTrovato)
{
**libri.get(i).setUtenteAssegnato(Utente);**
}
}
public String toString()
{
String stampa = ", ";
for(Libro d : libri)
{
stampa += d.toString();
}
return stampa;
}
}
Basically, i don't know how to set the object in the arraylist (i) position from input (it should be 2 strings, right?)
Do i have to create another instance of Utente?
LabServiceManagement.Java
package com.bean;
public class LabServiceManagement {
private String lspName;
private String address;
private int zipcode;
private String state;
private String city;
private String testName;
private int testCode;
private String testDescription;
private double costOfTest;
private String lab_home;
public String getLspName() {
return lspName;
}
public void setLspName(String lspName) {
this.lspName = lspName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public int getTestCode() {
return testCode;
}
public void setTestCode(int testCode) {
this.testCode = testCode;
}
public String getTestDescription() {
return testDescription;
}
public void setTestDescription(String testDescription) {
this.testDescription = testDescription;
}
public double getCostOfTest() {
return costOfTest;
}
public void setCostOfTest(double costOfTest) {
this.costOfTest = costOfTest;
}
public String getLab_home() {
return lab_home;
}
public void setLab_home(String lab_home) {
this.lab_home = lab_home;
}
}
DBUtility.java
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtility {
static final String driver = "oracle.jdbc.driver.OracleDriver";
static final String dbURL = "jdbc:oracle:thin:#172.26.132.40:1521:ORCLILP";
static final String dbUserName = "aja16core";
static final String dbPassword = "aja16core";
public static Connection getConnection()
{
Connection con=null;
try {
// load the JDBC-ODBC Bridge driver
Class.forName(driver);
// connect to db using DriverManager
con = DriverManager.getConnection(dbURL, dbUserName, dbPassword);
}
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
return con;
}
public static void closeResultSet(ResultSet rs) {
if(rs!= null)
{
try
{
rs.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
public static void closeStatement(PreparedStatement ps) {
if(ps!= null)
{
try
{
ps.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
public static void closeConnection(Connection con) {
if(con!= null)
{
try
{
con.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
}
LabServiceDAO.java
package com.dao;
import com.bean.LabServiceManagement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class LabServiceDAO {
public ArrayList<LabServiceManagement> searchcity(String city)
{
ArrayList<LabServiceManagement> result_list= new ArrayList<LabServiceManagement>();
Connection con=DBUtility.getConnection();
PreparedStatement ps=null;
ResultSet rs=null;
try
{
ps=con.prepareStatement("select * from LSP where CITY=? ");
ps.setString(1, city);
rs=ps.executeQuery();
while(rs.next())
{
String lspName=rs.getString("lspName");
String address=rs.getString("address");
int zipcode=rs.getInt("zipcode");
String state=rs.getString("state");
String testName=rs.getString("testName");
int testCode=rs.getInt("testCode");
String testDescription =rs.getString("testDescription");
double costOfTest=rs.getDouble("costOfTest");
String lab_home=rs.getString("lab_home");
LabServiceManagement l=new LabServiceManagement();
l.setLspName(lspName);
l.setAddress(address);
l.setZipcode(zipcode);
l.setState(state);
l.setCity(city);
l.setTestName(testName);
l.setTestCode(testCode);
l.setTestDescription(testDescription);
l.setCostOfTest(costOfTest);
l.setLab_home(lab_home);
result_list.add(l);
}
} catch (SQLException e)
{
e.printStackTrace();
}
finally
{
DBUtility.closeResultSet(rs);
DBUtility.closeStatement(ps);
DBUtility.closeConnection(con);
}
return result_list;
}
}
LabService.java
package com.service;
import java.util.ArrayList;
import com.bean.LabServiceManagement;
import com.dao.LabServiceDAO;
public class LabService {
public ArrayList<LabServiceManagement> searchcity(String city)
{
LabServiceDAO searchdao = new LabServiceDAO();
ArrayList<LabServiceManagement> result_list= searchdao.searchcity(city);
return result_list;
}
}
I have created table in SQL
I inserted few data
I coded for search city only, where I given mumbai which is already there in database, but result set is not coming
Can you please find the mistake, where I am gone wrong?
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
java.net.MalformedURLException: no protocol: "localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38
at java.net.URL.<init>(URL.java:567)
at java.net.URL.<init>(URL.java:464)
at java.net.URL.<init>(URL.java:413)
Malformed URL exception when reading data from url containing localhost.
Actually my program is as below
package bll.sap;
import java.net.MalformedURLException;
import utility.PropertyUtility;
public class GetActiveData
{
public static void main(String[] args) {
String sapURL = "";
try {
sapURL = PropertyUtility.getSapURL();
//Get Summary Data
SapDataSync sapDataSync = new SapDataSync();
//sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=false");
sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=E13F42EC5E38");
}
catch(MalformedURLException me)
{
me.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
AND
package bll.sap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import utility.Utility;
import com.google.code.morphia.Datastore;
import dal.GetMorphiaDB;
public class SapDataSync
{
private void saveSapTransaction(List<TransactionUnit> sapTransaction){
GetMorphiaDB morphia;
try {
morphia = GetMorphiaDB.getInstance();
Datastore ds = morphia.getDs();
ds.save(sapTransaction);
}catch (Exception e) {
e.printStackTrace();
}
}
private void createSapTransaction(String transactionJson){
JSONObject jsonObj = JSONObject.fromObject(transactionJson);
JSONArray transactionUnits = jsonObj.getJSONArray("TRANSACTION");
List<ActiveUnit> transactionList = new ArrayList<ActiveUnit>();
for(int i = 0; i < transactionUnits.size() ; i++){
JSONObject jsn = transactionUnits.getJSONObject(i);
JSONObject jsnFeed = transactionUnits.getJSONObject(i);
ActiveUnit transactionUnit = new ActiveUnit(
jsn.getString("listEditions"),
jsn.getString("listPackage"),
//Double.parseDouble(jsn.getString("YIELD")),
//Double.parseDouble(jsn.getString("QUANTITY")),
//Double.parseDouble(jsn.getString("VALUE")),
jsn.getString("referenceID")
//jsn.getString("PRICEGROUP"),
//jsn.getString("PAGE"),
//Utility.getCalendarTime(jsn.getString("PUBDATE"), "dd-MM-yyyy"),
//jsn.getString("CLIENTNAME"),
//jsn.getString("CLIENTCODE"),
// new Date().getTime(),
//jsn.getString("BOOKINGUNITNAME"),
//jsn.getString("BCCNAME"),
//jsn.getString("PAGENAME"),
// jsn.getString("PRICEGROUPNAME"),
// jsn.getString("ORDER"),
// jsn.getString("PAGE_LH_RH")
);
transactionList.add(transactionUnit);
System.out.println(transactionList);
}
System.out.println(transactionList.size());
if (transactionList.size() > 0) {
//saveSapTransaction(transactionList);
}
}
public void readTransactionJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
createSapTransaction(sb.toString());
} finally {
is.close();
}
}
}
AND
package bll.sap;
import java.io.Serializable;
import java.util.Date;
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
#Entity("SapTransaction")
public class ActiveUnit implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private ObjectId id;
private Long tilCreationDate;
private String clientName;
private String clientCode;
private String listEditions;
private Long date;
private String listPackage;
private String bookingUnitName;
private String referenceID;
private String bccName;
private String page;
private String pageName;
private String priceGroup;
private String pgName;
private Double yield;
private Double qty;
private Double value;
private String order;
private String pageType;
public ActiveUnit() {
}
public ActiveUnit(String listEdtions, String listPackage, /*Double yield,
Double qty, Double value,*/ String referenceID /*, String priceGroup,
String page, Long date,String clientName,
String clientCode,Long tilCreationDate,String bookingUnitName,String bccName,String pageName,String pgName,String order,String pageType*/) {
this.listEditions = listEdtions;
this.listPackage = listPackage;
//this.yield = yield;
//this.qty = qty;
//this.value = value;
this.referenceID = referenceID;
//this.priceGroup = priceGroup;
//this.page = page;
//this.date = date;
//this.clientName = clientName;
//this.clientCode = clientCode;
//this.tilCreationDate = tilCreationDate;
//this.setBookingUnitName(bookingUnitName);
//this.bccName = bccName;
//this.pageName = pageName;
//this.pgName = pgName;
//this.order = order;
//this.pageType = pageType;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientCode() {
return clientCode;
}
public void setClientCode(String clientCode) {
this.clientCode = clientCode;
}
public void setId(ObjectId id) {
this.id = id;
}
public ObjectId getId() {
return id;
}
public void setTilCreationDate(Long tilCreationDate) {
this.tilCreationDate = tilCreationDate;
}
public Long getTilCreationDate() {
return tilCreationDate;
}
public String getreferenceID() {
return referenceID;
}
public void setreferenceID(String referenceID) {
this.referenceID = referenceID;
}
public String getPriceGroup() {
return priceGroup;
}
public void setPriceGroup(String priceGroup) {
this.priceGroup = priceGroup;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
public String getListEditions() {
return listEditions;
}
public void setVertical(String listEditions) {
this.listEditions = listEditions;
}
public String getListPackage() {
return listPackage;
}
public void setListPackage(String listPackage) {
this.listPackage = listPackage;
}
public Double getYield() {
return yield;
}
public void setYield(Double yield) {
this.yield = yield;
}
public Double getQty() {
return qty;
}
public void setQty(Double qty) {
this.qty = qty;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public void setBookingUnitName(String bookingUnitName) {
this.bookingUnitName = bookingUnitName;
}
public String getBookingUnitName() {
return bookingUnitName;
}
public String getBccName() {
return bccName;
}
public void setBccName(String bccName) {
this.bccName = bccName;
}
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getPgName() {
return pgName;
}
public void setPgName(String pgName) {
this.pgName = pgName;
}
#Override
public String toString() {
String unit = "{ " +
//"ClientCode: " + this.clientCode+
//",TILCreation Date: " + new Date(this.tilCreationDate)+
//",ClientName: "+ this.clientName+
"listEditions: " + this.listEditions+
",listPackage: "+ this.listPackage+
//",BookingUnitName: "+ this.bookingUnitName+
//",Yield: " + this.yield+
//",QTY: " + this.qty+
//",Value: " + this.value+
",referenceID: " + this.referenceID+
//",Price Group: " + this.priceGroup+
//",BCCName: " + this.bccName+
//",PageName: " + this.pageName+
//",PriceGroupName: " + this.pgName+
//",Page: " + this.page+
//",PageType: " + this.pageType+
//",Order: " + this.order+
//",PublishDate: " + new Date(this.date) +
" }";
return unit;
}
public void setOrder(String order) {
this.order = order;
}
public String getOrder() {
return order;
}
public void setPageType(String pageType) {
this.pageType = pageType;
}
public String getPageType() {
return pageType;
}
}
First, make sure you have the protocol set for your request.
Second, make sure that the String containing the URL is URL-encoded. I.e. the URL doesn't have any spaces and other special characters - these should be encoded (space is %20 etc).
Given that the two above are met, your program should not throw an exception from the java.net.URL class.
Looking at the exception above, you'll just have to set the protocol (http://), but do make sure that you encode your URL address strings properly or else you'll get exceptions from other parts of your program.
Also, adding http:// to the following string will also result in a MalformedURLException:
"localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38 as your URL would contain special characters (" in this case) which would need to be encoded.
To provide a valid URL you should make sure that the quotes are stripped from your URL's server and path segments areas:
localhost/uatpw/ActiveTransaction?isx=E13F42EC5E38. Prepeding http:// to this will result in a valid URL.
You are missing the protocol (e.g. http://) in front of localhost.
The welformed URL could be http://localhost/uatpw/ActiveTransaction
This is not a question. What are you trying to do?
But otherwise, "localhost/uatpw/ActiveTransaction" is not a valid URL. An url must start with a protocol (http, https, ftp, etc.).
You should try with:
http://localhost/uatpw/ActiveTransaction