How to assign Json Array into spinner list? - android

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.

Related

Xamarin.Android listview getPosition method returns object

I have a Listview and I want to take the item at clicked position. But GetItemAtPosition method return Object and casting is not working. I assigned it to a "var" type variable but in this case I can not get properties and method of Person object. What sould I do? Thank you.
persons.Add(new Person("Random Name", "Merhaba", Resource.Drawable.image));
persons.Add(new Person("Random Name", "Merhaba", Resource.Drawable.image));
ListView listView = (ListView)FindViewById(Resource.Id.listView);
PersonAdapter adapter = new PersonAdapter(this,persons);
listView.Adapter = adapter;
listView.ItemClick += (object sender, ItemClickEventArgs e) =>
{
Person person = listView.GetItemAtPosition(e.Position); // this line gives error. (Cannot implictly convert type "Java.Lang.Object" to Person)
Toast.MakeText(this.ApplicationContext, person.Name, ToastLength.Short).Show();
var intent = new Intent(this, typeof(ChatActivity));
this.StartActivity(intent);
};
enter image description here
Use listview ItemSelected
private void Handle_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (((ListView)sender).SelectedItem == null)
{
return;
}
else
{
var obj = (Person)e.SelectedItem;
}
}
The IDE could not convert the type of object in Adapter when building the project .So you could explicit convert it manually.
Person person = (Person)listView.GetItemAtPosition(e.Position);

Old values get duplication in For each loop

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

Sorting adapter on particular array

I have a collection of object assigned to an adapter set to a listview. I know how to sort an adapter value when it contains single object. My question is how do I sort the collection only on the data datatype. Below is my collection
you = new MyVideoAdapter(getActivity(),vDancers,video, vName, vDanceStyle, vOwner, dCountry, vPic, vCreated, fullname,
vLikes,vComments, vViews,vRepost, objectID, nLikes, nComments, nRepost, vUserID, postType);
//you.comp
listView.setAdapter(you);
I want to sort this adapter (you) by the vCreated which is an array of dates. Thanks in advance for any help.
For those looking for a solution, this is how I went about it (I don't know if its the best solution but it does work for my case).
1. Instead of populating the adapter with the individual arrays, I created an ArrayList and populated it with my arrays.I sorted it using compareTo().
public class Items implements Comparable<Items>{
private final Number vLikes; private final Number vComments; private final Number vRepost; private final Number vViews;
private final Date vCreated;
public Items(Number vLikes, Number vComments, Number vViews, Number vRepost, Date created) {
this.vCreated = vCreated;
this.fullname = fullname;
this.vLikes = vLikes;
this.vComments = vComments;
this.vViews = vViews;
this.vRepost = vRepost;
}
#Override
public int compareTo(Items o) {
if (getvCreated() == null || o.getvCreated() == null)
return 0;
return o.getvCreated().compareTo(getvCreated());
}
public Number getvLikes() {
return vLikes;
}
public Number getvComments() {
return vComments;
}
public Number getvViews() {
return vViews;
}
public Number getvRepost() {
return vRepost;
}
public Date getvCreated() {
return vCreated;
}
}
2. I then sort the arraylist using the date column and using Collections to apply the sorting.
List<Items> myList = new ArrayList<Items>();
Items item = new Items(a,b,c,d);//a, b, are my variables
myList.add(item);
3. I populated my adapter with the sorted arraylist.
Collections.sort(myList);
you = new MyAdapter(getActivity(), myList);
I hope this helps.

Cannot save null column value in ActiveAndroid

To make it simple, I have this model:
#Table(name = "Items")
class TItem extends Model {
#Column(name = "title")
private String mTitle;
public String getTitle() { return mTitle; }
public void setTitle(String title) { mTitle = title; }
}
And I'm failing in my testings doing that:
//Create new object and save it to DDBB
TItem r = new TItem();
r.save();
TItem saved = new Select().from(TItem.class).where("id=?", r.getId()).executeSingle();
//Value for saved.getTitle() = null --> OK
r.setTitle("Hello");
r.save();
saved = new Select().from(TItem.class).where("id=?", r.getId()).executeSingle();
//Value for saved.getTitle() = "Hello" --> OK
r.setTitle(null);
r.save();
saved = new Select().from(TItem.class).where("id=?", r.getId()).executeSingle();
//Value for saved.getTitle() = "Hello" --> FAIL
It seems I cannot change a column value from anything to null in ActiveAndroid. Very strange. Is it a bug? I didn't find anything about it, but looks pretty basic this functionallity.
If I debug the app and follow the saving method, the last command it reaches is in SQLLiteConnection.java:
private void bindArguments(PreparedStatement statement, Object[] bindArgs) {
....
// It seems ok, as it is really inserting a null value in the DDBB
case Cursor.FIELD_TYPE_NULL:
nativeBindNull(mConnectionPtr, statementPtr, i + 1);
....
}
I cannot see further, as "nativeBindNull" is not available
Finally I found what happened, and the problem is in ActiveAndroid library.
The null value is saved propertly to DDBB, but is not retrieved correctly. As ActiveAndroid uses cached items, when getting an element, it gets an "old version" and updates it with the new values. Here is where the library fails, because is checking that if not null replace the value, otherwise, nothing.
To solve this, we'll have to change it from the library, in the class Model.java:
public final void loadFromCursor(Cursor cursor) {
List<String> columnsOrdered = new ArrayList<String>(Arrays.asList(cursor.getColumnNames()));
for (Field field : mTableInfo.getFields()) {
final String fieldName = mTableInfo.getColumnName(field);
Class<?> fieldType = field.getType();
final int columnIndex = columnsOrdered.indexOf(fieldName);
....
if (columnIsNull) {
<strike>field = null;</strike> //Don't put the field to null, otherwise we won't be able to change its content
value = null;
}
....
<strike>if (value != null)</strike> { //Remove this check, to always set the value
field.set(this, value);
}
....
}
....
}

Using Arrays.asList and compare

I have an array like the next:
this.ntpServers[0][0] = "Global";
this.ntpServers[0][1] = "pool.ntp.org";
this.ntpServers[1][0] = "Africa";
this.ntpServers[1][1] = "africa.pool.ntp.org";
this.ntpServers[2][0] = "Asia";
this.ntpServers[2][1] = "asia.pool.ntp.org";
this.ntpServers[3][0] = "Europe";
this.ntpServers[3][1] = "europe.pool.ntp.org";
this.ntpServers[4][0] = "North America";
...
this.ntpServers[85][0] = ...
this.ntpServers[85][1] = ...
I have in another String a country, and I am trying to use the next code to compare if exist in the list, but Iit doesn't returns me a true, when it must be true. If I check for "Asia" it would be true. But something is wrong.
gettedCountry is a String
public int existNTP(String[][] list) {
if(Arrays.asList(list).contains(gettedCountry)){
Log.i("Found", "Found");
}
return position;
}
Thank for your help.
Either make proper objects to turn your two-dimentional array into a list (recommended)
OR
iterate over your array:
int position = 0;
for (String[] entry : ntpServers) {
if (entry[0].equals(country)) return position;
++position;
}
return -1; // Not found is an invalid position like -1
Arrays.asList(list) will return an ArrayList of String[] not String. If you need to check for the first item:
ArrayList<String[]> arr=Arrays.asList(list);
for(String[] arry : arr){
if(arry[0].equals(gettedCountry)) /* Do your stuff */;
}

Categories

Resources