I'm trying to check if my arraylist has an object with long name with the following code:
public static boolean containsName(Collection<MyObject> c, long name) {
for(MyObject o : c) {
if(o != null && o.getName() == name) { //name is a long
return true;
}
}
return false;
}
MyObject:
public class MyObject extends SugarRecord {
Long fk_id_specs;
String url;
String timestamp;
int status;
int time;
public MyObject(Long fk_id_specs, String url, String timestamp,int status,int time) {
this.fk_id_specs = fk_id_specs;
this.url = url;
this.timestamp = timestamp;
this.status = status;
this.time = time;
}
I'm getting the collection from the database by a libary with:
List<MyObject> sp = MyObject.listAll(MyObject.class);
The list is filled properly, already checked that.
The problem is: it's always returning false, any suggestions?
Assuming that o.getName() is a String. You must compare Strings like this:
String o_name = o.getName();
String str_name = String.valueOf(name); // Convert the long to String
boolean is_equal = o_name.equals(str_name);
Related
Helper Class
public class HomeScreenChatsHelper implements Comparable {
private String ID;
private String Name;
private String Image;
private String From;
private String Seen;
private String LastMessage;
private String LastMessageTime;
public HomeScreenChatsHelper(){
}
public HomeScreenChatsHelper(String id, String name, String image, String from, String seen, String lastmessage, String lastMessageTime) {
this.ID=id;
this.Name = name;
this.Image = image;
this.From = from;
this.Seen = seen;
this.LastMessage = lastmessage;
this.LastMessageTime = lastMessageTime;
}
public String getID() {
return ID;
}
public void setID(String id) {
ID = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getMessage() {
return LastMessage;
}
public void setMessage(String message) {
LastMessage = message;
}
public String getTime() {
return LastMessageTime;
}
public void setTime(String time) {
LastMessageTime = time;
}
public String getFrom() {
return From;
}
public void setFrom(String from) {
From = from;
}
public String getSeen() {
return Seen;
}
public void setSeen(String seen) {
Seen = seen;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public int compareTo(Object comparestu) {
long compareage= Long.parseLong(((HomeScreenChatsHelper)comparestu).getTime());
long a = Long.parseLong(LastMessageTime);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
}
return Long.compare(a,compareage);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HomeScreenChatsHelper)) return false;
HomeScreenChatsHelper that = (HomeScreenChatsHelper) o;
return getID().equals(that.getID());
}
#Override
public int hashCode() {
return getID().hashCode();
}
Activity
for(HomeScreenChatsHelper str : mChats) {
if (str.getID().equals(ID)) {
mChats.remove(ID);
break;
}
}
There are a ton of tutorials on how to do it and I've spent the past week looking for a solution and I still don't have it. Is there anyway I can remove an whole object by just specifying just the ID? I wont have the values of all the other fields so I just want to remove a particular object by its ID. Also I cant use the clear option because I need the other data. So can someone help me out please?
With the present code nothing happens. No errors but doesn't work
By using java-8 you can filter the list, result will be the List<HomeScreenChatsHelper> that does have HomeScreenChatsHelper with same id
List<HomeScreenChatsHelper> mChats = new ArrayList<>();
//filter
List<HomeScreenChatsHelper> result = mChats.stream()
.filter(str->!str.getId().equals(Id)).
.collect(Collectors.toList());
Or by using Iterator
// Iterator.remove()
Iterator itr = mChats.iterator();
while (itr.hasNext())
{
HomeScreenChatsHelper x = itr.next();
if (x.getId().equals(Id)) }
itr.remove();
}
}
Your question is quite unclear. is mChats a List containing HomeScreenChatsHelper objects?
I assume so. If this is the case, then you can change your foreach loop into the normal loop
//Assuming mChats is List e.g ArrayList
for (int i = 0; mChats.size(); i++){
if (mChats.get(i).getID().equals(ID)) {
mChats.remove(i);
break;
}
}
The easiest way in Java 8 or later is with Collection#removeIf:
mChats.removeIf(str -> str.getID().equals(ID));
By the way, the convention in Java is for fields to begin with a lowercase letter.
in this case, i want to show Json to an response page in java hibernate, query method from DAO like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("FROM TransactionQR tr, Batch b, Terminal t, User_Smartphone us, Merchant mc WHERE tr.batch = b.id AND b.user_smartphone = us.id AND b.terminal = t.id AND t.merchant = mc.id AND state = '1' ").list();
}
then in servlet class i try to convert the list into json using Json object and json array then write in response like this:
int start = 0;
String jsonResult = null;
JSONObject jo=new JSONObject();
HttpServletRequest request = context.getRequest();
HttpServletResponse response = context.getResponse();
HttpSession session = context.getSession();
DB db = getDB(context);
//JSONObject jo = new JSONObject();
QRTransactionDao QR = new QRTransactionDao(db);
//Gson objGson = new GsonBuilder().setPrettyPrinting().create();
//String json = objGson.toJson(QR.getAllTransaction());
//System.out.println(json);
List<TransactionQR> str = QR.getAllTransaction();
JSONArray array = new JSONArray();
for(TransactionQR tr : str){
JSONObject str3 = new JSONObject();
str3.put("amount", tr.getAmount());
context.put("jsoncontent", jsonResult);
array.add(str3);
}
jo.put("status", "ok");
jo.put("dataqr", array);
jsonResult=jo.toString();
response.setContentType("application/json");
response.getWriter().print(jsonResult);
but i got the error on syntax in this line loop:
for(TransactionQR tr : str){
the error like this:
[Ljava.lang.Object; cannot be cast to Transaction
here the model Transaction:
package id.co.keriss.consolidate.ee;
import java.io.Serializable;
import java.util.Date;
public class TransactionQR implements Serializable{
private Long id;
private String codeqr;
private Date approvaltime;
private String merchant;
private String code_merchant;
private Long amount;
private Long saldoawal;
private Integer tracenumber;
private String state;
private Date createdate;
private Batch batch;
public TransactionQR() {
}
public TransactionQR(Long id, String codeqr, Date approvaltime, String merchant, String code_merchant, Long amount,
Long saldoawal, Integer tracenumber, String state, Date createdate, Batch batch) {
super();
this.id = id;
this.codeqr = codeqr;
this.approvaltime = approvaltime;
this.merchant = merchant;
this.code_merchant = code_merchant;
this.amount = amount;
this.saldoawal = saldoawal;
this.tracenumber = tracenumber;
this.state = state;
this.createdate = createdate;
this.batch = batch;
}
public Long getId() {
return id;
}
public Date getApprovalTime() {
return approvaltime;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
public void setApprovalTime(Date approvalTime) {
this.approvaltime = approvalTime;
}
public void setId(Long id) {
this.id = id;
}
public Date getApprovaltime() {
return approvaltime;
}
public void setApprovaltime(Date approvaltime) {
this.approvaltime = approvaltime;
}
public String getCodeqr() {
return codeqr;
}
public void setCodeqr(String codeqr) {
this.codeqr = codeqr;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getCode_merchant() {
return code_merchant;
}
public void setCode_merchant(String code_merchant) {
this.code_merchant = code_merchant;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Long getSaldoawal() {
return saldoawal;
}
public void setSaldoawal(Long saldoawal) {
this.saldoawal = saldoawal;
}
public Integer getTracenumber() {
return tracenumber;
}
public void setTracenumber(Integer tracenumber) {
this.tracenumber = tracenumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
i have try to handle the list with Gson:
Gson objGson = new GsonBuilder().setPrettyPrinting().create();
String json = objGson.toJson(QR.getAllTransaction());
System.out.println(json);
in that way, it's work to show but it's not from POJO right i want work with pojo to parse the data to json ?
why i get the error can't cast to model ? any clue ?
Try adding Select tr to your query in getAllTransaction()
Wich is the relation between QRTransactionDao and TransactionQR ?
I m new in android.I want to add these String variables to ArrayList, what I am doing now.
Suppose I have a four of String Variables.....
String number = "9876543211";
String type = "incoming";
String date = "1/1/2016";
String duration = "45 sec";
Here is my java code.......
while (managedCursor.moveToNext()) {
String number = managedCursor.getString(number1);
String type2 = managedCursor.getString(type1);
String date = managedCursor.getString(managedCursor.getColumnIndexOrThrow("date")).toString();
java.util.Date date1 = new java.util.Date(Long.valueOf(date));
String duration = managedCursor.getString(duration1);
String type = null;
String fDate = date1.toString();
int callcode = Integer.parseInt(type2);
sb.append("\nPhone Number:--- " + number + "");
sb.append(" \nCall Type:--- " + type + " ");
sb.append("\nCall Date:--- " + fDate + "");
sb.append("\nCall duration in sec :--- " + duration);
sb.append("\n----------------------------------");
}
As 4castle suggest, you should really have a custom class - which looking at the properties you are interested in, you might want to name "CallLogEntry" and then have properties for this class. Here is an example of such a custom class.
public class CallLogEntry {
String number;
String type;
String date;
String duration; //this should ideally be of type Long (milliseconds)
public CallLogEntry(){
//do stuff if necessary for no-params constructor
}
public CallLogEntry(String number, String type, String date, String duration){
this.number = number;
this.type = type;
this.date = date;
this.duration = duration;
}
//getters and setters go here..
getNumber(){ return this.number;}
setNumber(String number){ this.number = number;}
//...the rest of them...
}
Than it makes more sense to have an ArrayList of CallHistoryEntry items like this:
//...declare list of call-log-entries:
List<CallLogEntry> callLogEntryList = new ArrayList<CallLogEntry>();
//...add entries
CallLogEntry entry = new CallLogEntry(number, type, date, duration);
callLogEntryList.add(entry);
The advantage of doing it like this, especially in an Android app, is that later you may pass this list to some list-adapter for a list-view.
I hope this helps.
Create JavaBean Class as follows
public class DataBean {
String number;
String type;
String date;
String duration;
public DataBean(String number, String type, String date, String duration) {
this.number = number;
this.type = type;
this.date = date;
this.duration = duration;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
Now create Arryalist as follows
ArrayList<DataBean> dataBeanList = new ArrayList<>();
DataBean dataBean=new DataBean(number,type,date,duration);
dataBeanList.add(dataBean);//added bean object arrylist
For Retrieving data do as follow
// iterate through arraylist as follows
for(DataBeand d: dataBeanList ){
if(d.getName() != null && d.getDate()!=null)
//something here
}
I am creating the ArrayList of Object, to insert information I use different constructors in that class but I have one type variable that I update with every constructor call. here is what i am doing
public class eProperty {
public String type = null;
public int marks;
public int code;
public String category
public String student_name = null;
public String employee_name = null;
public String o_name = null;
public eProperty(String type, String student_name, int marks) {
this.marks = marks;
this.type = type;
this.student_name = student_marks;
}
public eProperty(String type, String employee_name, int makrs, String category) {
this.marks = marks;
this.type = type;
this.employee_name = employee_name;
this.category = category;
}
public eProperty(String type, int code, int makrs, String o_name) {
this.marks = marks;
this.type = type;
this.mnc = code;
this.o_name = o_name;
}
}
I populate arraylist like this,
ArrayList<eProperty> allData;
eProperty data;
if(type.equals("Student")) {
data = new eProperty(type, "John", 45)
allData.add(data)
}
if(type.equals("Employee")){
data = new eProperty(type, "Vicky", 86, "Developer")
allData.add(data)
} ... other cases also handled like this
Now I want to retrive highest marks for each type and I am stuck here, any help
Thanks
Using loop (sorry for that...) and Predicate from Apache Commons
public static int getHighestMarkByType(ArrayList<eProperty> allData, String type) {
Predicate predicate = new Predicate() {
public boolean evaluate(Object data) {
if ((eProperty) data).getType().equals(type)) {
return true;
} else {
return false;
}
}
};
ArrayList<eProperty> filteredData = (ArrayList<eProperty>) CollectionUtils.select(allData,predicate);
int maxMarks = 0;
for (eProperty data : filteredData) {
if (data.getMarks() > maxMark) {
maxMarks = data.getMark();
}
}
return maxMarks;
}
I am trying to read certain values from the hsql db and these values are returned as map with key and value. I have one more method which will accept these map values and will iterate through it and will fetch certain values based on the conditions.After this it will add all these values to a list. for me the condition and the first method is working fine but while adding the values to the list I am facing the class cast exception
Method which reads values from the table:
List<EntityMap> sample = session.createQuery(" FROM EntityMap order by if.ifName").list();
for (Iterator<EntityMap> iterator = sample.iterator(); iterator.hasNext();) {
entityMap = (EntityMap) iterator.next();
if (IfName != entityMap.getIf().getIfName().toString()) {
IfName = entityMap.getIf().getIfName().toString();
entitymapobject = new ArrayList<EntityMap>();
}
entitymapobject.add(entityMap);
EntityMaplist.put(entityMap.getIf().getIfName(),entitymapobject);
}
tx.commit();
This method is returning a map and it has the values which is fetched from the db. After that i am trying to extract certain values based on some conditions.In this I am calling the above method and i am iterating through it
proertyMap = listPROPERTNAMES();
System.out.println("inside loadproperty");
for (Iterator<Integer> itr1 = srcEntityIDList.iterator(); itr1.hasNext();) {
Integer aInteger = itr1.next();
for (Map.Entry<Long, List<PropertyMap>> entry : proertyMap.entrySet()) {
System.out.println(aInteger);
System.out.println(entry.getKey());
Long aLong = entry.getKey();
if (aLong.equals(Long.valueOf(aInteger))) {
System.out.println("values are equal");
trgtPropNameList.add(( (PropertyMap) entry.getValue()).getTgtpropnm());
}
}
}
return trgtPropNameList;
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return EntityMaplist;
}
Here while trying to add the values to the list (trgtPropNameList) I am getting a class cast exception. My POJO class which has the setter and the getter methods is
public class PropertyMap implements java.io.Serializable {
private PropertyMapId id;
private EntityMap entityMap;
private String tgtpropnm;
private String splitrule;
private String combinerule;
private String createdby;
private Date createdon;
public PropertyMap() {
}
public PropertyMap(PropertyMapId id, EntityMap entityMap) {
this.id = id;
this.entityMap = entityMap;
}
public PropertyMap(PropertyMapId id, EntityMap entityMap, String tgtpropnm,
String splitrule, String combinerule, String createdby,
Date createdon) {
this.id = id;
this.entityMap = entityMap;
this.tgtpropnm = tgtpropnm;
this.splitrule = splitrule;
this.combinerule = combinerule;
this.createdby = createdby;
this.createdon = createdon;
}
public PropertyMapId getId() {
return this.id;
}
public void setId(PropertyMapId id) {
this.id = id;
}
public EntityMap getEntityMap() {
return this.entityMap;
}
public void setEntityMap(EntityMap entityMap) {
this.entityMap = entityMap;
}
public String getTgtpropnm() {
return this.tgtpropnm;
}
public void setTgtpropnm(String tgtpropnm) {
this.tgtpropnm = tgtpropnm;
}
public String getSplitrule() {
return this.splitrule;
}
public void setSplitrule(String splitrule) {
this.splitrule = splitrule;
}
public String getCombinerule() {
return this.combinerule;
}
public void setCombinerule(String combinerule) {
this.combinerule = combinerule;
}
public String getCreatedby() {
return this.createdby;
}
public void setCreatedby(String createdby) {
this.createdby = createdby;
}
public Date getCreatedon() {
return this.createdon;
}
public void setCreatedon(Date createdon) {
this.createdon = createdon;
}
}
Can anyone please help me here?
entry.getValue() is an object of type List<PropertyMap> and not PropertyMap
If you can't cast it just construct and fill a new one.
Change the line
trgtPropNameList.add(( (PropertyMap) entry.getValue()).getTgtpropnm());
to
for(PropertyMap map : entry.getValue(){
trgtPropNameList.add(((PropertyMap)map).getTgtpropnm());
}
Should fix the casting problem.