How to view all items in arraylist java? - java

In my android application I want to be able to add a string value to a static arraylist I have declared on my main android activity. The logic goes like this:
1) When you click a button and an activity starts. On the oncreate method I want to save the name of the class that is the current activity to a string value. For example:
String className = "com.lunchlist.demo";
After this value is assigned I want to immediately add this string value to a Static ArrayList I have declared in my main android activity (meaning first android activity that starts) After adding the value
I did something like this:
static String List<String> members = new ArrayList<String>();
This is declared in my main activity. Now when I click a button to start another activity I use this to add the string classname for that current activity to my arraylist in my oncreate method:
String className = "com.lunchlist.demo"
members.add(className);
My question is now, would this add the string value to my arraylist and save it for later use? For example If I click three different buttons this will add three different className values to the arraylist. Would this then store a string value that would hold three different string values for my members arraylist? How would I check each item in my arraylist to see if the values are being added when a new activity is started?
I'm asking this because I will need to retrieve this and store these values using shared preferences and later retrieve them and starting an intent using the string value which is the class to start the activity. I got the activity to start with a string value of a class name I'm just having trouble storing them.

Answering to all of your questions:
would this add the string value to my arraylist and save it for later
use?
Yes. Your code seems perfect to do it with no problems.
For example If I click three different buttons this will add three
different className values to the arraylist. Would this then store a
string value that would hold three different string values for my
members arraylist?
If you tell to your button's onClickListener to add a string to the members ArrayList then it will be done and no matter if you already had previously added that member to the ArrayList because array lists don't care if there is duplicated data or not.
How would I check each item in my arraylist to see if the values are
being added when a new activity is started?
You have to iterate your array list with a for or a for-each cicle and then print that member name as a log entry.
For-each cicle
for (String member : members){
Log.i("Member name: ", member);
}
Simple For cicle
int listSize = members.size();
for (int i = 0; i<listSize; i++){
Log.i("Member name: ", members.get(i));
}
If you try to print/ log a value which index is out of range, i.e., i < 0 || i >= listSize then a IndexOutOfBoundsException will be thrown and crash your app.

Iterate using For-Each introduced in Java from Java 1.5 :
for (String s : members){
Log.d("My array list content: ", s);
}
See this link for further details:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

Try this:)
We can implement by these two way
foreach
for loop
String type arraylist
ArrayList<String> limits = new ArrayList<String>(); // String arrayList
Using foreach
for (String str_Agil : limits) // using foreach
{
Log.e("Agil_Limits - " , str_Agil);
}
Using forloop
for(int agil=0; agil<=limits.size(); agil++) // using for loop
{
Log.e("Agil_Limits - " , limits.get(agil).toString());
}

Related

method add in ArrayList<ClassName> is not applicable for the arguments (String)

I'm trying to read a .txt file that contains several lines with the name of a professional carreer in each one of them. I've created a Scanner but whenever I want to add what the scanner have just read and try to add it to the arrayList, this error pops up
The method add(ClassName) in the type ArrayList is not applicable for the arguments (String)
ArrayList<Claseqla> clista = new ArrayList<Claseqla>();
Scanner s = new Scanner(new File("texto.txt"));
while(s.hasNextLine())
{
**clista.add(s.nextLine());**
}
This is the piece of code inside another class;
The bold marked line is where the error pops up.
clista only has 2 attributes but I'd like to add them to the list with just one String element filled and the other empty (Is that even possible?)
s.nextLine() returns a String. But your ArrayList has generic type Claseqla. You need to create a Claseqla object using the string you grab from the s.nextLine() call, and then add that object to your ArrayList.
I guess you are trying to say that the class Claseqla has 2 attributes. If so, then you can create a Claseqla object and set the value of one of the attributes with s.nextline()
while(s.hasNextLine())
{
Claseqla cq = new Claseqla();
cq.setCareer(s.nextLine());
clista.add(cq);
}
This is asumming that you have an attribute named career (String) in your Claseqla class with its respective setter function.

How do I add a User Input of type String to an ArrayList in Java?

