How can I get previous value java? - java

I have tow Spinner dropDown on my layout when user select each of spinner I'll take an id from spinner,and I have a class that I send these Ids to it class .
the getID.class :
public class getID {
private String tagID = "105358";
public getID tagID(String tagID) {
this.tagID += "," + tagID;
return this;
}
public URL build() throws MalformedURLException {
return new URL(
String.format("%s",
tagID));
}
}
Problem :
But when I select an item on second spinner I lost the first Value of the first spinner .
I send my value to class with this code:
URL url = new getID(Const.URLMedia)
.tagID("10")
.build();
For example when I select an item on first spinner(for exam I send 10 value) in other class I see :
105358,10
when I select an Item on second spinner(for exam I send 85 value) in other class I see :
105358,85
But I need to :
105358,10,85

Seems like you are creating a new instance of getID everytime:
URL url = new getID(Const.URLMedia)
.tagID("10")
.build();
so when you select the first spinner you get 105358,10 and when you select second, your code will again create new instance of getID and you get 105358,5 so simply create a single getID instance instead of creating a new one every time.
class Activity ..{
getID url;
#Override
oncreate (Bundle saveinstance){
url=new getID();
}
}
Now simple appends the value
URL url = obj.tagID(StringValue).build();
plus i can't see any constructor for this getID(Const.URLMedia),seems like missing.
Best Practices for some unexpected cases to avoid broken URL(if
sequence matter):
if user select 2nd spinner instead of first : you can create new getID object inside onclick of first spinner plus set the default value of 2nd spinner.

One way to do it is to keep track of the two sliders (I have added a constructor):
public class getID {
private String tagID;
private String init;
private String firstSlider;
private String secondSlider;
public getID setFirstSlider(String value) {
firstSlider = value;
return this;
}
public getID setSecondSlider(String value) {
secondSlider = value;
return this;
}
public getID(String init) {
this.init = init;
tagID = "" ;
firstSlider = "";
secondSlider = "";
}
public getID tagID() {
this.tagID = init + "," + firstSlider + "," + secondSlider;
return this;
}
public URL build() throws MalformedURLException {
return new URL(
String.format("%s",
tagID));
}
}
Then you can use the class like this:
try {
getID myID = new getID("105358") ;
URL url = myID.setFirstSlider("10").setSecondSlider("20").tagID().build();
System.out.println("url: " + url);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
There are other ways to do it, for example by removing the tagID() function and the tagID String and calling directly build() since all the info is available:
public URL build() throws MalformedURLException {
return new URL(
String.format("%s,%s,%s",
init, firstSlider, secondSlider));
}
}

Related

Get a variable from an ArrayList that uses external class

I have an ArrayList called results that uses the class ItemObjects when I want to add an item in results. My problem is that I cannot manage to retrieve a specific String from an item.
The class code is:
public class ItemObjects {
private String mText1;
private String mText2;
public ItemObjects(String text1, String text2){
mText1 = text1;
mText2 = text2;
}
public String getmText1() {
return mText1;
}
public void setmText1(String mText1) {
this.mText1 = mText1;
}
public String getmText2() {
return mText2;
}
public void setmText2(String mText2) {
this.mText2 = mText2;
}
}
And I use the following code to add an item into the ArrayList:
ArrayList results = new ArrayList<ItemObjects>();
//THis part goes inside a for using i as increment;
ItemObjects obj = new ItemObjects(type, sender);
results.add(i , obj);
I have tried several things to retrieve the data such as:
String type = ItemObjects.getmText1();
or:
String type= results.get(i);
the first try, only retrieves the mText1 from the first item, and the second is an object and I dn't know how i should get the mText1 from it.
Any help would be appreciated :)
For adding the Value
ArrayList<ItemObjects> results = new ArrayList<ItemObjects>();
ItemObjects obj = new ItemObjects(type, sender);
results.add(obj);
For getting the Value
for (int i=0, i<result.size(); i++)
{
String type = results.get(i).mText1;
String sender= results.get(i).mText2;
Toast.makeText(this, "" + type, Toast.LENGTH_LONG).show();
Toast.makeText(this, "" + sender, Toast.LENGTH_LONG).show();
}
Change
ArrayList results = new ArrayList<ItemObjects>();
to
ArrayList<ItemObjects> results = new ArrayList<>();
Then results.get() will return ItemObjects.
Or you can simply cast your current result.get() to ItemObjects

Passing value to another class in java

