Old values get duplication in For each loop - android

I am getting values from Firebase. But the problem occur when i try to add values in array previous values get repeated. Can anyone tell me how can i put values in Array . i want to show those values in recyclerview.
Code :
bookCollection
.get().addOnSuccessListener {
booksSnapshot->
if (!booksSnapshot.isEmpty){
var booksArray = arrayListOf<Book>()
for (bookSnapshot in booksSnapshot.documents){
val hashmap = bookSnapshot.data
hashmap?.put("id", bookSnapshot.id)
bookCollection.document(bookSnapshot.id).collection("pages")
.get().addOnSuccessListener {
pagesSnapshot->
hashmap?.put("page_count", pagesSnapshot.documents.size)
val bookData = Gson().toJson(hashmap)
val book = Gson().fromJson<Book>(bookData, Book::class.java)
booksArray.add(book)
}
}
}
}
Log for array :
E/books: [co.myapp.myapplication.Book#d6f7f62]
E/books: [co.myapp.myapplication.Book#d6f7f62, co.syntags.myapplication.Book#93c49b0]
Thanks in advance

You have to clear your ForEach loop booksArray before adding new values.
Because when you are adding new values that is added as the next items in your array.
Use booksArray.clear() Before adding new values where you are using booksArray.add(book)
Replace this var booksArray = arrayListOf<Book>() With var booksArray = ArrayList<Book>()

in main class (List add) :-
(Yourlistname).add(new yourpojoname(your value));
in PoJo class :-
create constructor :-
--> public constructorName(String s) { (Your value) = s; }
note :- yourpojoname == constructorName

Related

Loop through two arrays while checking if both are are empty or not onClick of a button

I am stuck with something that might be trivial to many but it has become a problem for me.
Basically I am trying to loop thru two string arrays one of which has a static size and another which has variable size and may also be 0.
So my goal is to loop thru both of them while iterating through the first array and getting the values of the second array with the value of the first and loop completely through the second array.
However if the second array is empty I want to increase the index of the first array and query for the second array and go on till the first array and it's inner arrays are completely iterated.
Sounds easy but I am having a tough time writing something that works.
My code :
var array1 : ArrayList<String> = ArrayList() // static value say 10
var array2 : ArrayList<String> = ArrayList() // may vary
var array1index = 0
var array2index = 0
array1 = getArray1Value()
button.setOnClickListener {
if(array1index<array1.size){
array2 = getByArray1Value(array1[array1index])
if(array2.isEmpty()){
//increase array1 index
if(array1index<array1.size){
array1index+=1
array2 = getByArray1Value(array1[array1index])
// ....... ?
}else{
over()
}
}else{
if(array2index<array2.size){
array2index+=1
}else{
over()
}
}
}else{
over()
}
I think it is getting more complicated than it is supposed to....please help.
Check this
private void doStuff() {
if(array1index<array1.size){
array2 = getByArray1Value(array1[array1index])
if(array2.isEmpty()){
array1index+=1
doStuff();
}else{
if(array2index<array2.size){
array2index+=1
}else{
over()
}
}
}else{
over()
}
}
Hope this is what you are trying to achieve
If any newbie gets confused with something like this here is the answer:
val array1 : ArrayList<String> = ArrayList() // static value say 10 items
var array2 : ArrayList<String> = ArrayList() // may vary
var array1index = 0
var array2index = 0
array1 = getArray1Value()
array2 = getByArray1Value(array1[array1index])
button.setOnClickListener {
if(array1index<array1.size){
mLog.i(TAG,"number of questions : ${array2.size}")
if(array2index<array2.size){
mLog.i(TAG,"1 activity index $array1index question index $array2index ")
array2index+=1
}else{
MaterialAlertDialogBuilder(context).setTitle("Questions over")
.setMessage("ok thicha")
.setPositiveButton("ok"){
dialogInterface, i ->
dialogInterface.dismiss()
array2index =0
array1index+=1
if(array1index<array1.size){
array2 = getByArray1Value(array1[array1index])
}
button.callOnClick()
}.create().show()
}
}else{
over()
}
}

How to assign Json Array into spinner list?

I have a JSON sample list as below and I tried to put this into my spinner:-
[{"occupation_id":0,"occupation_name":"Teacher"},{"occupation_id":1,"occupation_name":"Business Owner"}]
When I tried to apply these code:-
val jsonArray = JSONArray(jsonString)
var list = ArrayList<Occupation>()
var x = 0
while (x < jsonArray.length()) {
var jsonObject = jsonArray.getJSONObject(x)
list.add(Occupation(
jsonObject.getString("occupation_id"),
jsonObject.getString("occupation_name")
))
x++
}
var spinnerOccupation = findViewById<Spinner>(jasiez.helloworld.jasiez.R.id.spinnerOccupation)
// Initializing an ArrayAdapter
val occupationAdapter = ArrayAdapter(
this, // Context
android.R.layout.simple_spinner_item,
list// Array
)
occupationAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line)
spinnerOccupation.adapter = occupationAdapter
I getting this in my spinner
When I tried to change
val occupationAdapter = ArrayAdapter(
this, // Context
android.R.layout.simple_spinner_item,
list// Array
)
to
val occupationAdapter = ArrayAdapter(
this, // Context
android.R.layout.simple_spinner_item,
list.occupation_name.toList()
)
I getting error Unresolved reference: occupation_name. If I change to list[0].occupation_name.toList() I will show 1st occupation name with 1 char in every single dropdown list option.
How can I get proper occupation name in each option here? Please help.Thank you.
When you are using ArrayAdapter, you can only pass the list of String (List), You can't pass like List so make the list like below:
var list = ArrayList<String>()
.......
list.add(jsonObject.getString("occupation_name"))
I have also encountered the same when dealing with JSon. What I did is I override toString from my Object. In your case, you can override a toString to your occupation name from your Occupations Object.
public class Occupation {
int occupation_id;
String occupation_name;
public Occupation() {
}
public int getOccupation_id() {
return occupation_id;
}
public void setOccupation_id(int occupation_id) {
this.occupation_id = occupation_id;
}
public String getOccupation_name() {
return occupation_name;
}
public void setOccupation_name(String occupation_name) {
this.occupation_name = occupation_name;
}
//converts your occupation_name to string
#NonNull
#Override
public String toString() {
return occupation_name;
//or you can also add title to your occupation name by doing this
//return "Occupation: "+ occupation_name;
}
}
Check out if this works for you.
You can write a custom adapter to hold your data list, and override getview to set the values in spinner's textview. Have a look at this link to see an example.

Arraylist filter?

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.

How to remove an object form the List but not from Realm

I'm getting the
Removing is not supported.
while trying to remove an item from the list:
List<Animal> animals = realm.allObjects(Animal.class);
animalsForFragment = createAnimals(animals);
private Map<Integer, Animal> createAnimals(List<Animal> animals) {
Map<Integer, Animal> animalMap = new HashMap<>();
for (Animal animal: animals){
if (animal.getUniqueId() == animalId) {
animals.remove(animal);
animalMap.put(1, animal);
}
}
...
}
I suppose it happens because Realm thinks that I want him to delete this record but I just want to work with current snapshot of this list. How can I do that?

Get Data from ArrayList Model class in android

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

Categories

Resources