I am attempting to make a course registration system and one of my classes (Course) is centered around course attributes (ie. Course number, course name, instructors, students). I am making an ArrayList so that the Administrator (one of the user types) may add as many instructors to the course as he/she would like- I have created a Scanner and a String variable and everything, but when I write the .add command, Eclipse highlights ".add" and says "the method .add() is undefined for the type of scanner". Now, I can understand this, but I have no idea how to fix it and I've tried so many ideas.
Here is the method:`
public static String Instructor(){
String courseInstructors;
System.out.println("Please add name(s) of course instructors.");
ArrayList<String> Instructors= new ArrayList<String>();
Scanner courseInst = new Scanner(System.in);
courseInstructors = courseInst.next();
//courseInst.add(courseInstructors);
for(String courseInstructors1 : Instructors) {
courseInstructors1 = courseInstructors;
courseInst.add(courseInstructors1);
}
return;
}`
Please adhere to Java naming conventions ad use lower case for variable names - instructors instead of Instructors.
Also, you want to add to your arraylist, so call add() on
instructors.add(courseInstructors1)
You may also want to consider choosing better variable naming than courseInstructors1, for instance just courseInstructor, since you are referring to on instructor of all instructors.
Also in your for loop you are doing the following
for(String courseInstructors1 : Instructors) {
courseInstructors1 = courseInstructors;
courseInst.add(courseInstructors1);
}
This can be simplified to
for(String courseInstructors1 : Instructors) {
courseInst.add(courseInstructors);
}
And if you look at the simplification you will see that iterating through Instructors make no sense here, since you are not using the contents of courseInstructors1.
I'm trying to understand what your loop is for.
if you are trying to get multiple instructor names from one input then you need something like this.
//get input
//"John Peggy Adam blah blah"
courseInstructors = courseInst.next();
//split the string by white space
String[] instArr = courseInstructors.split(" ");
//will give array of John, Peggy, Adam, blah, blah
Then do your foreach loop to add them to the list.
for(String inst: instArr){
instructors.add(inst);
}
Otherwise I would suggest doing something like this so you don't have to worry about splitting names and such.
courseInstructor = courseInst.nextLine();
while(!courseInstructor.equals("done"){
//add name to list of instructors.
instructors.add(courseInstructor);
//get next name.
courseInstructor = courseInt.nextLin();
//if the user types done, it will break the loop.
//otherwise come back around and add it and get next input.
}

Want to convert java struts 2 static code into dynamic

I have been assign to one struts2 project and its one of jsp contains more than 100 radio buttons and they have handled in statically not dynamically. As jsp contains 100 radio buttons so I am able to see the below list of radio buttons catches in actions with their getter and setter
List selectRadioList001
List selectRadioList002
List selectRadioList003
List selectRadioList004
etc
List selectRadioList100
I want to add these radio button in a list dynamically iterating through 1 to 100 something like below but when I try to access the variable like "searchBoxSelectRadioList"+i then it is pretending like a simple string. I want it to be like a List as shown above.
public class SelectRadioListPOJO {
private List<TicketDesignUtil> selectRadioList;
public List<TicketDesignUtil> getSelectRadioList() {
return selectRadioList;
}
public void setSelectRadioList(List<TicketDesignUtil> selectRadioList) {
this.selectRadioList = selectRadioList;
}
}
Action code:
List<SelectRadioListPOJO> selectRadioListPOJOList = new ArrayList<>();
SelectRadioListPOJO selectRadioListPOJO;
for (int i = 1; i <= 100; i++) {
selectRadioListPOJO = new SelectRadioListPOJO();
selectRadioListPOJO.setSelectRadioList("searchBoxSelectRadioList"+i);// ERROR
selectRadioListPOJOList.add(selectRadioListPOJO);
}
It's not clear what you're asking.
You can't pass arbitrary values to methods; setSelectRadioList takes a list of TicketDesignUtil.
If your action doesn't have getters and setters for all of those radio buttons then you should resort to accessing the request parameters directly, for example, via ParameterAware.
You would then access the radio button parameters by name from the injected parameter map.
Notes:
It's not "pretending" to be a simple string, it is a simple string, because... well, because it is.
Your for loop is wrong; I corrected it in your question to avoid others commenting on it. The POJO should be added to the POJOList inside the loop.
Naming is funky; just call it selectRadioListPojos. Better yet, name it something domain-specific: variables should be semantically meaningful, not just a description of the class(es) involved.
These shouldn't be static in the first place, but a map or array.

Object Array add only adds last record

I am trying to add an object to an arraylist.
The object is defined as:
ExercisesGroup group = new ExercisesGroup();
Array List defined as:
ArrayList<ExercisesGroup> groups = new ArrayList<ExercisesGroup>();
I am then populating the object in a loop (rs is a result set from a database):
while (rs.next()){
group.setExerciseGroupId(rs.getInt("idbodyarea"));
group.setExerciseGroupDescription(rs.getString("bodyareadescription"));
groups.add(group);
}
When I return the arraylist 'groups' the correct number of results are added, however the data is all the same, i.e. the last record is added for every slot.
<exerciseGroupsReturn>
<exerciseGroupDescription>Description2</exerciseGroupDescription>
<exerciseGroupId>2</exerciseGroupId>
</exerciseGroupsReturn>
<exerciseGroupsReturn>
<exerciseGroupDescription>Description2</exerciseGroupDescription>
<exerciseGroupId>2</exerciseGroupId>
</exerciseGroupsReturn>
Any idea what I am doing wrong?
You need to create a new instance of the object on every iteration:
while (rs.next()){
group = new ExercisesGroup();
//...
}
Also, it would be better if you change the declaration of groups variable from ArrayList<ExercisesGroup> to List<ExercisesGroup>. Refer to What does it mean to "program to an interface"?
It looks like you're creating your ExcerciseGroup outside of the loop so you're always referencing the same object. Put the ExerciseGroup constructor inside the loop.

Sharing an ArrayList Between Activities

I am having problems storing a List in an Application class across activities.
In my Splash screen, I am loading data into a List from a MySQL database.
The List is in a class called Rateit that extends Application. I do this in it as a class variable:
public static List<String> masterCats;
In the Splash Screen Activity/Class, I do this:
in onCreate:
Rateit.masterCats = new ArrayList<String>();
Inside my AsyncTask loop where loading data I do this:
Rateit.masterCats.add(cat);
cat being the list item that comes from the database. I have Log.d the data (cat) as well as the ListPosition to check if it is being added to the List and it is.
However, I need to grab that same info in the next Activity and put it into an adapter. It comes back with 0 length.
I simply do this: adapter = new MasterCatAdapter(getActivity(), Rateit.masterCats, tf);
How come the list doesn't maintain data across activies? Is this because its static? something else?
(Note: I will add getter and setter methods here soon!)
As #A--C mentioned in his comment, avoid the model you have now with the static variable. Instead, I would do something like this:
private void yourMethodWhereYouGetYourData(){
//get your data
ArrayList<String> masterCats = new ArrayList<String>();
masterCats.add(cat);
//Assuming you're doing this synchronously, once you've gotten your data just do:
Intent i = new Intent(this, YourActivity.class);
i.putStringArrayListExtra("MasterCats", masterCats);
startActivity(i);
}
Then, in your new Activity's onCreate() or wherever, just access the list by doing:
getIntent().getStringArrayListExtra("MasterCats");
#KickingLettuce also mentioned in the comments about keeping this accessible if the user navigates away from the Activity. So, in whichever Activity you want to save the ArrayList, just convert it to a comma-separated String and save it in SharedPreferences like so:
private void saveCats(){
//get your ArrayList from wherever (either as a global variable or pass it into the
//method.
StringBuilder sb = new StringBuilder();
for(int i = 0; i < masterCats.size(); i++){
if(i == masterCats.size() - 1)
sb.append(masterCats.get(i));
else
sb.append(masterCats.get(i)+",");
}
SharedPreferences.Editor prefsEditor =
PreferenceManager.getDefaultSharedPreferences(this).edit();
prefsEditor.putString("MasterCats", sb.toString()).commit();
//Note: in API 11 and beyond you can store a Set of Strings in SharedPreferences, so
//if you are only targeting API 11+ you could do:
Set<String> masterCatsSet = new LinkedHashSet<String>(); //<--using LinkedHashSet to preserve order
masterCatsSet.addAll(masterCats);
prefsEditor.putStringSet("MasterCats",masterCatsSet).commit();
}
Then access this SharedPreference in your onCreate or something if you wish to persist the list across the Activity lifecycle.
saving the List in a Application extended class is good idea you can achieve it by following
Declare List as follows in your App class like
public static List<String> masterCats;
and declare setter and getter methods for above variable
public List getMasterCatsList()
{
return masteCats;
}
public Void setMasterCatsList(List list)
{
masteCats=list;
}
get the application object as follows in your Loader class as follows
Application application = (YOurClassName That Extends Application class) getApplication();
and set the list as follows
application.setMasterCatsList(List list);
now you can access this list from any activity as follows
Application application = (YOurClassName That Extends Application class) getApplication();
List l = application.getMasterCatsList();
hope it will be helpful to you

Categories

Resources