I have a problem in passing the value of input of user to another class. This is a webservice that's why i don't know how i will fix it and this is my first time to encounter wevservice. This is my code in getting the input of user.
PlateNumberCheck.java
//PATH FOR CHECKING PLATE NUMBER
#Path("platecheck") //for the url
public class PlateNumberCheck {
public String anss;
#GET
//To get the full url : http://Ipaddress:portnumber/#path/#getPath
#Path("/check")
#Produces(MediaType.APPLICATION_JSON)
//Produces is for the response of JSON.
public String check(#QueryParam("taxi_plate_no") String taxi_plate_no){
String sagot = "";
anss = taxi_plate_no;
if(checkInput(taxi_plate_no)){
display();
sagot = JsonConstruction.JSONResponse("checked", true);
} else{
sagot = JsonConstruction.JSONResponse("checked", false, "Not in the database");
}
return sagot;
}
private boolean checkInput (String taxi_plate_no){
System.out.println("Check Input");
boolean output = false;
if(JsonConstruction.isNotNull(taxi_plate_no)){
try{
output = DatabaseConnection.checkPlate(taxi_plate_no);
} catch (Exception e){
output = false;
}
} else{
output = false;
}
return output;
}
public void display(){
System.out.println(anss);
}
}
I think this class works. because as you can see i use the method first before it success and the method contains system.out.print which prints the input in console. This is my second class which i want to pass the input to this class.
DisplayTaxiDetails.java
#Path("/displays")
public class DisplayTaxiDetails {
String plates;
#GET
#Path("taxidetails")
#Produces(MediaType.APPLICATION_JSON)
public String taxidetails (){
String taxidetails = null;
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
try{
PlateNumberCheck plate = new PlateNumberCheck();
plates = plate.anss;
taxiDetailsList = new ArrayConnection().getTaxiDetails(plates);
System.out.println(plates);
Gson gson = new Gson();
taxidetails = gson.toJson(taxiDetailsList);
} catch (Exception e){
e.printStackTrace();
}
return taxidetails;
}
}
As you can see i call the first class and access the anss which is the string of that class where the input was stored. but when i access it and try to pass value it doesn't work. I use again system.out.print to see if it prints the data but it always shows null which i think the value from first class is not passed to the variable of this second class.
You need to understand the basics of java runtime environment. That'll explain how your objects bind with each other and can interact with each other. In your case, you are creating a new instance of PlateNumberCheck every time your method in second class is getting called.
PlateNumberCheck plate = new PlateNumberCheck();
For that instance, you don't have any value set in the anss field (by the way, this is also not correct way, but that's for later) as this instance has just got created.

How to remove particular bean object from ArrayList in Java? [duplicate]

