Android Development-ExpandableList(Headername,arraylist):
I have these two arraylists headerArrayList<Category> and subHeaderArraylist<ItemDetails>.
Category Class contains headerid, headername, Item Class contains headerid,subheadername;
Now, I need to filter out
if headerid of headerArrayList equals headerid of subHeaderArraylist, then result the subheadername of subHeaderArraylist ( which has same headerid).
My code:
List<ItemDetail> result = new ArrayList<ItemDetail>();
for(int i=0;i<headerArraylist.size();i++){
Category cat =new Category();
String category=headerArraylist.get(i).getHeader();
String headeridd=headerArraylist.get(i).getHeaderid().trim();
cat.setHeader(category);
for (ItemDetail itemDetail : subheaderArrayList) {
if (itemDetail.getHeaderid().toLowerCase().contains(headeridd.toLowerCase())) {
result.add(itemDetail);
cat.setItemList(filterlist);
}
}
catList.add(cat);
Now i fill the catList to Expandable adapter:
ExpandableListAdapter exAdpt = new ExpandableListAdapter(catList, this);
exList.setAdapter(exAdpt);
}
Lets say, headerArraylist contains {(H0001,Cosmetics),(H0002,Snacks)} and subheaderArrayList contains {(H0001,Mens Cosmetics),(H0002,PotatoChips)}.
When i tried to filter with headerid=H0001, it returns all subheadername viz Mens Cosmetics,Potatochips.
But, I did not get the output as expected as it returns all subheadername, not filtering out. Kindly suggest me what could have been wrong.
Related
I am having a pretty difficult situation which I just can`t find a solution for.
I have a sections recyclerview which I fill with data through an arraylist, this data contains URL links and normal text.
The normal text should be set as a section in the recyclerview and the URLs as the items. The tricky part is that the arraylist needs to be in a specific order with the sections.
So the recylcerview should look like this for example:
URL
Section 1
URL
URL
Section 2
URL
URL
URL
URL
Section 3
etc...
I first tried to modify (remove) items from the arraylist itself but it won`t work as the sections and URLs are then out of order as they should be.
I then thought to load the whole list into the recylerview and before showing it remove the relevant items (marked as dummy in below code) from the SimpleAdapter but this doesn`t work in a for loop.
So how can I remove the dummy items from the adapter or arraylist without losing the order of the sections and URLs shown in the recylcerview?
In below code I fill the arraylist and set the sections.
public static List<String> test = new ArrayList<>();
int k = 0;
for (String str : Arrays.asList(lines)) {
str = unescapeJavaString(String.valueOf(Html.fromHtml(str)));
if (!str.contains("some info")) {
// if it is a URL add to arraylist, otherwise set section at relevant position in adapter.
if (str.startsWith("http")) {
test.add(k, str);
} else {
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(k, str));
test.add(k, "dummy"); // add dummy which should be removed.
}
k++;
}
}
Removing it from the adapter, does not work either:
int i = 0;
...
mAdapter = new SimpleAdapter(this, sCheeseStrings, userID, dlTypeValue);
...
recyclerView.setAdapter(mSectionedAdapter);
Iterator itr = test.iterator();
String strElement = "";
while (itr.hasNext()) {
i++;
strElement = (String) itr.next();
if (strElement.equals("dummy")) {
mAdapter.remove(i);
mAdapter.notifyItemRemoved(i);
}
}
I am using Gson library for pasring json,
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
PropertyModel[] response = gson.fromJson(reader, PropertyModel[].class);
i had set all data in Araylist like
Arraylist<PropertyModel[]> model=Arraylist<PropertyModel[]>();
model.add(response);
Now My problem is i am not able to get Arraylist PropertyModel class data
Please suggest me how can get Value from ArrayList
Thanks in Advance
try this code it will probably work...
String responseString = jsonArray.toString();
Log.e("jsonArray string --->", "" + responseString);
Type listType = new TypeToken<ArrayList<ModelOneVOneListItem>>() {
}.getType();
yourArrayList = new Gson().fromJson(responseString, listType);
First add values in Arraylist . Assume your modelclass name is CorpusHeadingModel:
ArrayList<CorpusHeadingModel> lemmaHeadingList = new ArrayList<CorpusHeadingModel>();
CorpusHeadingModel headingModel = new CorpusHeadingModel();
headingModel.setLemmaWord("Apple");
headingModel.setLemmaOccurance("3");
// now add the values to the list :
lemmaHeadingList.add(headingModel);
Now, Retrive one value with list position or any number corresponding the length of lemmaHeadingList :
CorpusHeadingModel model = lemmaHeadingList.get(position);// "position" or any number value according to your lemmaHeadingList.size().
String word = model.getLemmaWord();
String countWord= model.getLemmaOccurance();
Toast.makeText(mContext, "word= " +word+" Occurance= "+ countWord, Toast.LENGTH_SHORT).show();
Output:
word= Apple Occurance= 3
Hope, It helps, to retrieve any string from a list with modelClass.
Try like this
Add in Array list
ArrayList<String>() AddList= new ArrayList<String>();
Values = jb.getString("Your value");
AddList.add(Values);
Then Convert Array List to String Array
String[] BrandNameArray = new String[AddList.size()];
BrandNameArray = AddList.toArray(BrandNameArray);
use the Array
Your way is wrong assigning Array to Arraylist change last two lines:-
change these two line in the code
Arraylist<PropertyModel[]> model=Arraylist<PropertyModel[]>();
model.add(response);
to this:-
Arraylist<PropertyModel> model = new ArrayList<PropertyModel>(Arrays.asList(response));
For getting values you can use for loop
for(int i=0 ; i<model.size() ; i++){
PropertyModel object = model.get(i); //getting single object from Arraylist
}
as we know arraylist uses index to store values we must provide it an index but when its associated with a model class, it can be done in two ways.
let me give you an example.
1) you use your arraylist in the recycler adapter and get its object value using position,
holder.name.setText(myarraylist.get(position).getName()); // for recycler adapter in "onBindViewHolder"
name.setText(myarraylist.get(position).getName());//for base adapter in getview
2) if you want to check your object values in arraylist before passing it to the adapter you can do it this way,
for (contact d :emps ){
Log.e("name object of array",d.getName()+""); // getting the required object using the instance of model class
}
where contact is the model class, which is also the type of the arraylist emps. I hope this helps you. good luck
I would like to know a way to store an image and associated text in something like a List. I tried doing something like this
List<NameValuePair>cars = new ArrayList<NameValuePair>();
cars.add(new BasicNameValuePair("Hyundai Elantra",Integer.toString(R.drawable.hyundai_elantra)));
I know this is wrong but I'm posting it so you get an idea of what I'm trying to achieve.
It looks like the best thing for you would be to create a custom class called Car to store each car, and then create an ArrayList<Car> to store the data.
Here is what your Car class would look like:
public class Car
{
public String type;
public int imageID;
public Car(String t, int i)
{
type = t;
imageID = i;
}
public String toString()
{
return type + " " + String.valueOf(imageID);
}
}
Then you would declare the ArrayList, and add values:
ArrayList<Car> carList = new ArrayList<Car>();
carList.add(new Car("Hyundai Elantra", R.drawable.hyundai_elantra));
carList.add(new Car("Lexus RX350", R.drawable.lexus_rx350));
Then, you could iterate through the list when you want to populate your UI:
for (Car c : carList){
String s = c.type;
int image = c.imageID;
//use the values.......
}
Note that you could use this ArrayList as the data source for a custom adapter for displaying the text and images in a ListView, if that's what you're looking to do.
you can create a class named NameValue with Textand Image and you can declare an array list as follows
List<NameValue >cars = new ArrayList<NameValue >();
if (status == 200) {
String result = EntityUtils.toString(response.getEntity());
Log.d("Response", result);
ArrayAdapter < String > adapter = new ArrayAdapter < String > (getActivity(),
android.R.layout.simple_list_item_1, result);
setListAdapter(adapter);
}
I am unable to set my response into my List. I get my response as
{
"Appointments": [{
"Name": "Kevin",
}, {
"Name": "John",
}]
}
How would i set my name parameter in the listView.
How would i set my name parameter in the listView.
At a glance. Third parameter of ArrayAdapter should be collection but you are passing only simple String. According to your JSON i recommend you:
Create own object that will represent Person with properties(name,
age, etc.)
Parse JSON and create collection of persons
Set collection to ListAdapter
Example:
public class Person {
private String name;
...
// getters and setters
#Override
public String toString() {
return this.name;
}
}
Then, you need to parse JSON and get proper data:
List<Person> persons = new ArrayList<Person>();
Person person = null;
JSONObject root = new JSONObject(sourceString);
JSONArray appointments = root.getJSONArray("Appointments");
JSONObject child = null;
for (int i = 0; i < appointments.length(); i++) {
child = appointments.getJSONObject(i);
if (child != null)
person = new Person();
person.setName(child.getString("Name"));
persons.add(person);
}
}
Then initialise ListAdapter:
new ArrayAdapter<String>(getActivity(), layout, persons);
and now you got it.
Note:
Reason why i'm overriding toString() method is that since you are using default ArrayAdapter with build-in Android layout each object in your List will be converted to String and will be shown in ListView but if i don't override toString() it won't return person's name but string representation of object that is human-unreadable string.
result is a String containing the entire response. You need to parse or split that string into the items that you want.
You need to give your adapter the items (either as a list or an array). Right now you've created an adapter but haven't provided it any data via the constructor or any setter.
I suggest you read more about ListViews and Adapters on the Android developers site.
I am working on an application for Android. For this I am making an Activity in which you select your country and then a spot in that country. I have one spinner that contains a list of all available countries. Now, what I want it to do is get the country that has been selected, then filter a list of spots that I have for the items that start with the country that has been selected. Then it should put the spots for the selected country into a different spinner. Just for clarity, the list of countries is just a list of countries, and the list of spots looks like:
Country1 - Spot1
Country1 - Spot2
Country2 - Spot1
Country2 - Spot2
And so on.
This is what I thought the code should work like:
Get selected country from spinner 1.
Make a new ArrayList containing the spots.
Make a second empty ArrayList.
For each entry of the ArrayList containing the spots, check if it starts with the selected country.
If so, add it to the second ArrayList.
Once this is all done, make an ArrayAdapter with the second ArrayList.
Set this ArrayAdapter for spinner 2.
I tried to achieve this with the following code:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
ArrayList<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(R.array.spots_array);
ArrayList<CharSequence> arraylist2 = new ArrayList<CharSequence>();
for (i=0; i<arraylist.size(); i++) {
String delimiter = " - ";
if ((arraylist(i).split(delimiter)).equals(selectedCountry)) {
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, arraylist2<CharSequence>, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
But it gives several errors:
At addAll() it says: "The method addAll(int, Collection) in the type ArrayList is not applicable for the arguments (int)"
At arraylist it says: "The method arraylist(int) is undefined for the type Configuration"
At string (inside substring) it says: "string cannot be resolved"
I am still relatively new to Android, and am having a lot of trouble getting this working. Can anybody please help me out?
There is a lot of little mistakes in your code :
To access an element in an arraylist use the get(position) method
When you add your "spot_array", you actually add the id of the resource, not the array itself (see here)
Here is your code updated, it should works or may need some tweaks
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
List<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(Arrays.asList(getResources().getTextArray(R.array.spots_array)));
List<CharSequence> arraylist2 = new ArrayList<CharSequence>();
String delimiter = " - ";
for (int i=0; i<arraylist.size(); i++) {
String country = arraylist.get(i).toString();
if (country.contains(selectedCountry)) {
arraylist2.add(country.substring(country.lastIndexOf('-') + 2));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, android.R.id.text1, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
You have several errors in your code.
Firstly, the method addAll of the ArrayList must take as an argument a Collection. You are passing an Android array id R.array.spots_array; bear in mind that the Android ids are integers.
The usually method to fetch a string array from Android resources is (inside an activity):
String[] myArray = getResources().getStringArray(R.array.spots_array);
Second error: you should access the ArrayList elements by calling the method get(position) , not directly (arraylist(position)). Something like arraylist.get(position).
Third error:
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
should simply be arraylist2.add(arraylist.get(i)); for adding one list element to another.
More on ArrayLists can be found here.