How do we add livedata to spinner in Java - java

How can we use livedata in spinners? I have the following:
ArrayAdapter<CharSequence> adapter;
LiveData<List<Site>> sites = SiteDatabase.getInstance(this).siteDao().getAllSites();
Spinner spinner = findViewById(R.id.spinnerSites);
adapter = new ArrayAdapter<Site>(this,
this,android.R.layout.simple_spinner_dropdown_item, sites); //What Goes Here ? This gives Cannot Resolve Constructor Error...
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Thanks!

You need to replace this line
adapter = new ArrayAdapter<Site>(this,android.R.layout.simple_dropdown_item_1line, sites);
with this
adapter = new ArrayAdapter<Site(this,android.R.layout.simple_dropdown_item_1line, sites.getValue());
The signature for your ArrayAdapter is like this ArrayAdapter(Context context, int resource, List<Site> objects). You are correctly passing the Context and int param however the last param needs to be a List<Site> instead of a LiveData<List<Site>.

Related

"this" gives me an error in fragment

Why does this give me an error in the below fragment?
This is my code:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
Try this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_spinner_item, spinnerArray);
getContext() was added only on API 23 and should work only with few devices (since Android M still does not have a huge market share).
getActivity() was added on API 11 and it is NOT deprecated.. So, you can use it.
Replace this with this.getContext() or even simply just getContext()
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_spinner_item, spinnerArray);
The reason being is that the constructor for an ArrayAdapter object looks like this,
From https://developer.android.com/reference/android/widget/ArrayAdapter.html,
ArrayAdapter(Context context, int resource, T[] objects)
or
ArrayAdapter(Context context, int resource, List<T> objects)
What was probably happening before is that the class that the line of code was in was most likely not of type Context; therefore, you can't use this alone as a parameter in the construction of an ArrayAdapter. If getContext() doesn't work, then I'd suggest trying getActivity() or getApplicationContext() as well.
Use getActivity() which return the context of the activity that the fragment is associated with.
So your code becomes
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, spinnerArray);`]
You can try getActivity().getApplicationContext() instead of using just this in fragment.

ArrayAdapter with Json Parsing

i'm doing a system of news feed, so, i've a difficulty for adapter my ArrayAdapter insert value into ListView, with: "username, name, picture, content and others values" i'm newbie in Android Studio.
Searching the internet I found this function
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.list_item,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
list.setAdapter(adapter);
But, i use ArrayList and ArrayAdapter:
ArrayList<Post> postList =
new JsonConverter<Post>().toArrayList(s, Post.class);
ArrayList<String> postador = new ArrayList<String>();
for(Post value: postList){
postador.add(value.id_postador);
postador.add(value.post_legenda);
if(value.post_foto != null) {
postador.add(value.post_foto);
}
postador.add(value.post_data);
postador.add(value.curtidas);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_list_item_1, postador
);
lvPost.setAdapter(adapter);
I tried it, but no success.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
R.layout.list_item, postador, new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
There a method convert ListAdapter in ArrayAdapter or adapter my ArrayAdapter for ListAdapter?
If you are a newbie to Android, I would like to recommend few things to you.
1). Start Using RecyclerView from the very beginning instead of ListView. It is more advanced, flexible and efficient version of ListView. You can find a sample demo for the RecyclerView here and here
2). If you still want to use ListView. Then you further have two options, either to use BaseAdapter or ArrayAdapter.
a). Base Adapter as the name suggests, is a base class for all the adapters. If you need more flexibility, you can go with it. You can find the demo sample here and here
b). On the other hand, ArrayAdapter is a concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView.If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.To use something other than TextViews (like in your case) for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want. You can find the demo sample here and here.
Hope it will help you in future and also I suppose you will get answer to your question in the specified demo samples. Thanks and have a good day.. :)

Migrating from a single dropdown list spinner to a dependant spinner using mySQL data

I have one spinner that populates with my SQL data. This works well. I now want to make it into a dependant spinner where the spinner I already have becomes the second or dependant spinner. I have added another spinner in my MainActivity.java. and it sucessfully retrieves the required mySQL data
#Override
protected void onPostExecute(Void args) {
// Locate spinner1 in activity_main.xml
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
// Spinner adapter
List<String> typesofjobsunique = new ArrayList<>(new LinkedHashSet<>(typesofjobs));
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item, typesofjobsunique));
Collections.sort(typesofjobsunique);
// Locate my spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
Collections.sort(worldlist);
What is the simplest coding approach to migrate from a single to a dependant spinner given the data retrieval itself works well for both spinners and I just want to make it dependant from the current independant format so
spinner1 typesofjobsunique only displays the
mySpinner worldlist
spinner choices from mySQL corresponding to that particular typeofjobunique.
Most of the questions on here relating to dependant spinners, are where the data is in strings.xml which is not very helpful with remote data.
I'm assuming I will need to split my one adapter into two separate adapters, but I am unclear how to proceeed.
From the way that Spinners work, if you want to implement dependence between them, you will need to use the current selection of one (spinner1) as the key for the list source of the other (mySpinner). You should implement an AdapterView.OnItemSelectedListener on spinner1 as recommended in the Spinner guide and set the list in mySpinner. See code below:
// Locate spinner1 in activity_main.xml
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
// Locate mySpinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
List<String> typesofjobsunique = new ArrayList<>(new LinkedHashSet<>(typesofjobs));
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item, typesofjobsunique));
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// **EDIT**
List<String> myWorldList = getWorldListForItem(parent.getItemAtPosition(pos));
Collections.sort(myWorldList);
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
myWorldList));
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
Collections.sort(typesofjobsunique);
The implementation for getWorldListForItem() should query your database in the desired way. A hash table could also be used.
Hope that this is useful.
EDIT
Based on your comments, the implementation for getWordListForItem() would look something like this:
List<String> getWordListForItem(String s) {
String json = queryMySQLDatabase(s);
List<String> results = parseJSONintoList(json);
return results;
}
Also, the AdapterView.getItemAtPosition(int pos) function returns a Java object of the type passed into the ArrayAdapter (which is a String in this case). Therefore getWordListForItem() takes a String argument.
As for the "Cannot resolve contructor ArrayAdaptor" error, please check the spelling (it's supposed to be ArrayAdapter not ArrayAdaptor). See ArrayAdapter documentation for more details... I've also fixed my implementation above to sort the list properly.

build list from array and allow list to be clickable

I'm trying to build and Android app:
How can I build a list on screen from an array and have the list be clickable?
with a value of the name to be able to use later stored in a String.
What I have now.
String game_list[] = {"game_0","game_2","game_3","game_3","game_4","game_5"};
for(int i=0; i<game_list.length; i++){
myText = myText + game_list[i] +"\n";
}
myTextView.setText("");
myTextView.append(myText);
Also you can use a spinner and adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, game_list); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Here's a super simple example that I have used: http://www.javacodegeeks.com/2013/06/android-listview-tutorial-and-basic-example.html.
You basically need to make a listview object and add it to whatever view you happen to be using. Then you add "extends ListActivity" to the activity and add your list to the listactivity like so:
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,R.layout.file_row, this.directoryEntries);
ListView fileList = (ListView) findViewById(android.R.id.list);
fileList.setAdapter(directoryList);
Call:
protected void onListItemClick(ListView l, View v, int position, long id)
to associate actions with your listview elements
You can build that with ListView control in android and here very good tutorial about it to get more understand how to build it with the array or from any other data source like from database
http://www.vogella.com/tutorials/AndroidListView/article.html
feed be back in any thing not obvious for you

How to use findViewById to get a ListView

I don't know why this code is using findViewById to get the list view. Isn't the list view native to the ContentView that I set earlier? If not how do I set up a ListView for that Content View? I really just want to know if the setting up of the list view is necessary.
setContentView(R.layout.imgp_activity_home);
final String[] values = new String[] {"No Docs", "Pending", "Processed"};
final ListView listview = (ListView) findViewById(R.id.???);
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i<values.length; i++) {
list.add(values[i]);
...
listview.setAdapter((ListAdapter) adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
...
I feel like I should be able to add the listener to the array list somehow.
This is the tutorial I used to get me started.
in you layout floder about the activity layout the XML file called imgp_activity_home.xml.in this file you may have the tags about<listview>. set tags like <listview android:id="#+id/listname">.then in the Java file you can findviewbyid(r.id.listname).if you didn't declare the listview tag.you must new a listview object in you code.
From the example you should write
final ListView listview = (ListView) findViewById(R.id.listview);

Categories