This question already has answers here:
When you call remove(object o) on an arraylist, how does it compare objects?
(4 answers)
Closed 8 years ago.
I want to remove particular bean object from ArrayList.
I am using remove and removeAll method for delete the object element from ArrayList, but not remove element.
for example, assume below code,
ArrayList<SystemDetailData> systemDetails = new ArrayList<SystemDetailData>();
SystemDetailData data = new SystemDetailData();
data.setId("1");
data.setName("abc");
data.setHost("192.168.1.2");
systemDetails.add(data);
data = new SystemDetailData();
data.setId("2");
data.setName("asd");
data.setHost("192.168.1.45");
systemDetails.add(data);
System.out.println("Before remove : " + systemDetails);
ArrayList<SystemDetailData> systemDetail = new ArrayList<SystemDetailData>();
SystemDetailData data = new SystemDetailData();
data.setId("1");
data.setName("abc");
data.setHost("192.168.1.2");
systemDetail.add(data);
System.out.println("Old data :" + systemDetail);
//Remove object from arraylist - method1
systemDetails.removeAll(systemDetail);
//Remove object from arraylist - method2
systemDetails.removeAll(systemDetail.getId());
systemDetails.removeAll(systemDetail.getName());
systemDetails.removeAll(systemDetail.getHost());
System.out.println("After remove : "+systemDetails);
Bean Class :
public class SystemDetailData extends BusinessData {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String DOMAIN_NAME = "domainName";
private static final String HOST_NAME = "hostName";
private static final String USER_NAME = "userName";
private static final String PASSWORD = "password";
private static final String INDEX = "index";
private BigInteger index;
private String domainName;
private String hostName;
private String userName;
private String password;
public BigInteger getIndex() {
return (BigInteger) get (INDEX);
}
public void setIndex(BigInteger index) {
set (INDEX, index);
this.index = index;
}
public String getDomainName() {
return (String) get(DOMAIN_NAME).toString();
}
public void setDomainName(String domainName) {
set (DOMAIN_NAME, domainName);
this.domainName = domainName;
}
public String getHostName() {
return (String) get (HOST_NAME);
}
public void setHostName(String hostName) {
set (HOST_NAME, hostName);
this.hostName = hostName;
}
public String getUserName() {
return (String) get (USER_NAME);
}
public void setUserName(String userName) {
set (USER_NAME, userName);
this.userName = userName;
}
public String getPassword() {
return (String) get (PASSWORD);
}
public void setPassword(String password) {
set (PASSWORD, password);
this.password = password;
}
#Override
public String toString() {
return "SystemDetailData [index=" + index + ", domainName="
+ domainName + ", hostName=" + hostName + ", userName="
+ userName + ", password=" + password + "]";
}
#Override
public String getKeyValue() {
String value = "";
if (index != null) {
value = value + "INDEX =" + index + ";";
}
if (domainName != null) {
value = value + "DOMAIN_NAME =" + domainName + ";";
}
if (userName != null) {
value = value + "USER_NAME =" + userName + ";";
}
if (hostName != null) {
value = value + "HOST_NAME =" + hostName + ";";
}
if (password != null) {
value = value + "PASSWORD =" + password + ";";
}
return value;
}
}
I got below output :
Before remove : [SystemDetailData [index=1, Name=abc, host=192.168.1.2], SystemDetailData [index=2, Name=asd, host=192.168.1.45]]
Old data : [SystemDetailData [index=1, Name=abc, host=192.168.1.2]]
After remove : [SystemDetailData [index=1, Name=abc, host=192.168.1.2], SystemDetailData [index=2, Name=asd, host=192.168.1.45]]
I want below output :
After remove : [SystemDetailData [index=2, Name=asd, host=192.168.1.45]]
If the SystemDetailData Class you have to implement hashcode and equals method. To expand my answer, In java when you want to delete an Object from a collection. Java check if the Object you want to delete is in this collection ( if Collection contains an Object which is equals to the one we want to delete). It uses the method equals. So we have to tell (explain) to Java what is for us the same Object: it can have the same name or the same id or another property ( attribute ). This is a reason why we have to implements equals (and hashcode)
Your SystemDetailData class needs to implement an equals method. When you call remove on the ArrayList, the code is doing something like:
ArrayList<SystemDetailData> items;
void remove(SystemDetailData itemToRemove) {
for ( int i = 0; i < items.size() ++i ) {
if ( items.get(i).equals(itemToRemove) ) {
items.remove(i);
break;
}
}
}
he
So unless the equals method returns true for the item you are passing into the remove method and an item in your collection, nothing wil be removed.
You need to decide exactly what the equals method should look like but if, for example, two items are the same if the ids are the same then you could just add a method to SystemDetailData like:
public boolean equals(Object other) {
SystemDetailData otherData = (SystemDetailData)other;
return otherData.getId() == this.getId();
}
Obviously you'll need to add checks for null, the type of other etc. but that should give you an idea of what the method needs to look like.

References in Java constructor

This is the first version of my code :
public class ListSchedule implements ListInterface {
private ArrayList<Schedule> list;
private String cookie;
public ListSchedule() {
this.list = new ArrayList<Schedule>();
}
public ArrayList<Schedule> getList() {
return list;
}
}
In another class, I made this call :
protected final ListSchedule parse(String jsonString)
throws CustomException {
ListSchedule list = new ListSchedule();
JSONArray schedulesArray;
try {
// Convert the response to a JSONObject
JSONObject json = new JSONObject(jsonString);
try {
int errorCode = json.getInt("error");
// Check if there is no error from FilBleu server
if (errorCode > 0) {
throw new CustomException(
CustomException.ERROR_FILBLEU,
"DataAccessObject", "Server error "
+ json.getInt("subError"));
}
try {
String cookie = json.getString("cookie");
list = new ListSchedule(cookie);
} catch (JSONException e) {
throw new CustomException(CustomException.JSON_FORMAT,
"DataAccessObject", "No cookie value");
}
schedulesArray = json.getJSONArray("schedules");
// NullPointerException with the line below
Log.d("DAO", list.getList().toString());
parseSchedulesArray(list, schedulesArray);
} catch (JSONException e) { // Unable to get the error code
throw new CustomException(CustomException.JSON_FORMAT,
"DataAccessObject", "Bad JSON format ("
+ e.getMessage() + ")");
}
} catch (JSONException e) { // Unable to convert response
throw new CustomException(CustomException.JSON_FORMAT,
"DataAccessObject", "Bad JSON format ("
+ e.getMessage() + ")");
}
return list;
}
then I had a NullPointerException from the line Log.d("DAO", list.getList().toString());. So I tried another solution. As you can see, the only difference is the initialization of the list property :
public class ListSchedule implements ListInterface {
private ArrayList<Schedule> list = new ArrayList<Schedule>();
private String cookie;
public ListSchedule() {
}
public ArrayList<Schedule> getList() {
return list;
}
}
and the NullPointerException was never thrown again...
I don't really understand the difference between the two ways of initializing the list property. Can somebody give me a hint please ?
I am speculating that the following constructor exists in your code base :
public ListSchedule(String cookie) {
this.cookie = cookie;
}
and what you need is the following:
public ListSchedule(String cookie) {
this.cookie = cookie;
this.list = new ArrayList<Schedule>();
}
This is further validated by the invocation of this line in your program:
list = new ListSchedule(cookie);
Notice how you don't initialize the list in the second constructor. Also you start by invoking the default constructor, but you later reassign the pointer to the object into what gets created from the String constructor of ListSchedule.
You code is calling this constructor:
list = new ListSchedule(cookie);
Which to me, does not call the one that initializes your ArrayList<Schedule> and that explains the NullReferenceException

