I am quite new to Java and am currently coding an Android application. In my "Shortcuts" class, I have this bit of code (more of course, but not useful to you, I don't think):
final String[] items = new String[]{ "Please select a category",scanner.getCategorys() };
#SuppressWarnings({ "unchecked", "rawtypes" })
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selection.setAdapter(adapter);
I have another class named "Scanner", which has this code:
String categorys = "test";
public String getCategorys() {
return categorys;
}
This does work, and in my Spinner, I can fill in my "Please select a category" option with a single value (i.e "test"). The problem is, I would like to be able to select multiple categories. If I do this in "Shortcuts" class:
final String[] items = new String[]{ "Please select a category","test","test2" };
It would work, but I would like to set it from the "Scanner" class, so I tried this:
String[] categorys = "test","test2";
public String[] getCategorys() {
return categorys;
}
But it just gives me the error:
String cannot be converted to String[]
I would be grateful for any help.
This is wrong:
String[] categorys = "test","test2";
Change it to
String[] categorys = {"test","test2"};
In your last code sample, you have to put { } around your strings, like so:
String[] categorys = { "test","test2" };
public String[] getCategorys() {
return categorys;
}
According to your edit above, you can't add a String[] to an existing String[]. You need to add every item in the String[] you get from getCategorys() to the other array. I would probably switch to an ArrayList<string> in this case, so you don't have to decide what size the array should be, then add each item.
You can initialize categorys as follows
String[] categorys = {"test","test2"};
I'd call the variable as 'categories'.
EDIT :
scanner.getCategorys() cannot be used as the constructor expects a String and not a string array. A good idea would be use ArrayList as pointed out by uncocoder. You could then just use the add method to include "Please select a category".
I recomment to use ArrayList, it's fast and easy like this
ArrayList<String> strings = new ArrayList<String>();
strings.add("SOME TEXT");
strings.get(0);
//and more
Related
I'm trying to create an ArrayList of String[], but can't get it to add more than one item. Ultimately I want to extract the items from the ArrayList and send them to a JTable. The program is 5 separate classes, but here's the applicable code for this issue:
static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]> foodData;
JTextField newFoodText, portionText, carbsText;
public Main() {
void createFood() {
String[] foodProperties = new String[3];
foodProperties[0] = newFoodText.getText();
foodProperties[1] = portionText.getText();
foodProperties[2] = carbsText.getText();
Main.createFood(foodProperties);
}
static void createFood(String[] foodArray) {
foodData = new ArrayList<String[]>();
foodData.add(foodArray);
foodChoice.addItem(foodArray[0]);
}
void addFoodToTable() {
String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
System.out.println(foodData.get(0));
System.out.println(foodData.get(1));
}
addFoodToTable gets called with a button click. So the issue I'm having is that (based on the sysouts) I will get a pointer address to the first entry in the ArrayList, but then a Null Pointer Exception stating that it is out of bounds for Length 0 when it tries to print the second one to console. This is obviously after calling createFood() 3 or four times in order to populate foodData. I can provide additional code if required, it's just too much to place in whole into this post. Thanks!
you clear out foodData every time you call createFood remove this line:
foodData = new ArrayList();
and move the initialization to a static level , like this:
static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]> foodData = new ArrayList<String[]>();
JTextField newFoodText, portionText, carbsText;
public Main() {
void createFood() {
String[] foodProperties = new String[3];
foodProperties[0] = newFoodText.getText();
foodProperties[1] = portionText.getText();
foodProperties[2] = carbsText.getText();
Main.createFood(foodProperties);
}
static void createFood(String[] foodArray) {
foodData.add(foodArray);
foodChoice.addItem(foodArray[0]);
}
void addFoodToTable() {
String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
System.out.println(foodData.get(0));
System.out.println(foodData.get(1));
}
Every time you call createFood(String[] foodArray) you create a new List instead of just adding the incoming item to the existing list.
Create the ArrayList in a different place and remove the line from the createFood method and it should work fine.
Worked like a charm. Man I don't know how I missed that... I guess when you look at the same problem for too long you miss the obvious. Thanks guys!
How can I combine the following two string[] arrays into a two dimensional ArrayList?
private String[] titles = {
"Apple", "Orange", "Banana"};
private String[] details = {
"Red Fruit", "Orange Citrus Fruit", "Yellow Fruit"};
//In reality, these data sets are full.
It needs to fit in a wrapper class. The methods need to look like this, in order to be compatible with the other classes.
private ArrayList<DataObject> getDataSet() {
ArrayList results = new ArrayList<>();
return results; //Just a rough view of the class.
}
The output should be two-dimensional ArrayList with String[] titles at the 1st dimension and String[] details at the 2nd one.
Essentially
results.add("Apple", "Red Fruit");
and do it for all the items in titles and details.
If we go to the way of your provided sample then this should do.
private ArrayList<DataObject> mess() {
ArrayList results = new ArrayList<>();
for (int index = 0; index < titles.length; index++) {
DataObject obj = new DataObject(titles[index],
details[index]);
results.add(index, obj);
}
return results;
}
Note that, if these two arrays(titles and details) of yours have different length then this won't work.
You can achive by using below lines of code
ArrayList<String> a = new ArrayList<>();
a.addAll(Arrays.asList(titles));
a.addAll(Arrays.asList(details));
I get a coding error in eclips Type mismatch, cannot convert Object to String. All data going into AL is String Type and AL is declared as String.
If i can just have AL go to a String[] that would be better.
heres my code:
Object[] Result;
AL.toArray (Result);
String[] news= new String[Result.length];
for (int i1=0;i1<news.length;i1++){
news[i1]=Result[i1]; <=====here is where the error shows up
Change this:
news[i1]=Result[i1];
to this:
news[i1]=Result[i1].toString();
Try type casting.
news[i1] = (String) Result[i1];
However, it is probably a good idea to check the type of Result[i1] before type casting like that. So you could do something like
if( Result[i1] instanceof String){
news[i1] = (String) Result[i1];
}
If you are absolutely sure that every object in Result array is String type, why don't you use String[] in the first place? Personally, I'm not a big fan of Object[]...
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
You can supply the ArrayList.toArray() method with an existing array to define what type of array you want to get out of it.
So, you could do something like this:
String[] emptyArray = new String[0];
String[] news = AL.toArray(emptyArray);
Try this code:
public static void main(String[] args)
{
Object[] Result = {"a1","a2","a3"};
String[] AL = new String[Result.length];
for(int a=0; a<Result.length; a++)
{
AL[a] = Result[a].toString();
}
System.out.println(AL[0]);
System.out.println(AL[1]);
System.out.println(AL[2]);
}
Since AL is, as you report, an ArrayList<String>, this should do what you want in one line of code:
String[] news = AL.toArray(new String[AL.size()]);
I have a list of URL's added to a String[] with this.
try {
Elements thumbs = jsDoc.select("div.latest-media-images img.latestMediaThumb");
List<String> thumbLinks = new ArrayList<String>();
for(Element thumb : thumbs) {
thumbLinks.add(thumb.attr("src"));
}
for(String thumb : thumbLinks) {
System.out.println(thumbLinks.get(1));
}
}
How can i add each String that is loaded into a separate String?
EDIT:
SO as the images are loaded into the thumbLinks list. I want to get each link to a seperate
String url1;
String url2;
String url3;
If you expect a fixed number of items, and you have a fixed number of String variables, you have little choice but something like:
String url0 = thumbLinks.get(0);
String url1 = thumbLinks.get(1);
...
String url5 = thumbLinks.get(5);
Well, you could do something grim with reflection, I guess. But probably best to avoid this at all.
take a String array of the size of your ArrayList object - thumbLinks in your case. take an int variable and initialize it with zero. I have made some changes in your code just have a look:
try{
Elements thumbs = jsDoc.select("div.latest-media-images img.latestMediaThumb");
List<String> thumbLinks = new ArrayList<String>();
for(Element thumb : thumbs) {
thumbLinks.add(thumb.attr("src"));
}
String[] urls = new String[thumbLinks.size()];
int x =0;
for(String thumb : thumbLinks) {
urls[x++] = thumb;
}
}catch(Excpetion e){
}
use urls for your purpose
ArrayList has method public <T> T[] toArray(T[] a) that you can call as described below on thumbLinks:
String[] url = new String[thumbLinks.size()];
url = thumbLinks.toArray(url);
Then, you will have an array of strings that you can access like this:
System.out.println(url[0]);
System.out.println(url[1]);
System.out.println(url[2]);
// etc, etc. all the say up to thumbLinks.size() - 1
While this is not exactly what you've asked for, it's pretty much the same thing. If you really want variables named url1, url2, url3, etc., you're likely going to have to code it line by line for every element in the list.
Just as an aside, you don't need an array to access the elements of your thumbLinks list directly. You can already do this:
System.out.println(thumbLinks.get(0));
System.out.println(thumbLinks.get(1));
System.out.println(thumbLinks.get(2));
// etc. all the way up to thumbLinks.size() - 1
The Java Docs for the method
String[] java.io.File.list(FilenameFilter filter)
includes this in the returns description:
The array will be empty if the directory is empty or if no names were accepted by the filter.
How do I do a similar thing and initialize a String array (or any other array for that matter) to have a length 0?
As others have said,
new String[0]
will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:
private static final String[] EMPTY_ARRAY = new String[0];
and then just return EMPTY_ARRAY each time you need it - there's no need to create a new object each time.
String[] str = new String[0];?
String[] str = {};
But
return {};
won't work as the type information is missing.
Ok I actually found the answer but thought I would 'import' the question into SO anyway
String[] files = new String[0];
or
int[] files = new int[0];
You can use ArrayUtils.EMPTY_STRING_ARRAY from org.apache.commons.lang3
import org.apache.commons.lang3.ArrayUtils;
class Scratch {
public static void main(String[] args) {
String[] strings = ArrayUtils.EMPTY_STRING_ARRAY;
}
}
Make a function which will not return null instead return an empty array you can go through below code to understand.
public static String[] getJavaFileNameList(File inputDir) {
String[] files = inputDir.list(new FilenameFilter() {
#Override
public boolean accept(File current, String name) {
return new File(current, name).isFile() && (name.endsWith("java"));
}
});
return files == null ? new String[0] : files;
}
You can use following things-
1. String[] str = new String[0];
2. String[] str = ArrayUtils.EMPTY_STRING_ARRAY;<br>
Both are same.