Passing variable string to create arrays (Android) - java

I am a newbie to Android and Java and want to write a function that will display a list based on a variable that I pass to the function.
The function is below and the code below creates an array out of a string called type, but what I want to do is pass it a variable string and have it build a list based on that string.
So if I wanted the type list I would say list_it("type")
But if I try something like getResources().getStringArray(R.array.thelist); it doesn't work.
Can someone point me in the right direction?
public void list_it(String thelist){
String[] types = getResources().getStringArray(R.array.type);
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this, R.layout.list_item1, types);
setListAdapter(mAdapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
}

Use the following code to get the identifier for the given name i.e thelist :
int resID = getResources().getIdentifier( thelist, "string", "<package name>" );
This will return you the identifier for the given resource name. Then use the
getResources().getStringArray( resID );
HTH !

Related

Append listview with the same variable but different value each time

I have variable a in a loop, it gives a different string each time
I want to add that string in ListView, without overwriting it, i searched for append ListView, but didn't find anything, i always got the last item which is the last a value in the ListView
I think I need to use HashMap or foreach, but i don't know how
in the image, each line is string a variable, so the variable will change every time
158 word
here's my code
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1,list);
list.add(a);
simpleList.setAdapter(adapter);
UPDATE:
code
a variable comes from console.log in javascript
siteView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessag) {
String imgDataUr= consoleMessag.message();
if (imgDataUr.contains("heyyes")) {
String a=imgDataUr.substring(6); //this changed with different value each time
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1,list);
Log.d("countries", a);
list.add(a);
simpleList.setAdapter(adapter);
}
return super.onConsoleMessage(consoleMessag);
}
});

Extracting string array from object array

So I have arraylist modelData that populates a recyclerview using sqlite database in some activity.!
Now in my MainActivity I want an string arraylist of names from the modelData !
that's what did so far..
// inside the onCreate of MainActivity
//code ..
db = new DBHandler(this, null, null, 1);
modelData = new ArrayList<AzkarModel>();
modelData = db.getDataFromDB();
for (AzkarModel o : modelData) {
ArrayList<String> names = new ArrayList<>();
names.add(o.getName());
}
for (int i = 0; i< modelData.size();i++){
names.add(modelData.get(i).getName());
Log.i("The List Log", names);
}
Two problems
1) [FIXED] The names arraylist is showing the same element twice at first and end
I/ The List Log: [Mike, John, Sam, Nora, Mike]
2) The arraylist names doesn't get updated..! when I add/edit/delete from the recycler and go back to the MainActivity I don't see the new changes unless I close the app then open it again..! I can't use notifyDataSetChanged since there's no adapter here.!
Once you have an array list object, populate it inside a loop
ArrayList<String> modelNames = new ArrayList<>();
for (AzkarModel model : modelData) {
modelNames.add(model.getName());
}
Now you have an array list with model names inside. Concerning the second question, please use an recyclerview adapter here you can find a nice tutorial.

Android:ArrayList storing weird values

I just don't understand what's going on here.
ArrayList<ListItem> list=new ArrayList<ListItem>();
ListItem curItem=new ListItem();
String[] contents=cwFile.list();
for(int i=0;i<contents.length;i++){
curItem.itemName = contents[i];
if(new File(cwd+contents[i]).isDirectory()){
curItem.isDir=true;
}
list.add(i,curItem);
}
Log.i("Main",list.get(0).itemName);
Log.i("Main",contents[0]);
So in this code snippet, I get the contents of a directory using the File.list() method
Then, I store the names in an ArrayList of ListItem objects, where ListItem is a self-created class.
But, ListItem is just a class that stores the string
class ListItem {
protected String itemName ="";
protected boolean isDir=false;
protected Double size=0.0;
}
However, after logging the first elements of both the array and the ArrayList (last 2 lines of the first code snippet), I get different results!
This is the log output:
03-15 20:29:46.427 465-465/com.harshal.filer I/filer: .userReturn
03-15 20:29:46.427 465-465/com.harshal.filer I/filer: Android
The second output,"Android" is an actual directory on the device.
But what's ".userReturn" and where did it come from???
Change your code to the following:
ArrayList<ListItem> list=new ArrayList<ListItem>();
String[] contents=cwFile.list();
for(int i=0;i<contents.length;i++){
ListItem curItem=new ListItem();
curItem.itemName = contents[i];
if(new File(cwd+contents[i]).isDirectory()){
curItem.isDir=true;
}
list.add(i,curItem);
}
Log.i("Main",list.get(0).itemName);
Log.i("Main",contents[0]);
You see I moved
ListItem curItem=new ListItem();
into the for-loop. If it's outside the reference of the item at position 0 in the list will always point to the latest entry in your array, thus the weird result.

ArrayDeque add multiple elements

Im using arraydeque to create list of items and pass them parameters(Items is class)
ArrayDeque<Item> Items= new ArrayDeque<Item>();
But I have problem with java ArrayDeque. Maybe there are ways to add more than one element at once.
For example. I want add at the same time TableType and colourOfTable into ArrayDeque.
In c++ I could have done it with this
vector<Item>Items
Items.push_back(Item("CoffeeTable", "brown"));
I want to do the same thing with Java. Instead of creating a new obj for every item, as:
ArrayDeque<Item> Items = new ArrayDeque<Item>();
Item obj = new Item("CoffeTable", "brown");
Items.add(obj);
Item obj1 = new Item("DinnerTable", "Black");
Items.add(obj1);
But instead of obj I want to add "CoffeTable", "brown" at the same time and with one code line (like in c++ example) into the Items array.
I tried something like that
ArrayDeque<Item> Items= new ArrayDeque<Item>();
Items.add(Items("CoffeTable", "brown"));
But then got the error while creating create method 'Items(String,String)'
You can simple create the new item in the call of add:
items.add(new Item("CoffeTable", "brown"));
So you don't need an explicit variable.
Also note that in Java variable names normally start with a lower case character.
You will have to create a new object anyway to hold these 2 values.
You can do this:
Items.add(new Item("CoffeTable", "brown"));
Anything else you come up with will be syntactic sugar for the above
For example: you can add a static method to your class:
public static Item item(String k1, String k2) {
return new Item(k1, k2);
}
And use it later:
Items.add(item("CoffeTable", "Brown"));
Here is a solution which would surely work. You can add a function to your class itemAdd() as follows:
class Samp {
public static void main(String args[]){
//code.....
ArrayDeque<Item> Items= new ArrayDeque<Item>();
Items.add(itemAdd("CoffeeTable", "brown"));
//rest of code....
}
public static Item itemAdd(String tableType,String colourOfTable){
return new Item(tableType,colourOfTable);
}
}
class Item{
String tableType;
String colourOfTable;
Item(String tableType,String colourOfTable ){
this.tableType=tableType;
this.colourOfTable=colourOfTable;
}
}
Its similar to what u need to do!! Best of luck :)

How can I convert a String to a String[] // Android development // Java

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

Categories

Resources