How to encapsulate the logic of parametrized messages?

I'm using java.util.resourcebundle to format my JSTL messages and this works fine:
I use the class MessageFormat you can see here. Now I want to encapsulate this to a method that is just getParametrizedMessage(String key, String[]parameters) but I'm not sure how to do it. Now there is quite a lot of work to display just one or two messages with parameters:
UserMessage um = null;
ResourceBundle messages = ResourceBundle.getBundle("messages");
String str = messages.getString("PF1");
Object[] messageArguments = new String[]{nyreg.getNummer()};
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString("PI14"));
String outputPI14 = formatter.format(messageArguments);
formatter.applyPattern(messages.getString("PI15"));
String outputPI15 = formatter.format(messageArguments)
if(ipeaSisFlag)
if(checkIfPCTExistInDB && nyreg.isExistInDB()) {
//um = new ExtendedUserMessage(MessageHandler.getParameterizedMessage("PI15", new String[]{nyreg.getNummer()}) , UserMessage.TYPE_INFORMATION, "Info");
um = new ExtendedUserMessage(outputPI15 , UserMessage.TYPE_INFORMATION, "Info");
…and so on. Now can I move this logic to a static class MessageHandler.getParameterizedMessage that now is not working and looking like this:
private final static String dictionaryFileName="messages.properties";
public static String getParameterizedMessage(String key, String [] params){
if (dictionary==null){
loadDictionary();
}
return getParameterizedMessage(dictionary,key,params);
}
private static void loadDictionary(){
String fileName = dictionaryFileName;
try {
dictionary=new Properties();
InputStream fileInput = MessageHandler.class.getClassLoader().getResourceAsStream(fileName);
dictionary.load(fileInput);
fileInput.close();
}
catch(Exception e) {
System.err.println("Exception reading propertiesfile in init "+e);
e.printStackTrace();
dictionary=null;
}
}
How can I make using my parametrized messages as easy as calling a method with key and parameter?
Thanks for any help
Update
The logic comes from an inherited method that in in the abstract class that this extends. The method looks like:
protected static String getParameterizedMessage(Properties dictionary,String key,String []params){
if (dictionary==null){
return "ERROR";
}
String msg = dictionary.getProperty(key);
if (msg==null){
return "?!Meddelande " +key + " saknas!?";
}
if (params==null){
return msg;
}
StringBuffer buff = new StringBuffer(msg);
for (int i=0;i<params.length;i++){
String placeHolder = "<<"+(i+1)+">>";
if (buff.indexOf(placeHolder)!=-1){
replace(buff,placeHolder,params[i]);
}
else {
remove(buff,placeHolder);
}
}
return buff.toString();
}
I think I must rewrite the above method in order to make it work like a resourcebundle rather than just a dictionary.
Update 2
The code that seems to work is here
public static String getParameterizedMessage(String key, Object [] params){
ResourceBundle messages = ResourceBundle.getBundle("messages");
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString(key));
return formatter.format(params);
}
I'm not really sure what you're trying to achive, here's what I did in the past:
public static final String localize(final Locale locale, final String key, final Object... param) {
final String name = "message";
final ResourceBundle rb;
/* Resource bundles are cached internally,
never saw a need to implement another caching level
*/
try {
rb = ResourceBundle.getBundle(name, locale, Thread.currentThread()
.getContextClassLoader());
} catch (MissingResourceException e) {
throw new RuntimeException("Bundle not found:" + name);
}
String keyValue = null;
try {
keyValue = rb.getString(key);
} catch (MissingResourceException e) {
// LOG.severe("Key not found: " + key);
keyValue = "???" + key + "???";
}
/* Message formating is expensive, try to avoid it */
if (param != null && param.length > 0) {
return MessageFormat.format(keyValue, param);
} else {
return keyValue;
}
}

Categories