Cannot fill ListView with Items in Android - java

I am trying to fill a ListView with Items. Everything seems to work perfectly but ListView doesn't show Items. I am wondering if I miss a step here.
Please take a look at my code below;
ListView listView = (ListView) myView.findViewById(R.id.listViewLocations);
List<WMS_Location> list = (List<WMS_Location>) response.body();
String listViewItems[] = new String[list.size()];
for (int i=0;i<list.size();i++)
{
listViewItems[i]= list.get(i).getCode().toString().toUpperCase();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, listViewItems);
listView.setAdapter(adapter);
NOTE: I am sure that listViewItems is not empty and it has 5 string object in it.

Related

Application crashing when click on any item in ListView

I am a beginner in Android studio and I am having hard time to debug this issue.
when any item in my ListView gets clicked the application crashes, here is the class for the OnItemClick. The objective is to change the ListView from the Categories to the items inside the categories. The Categories and items are stored in a HashMap <String, String[]>, so passing the value of cat.toString() should return the string containing the category. Lastly using myList (Stored outside of the function) should return an array of string containing the items. However, when I click any of the items the application instantly crashes. Thanks for your help!
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Choosen category
TextView cat = (TextView) view;
ArrayList<String> tempItems = new ArrayList<String>();
//Toast.makeText(this, cat.getText().toString(),Toast.LENGTH_SHORT).show();
listAdapter.clear();
for(String val : myList.get(cat.getText().toString())){
tempItems.add(val);
}
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,tempItems);
listAdapter.notifyDataSetChanged();
}
Variables
ListView myViewList;
Map<String, String[]> myList = new HashMap<String, String[]>();
ArrayAdapter<String> listAdapter;
Populating the ListView
//Creating a list of all categories
Set<String> myListKeys = myList.keySet();
ArrayList<String> categories = new ArrayList<String>();
for(String val : myListKeys){
categories.add(val);
}
//String[] categories = myListKeys.toArray(new String[myListKeys.size()]);
//Populating list
myViewList = (ListView) findViewById(R.id.groceryList);
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,categories);
myViewList.setAdapter(listAdapter);
myViewList.setOnItemClickListener(this);
You are getting exception because you are using listAdapter.clear(); which tries to clear the List inside the adapter. But apparently you have passed an array (String[] categories) which cannot be cleared. You should convert the array to ArrayList, (not just List) by iterating through it and pass it into the adapter.
You should create the adapter by passing ArrayList
What do you think you're doing by creating a new adapter inside the onItemClick of old adapter?
Inside the onItemClick, don't create a new adapter. Instead, after clearing the adapter and creating a temp ArrayList, add all the temp ArrayList to the adapter.
listAdapter.addAll(tempItems);
Also to get text from a TextView, use cat.getText().toString(); instead of cat.toString();

constructor cannot resolve Array adapter in android

I don't know what error I did. But it shows me can not resolve constructor Arrayadapter on my array adapter code.Help me to fix it out.( I have used getActivity() because I have written this code on my fragment section) and it gets crashes after it.I have tried almost all issue fixing methods in stack overflow .(Before down voting suggest me some solutions )
spinner = (Spinner) view.findViewById(R.id.spinner3);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,getActivity(),android.R.layout.simple_spinner_item,def);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
here is my error log
Try this, if you use a fragment:
1. This code is designed to fetch a static array
ArrayAdapter myAdapter = ArrayAdapter.createFromResource(
getActivity(), R.array.my_array, android.R.layout.simple_spinner_item);
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(myAdapter);
2. If you are fetching a dynamic array, then the below sample code would work.
In this sample, I've fetched the list from db. You can change upon your requirement.
Spinner maritalSpinner = (Spinner) view.findViewById(R.id.marital_spinner);
List<MaritalStatus> maritalStatusList = new ArrayList<>();
List<String> maritalStatusArray = new ArrayList<>();
maritalStatusList = dbConnection.getMaritalStatus(maritalStatusDao);
maritalStatusArray.clear();
maritalIdArray.clear();
maritalStatusArray.add("~Select~");
maritalIdArray.add(0l); // this is number '0' and alphabet 'l'(small 'L') not number '1'
for (MaritalStatus marital : maritalStatusList) {
String maritalStatus = marital.getMaritalStat();
long maritalId = marital.getMaritalId();
maritalStatusArray.add(maritalStatus);
maritalIdArray.add(maritalId);
}
maritalAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, maritalStatusArray);
maritalAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
maritalAdapter.notifyDataSetChanged();
maritalSpinner.setAdapter(maritalAdapter);
your are passing to Context to your adapter so just pass one context
if your spinner in fragment than just change your adapter like this
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,def);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);

Using 1 spinner to dynamically change 2 spinners with if functions and notifyDataSetChanged?

Pretty new to Java in general. I have 3 Spinners in my code, and my 2 spinners would display lists depending on 1 main spinner ( which has 2 selections). After reading a few threads I read about refreshing the lists using notifySetDataChanged(); but the spinner lists never changed. Few questions :
Am I using the notifySetDataChanged correctly?
Is there another way to populate the lists?
Is the IF function the appropriate method?
Here's the code upto the onCreate method.
public class MainActivity extends Activity {
private Spinner spinner1, spinner2, spinner3, spinner4;
private Button convertButton;
private EditText from;
private List <String> list1 = new ArrayList<String>();
private List <String> list2 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
from = (EditText) findViewById(R.id.amount);
//spinners for units
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner4 = (Spinner) findViewById(R.id.spinner4_main);
List<String>list4 = new ArrayList<String>();
list4.add("Distance");
list4.add("Weight");
//adapter for main scale
ArrayAdapter<String> dataAdapter4 = new ArrayAdapter <String> (this,
android.R.layout.simple_spinner_dropdown_item, list4);
dataAdapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner4.setAdapter(dataAdapter4);
//adapter for "from" currency
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter1);
//adapter for "to" currency
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list2);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter2);
Object choice = spinner4.getSelectedItemPosition();
if (choice.equals("Weight")) {
//units to convert from
dataAdapter1.clear();
dataAdapter1.add("Milligrams");
dataAdapter1.add("Grams");
dataAdapter1.add("Kilograms");
dataAdapter1.add("Metric Ton");
//units to convert to
dataAdapter2.clear();
dataAdapter2.add("Milligrams");
dataAdapter2.add("Grams");
dataAdapter2.add("Kilograms");
dataAdapter2.add("Metric Ton");
}
else //(spinner4.getSelectedItem().toString().equals("Distance"))
{
//spinner1 = (Spinner) findViewById(R.id.spinner1);
dataAdapter1.clear();
dataAdapter1.add("Millimeter");
dataAdapter1.add("Centimeter");
dataAdapter1.add("Meter");
dataAdapter1.add("Kilometer");
dataAdapter2.clear();
dataAdapter2.add("Millimeter");
dataAdapter2.add("Centimeter");
dataAdapter2.add("Meter");
dataAdapter2.add("Kilometer");
}
dataAdapter1.notifyDataSetChanged();
dataAdapter2.notifyDataSetChanged();
}`
If anyone could explain what's wrong please enlighten this newbie. =)
U are approaching this wrong. Here is what you should do..
Define Spinner 1, 2 and 3.
Define arrayAdapters for spinner 1,2,3.
Populate ArrayAdapter and define this as the adapter for Spinner 1 (spinner1.setadapter(arrayadapter1)
Then call the spinner1.setOnItemSelectedListener. In the method onItemSelected, populate the logic to populate the array for spinner 2 and spinner 3 as per your requirement. Then call spinner2.setadapter(arrayadapter2) and spinner3.setadapter(arrayadapter3).
This should work.
So initially, spinner2 and spinner3 will not have any content. even if user clicks, there will be nothing in the dropdown. But once Spinner1 is selected by user, spinner2 and spinner3 will have dropdown values.
Please read up on setOnItemSelectedListener. Lots of tutorials are available. You can refer here to get a start.
If this works for you, please accept my answer.
Object choice = spinner4.getSelectedItemPosition();
This can't work.
getSelectedItemPosition()
returns an int (documentation) which won't equal your String as in
if (choice.equals("Weight")
Never ever (except in rare occasions) use the Object class as a reference, as any and every object in Java will be an Object (duh!) so you probably compare apples with oranges (which both are fruits). Seems like you're coming from a more weakly typed language, eh? ;)
Solution: Compare the positions:
if (spinnerX.getSelectedItemPosition == 0)...
Also, are you sure you want to change the content of spinner1 if something is selected on spinner4?

Update ListView on item delete or rename

I have the following code in a tabbed Fragment:
private SetRowsCustomAdapter adapter;
private ArrayList<SetRows> rowsArray = new ArrayList<SetRows>();
for (Map.Entry<String, String> current_file:filesInFolder.entrySet()) {
rowsArray.add(new SetRows(R.drawable.ic_launcher, current_file.getKey().toString(), current_file.getValue().toString()));
}
adapter = new SetRowsCustomAdapter(getActivity(), R.layout.customlist, rowsArray);
dataList = (ListView) mFrame3.findViewById(R.id.lvFiles);
dataList.setAdapter(adapter);
}
getActivity().deleteFile(txt + ".trp");
adapter.remove(adapter.getItem(info.position));
adapter.notifyDataSetChanged();
startActivity(new Intent(getActivity(), MainActivity.class).putExtra("tab", 2));
which deletes a row within my ListView and starts a new activity to show the changes. Although I have the adapter.notifyDataSetChanged(), it doesn't display the changes once a row is deleted without the last line on the code above.
Can someone please help me fix that so it shows the changes without starting a new activity.
Use of custom adapter is better for it, these link will help you for it
Remove ListView items in Android
How to remove arraylist item and then update listview
I think you require to delete from arraylist then call adapter setNotifyDataChange(), b'cos when you call this function it reload the adapter from arraylist.

how to create dynamic Spinners in android?

this code is working fine but its creating only one spinner dynamically i want to get value from database and want to run the loop till database values and generate dynamic Spinner inside the loop overhere i have mentioned the code of FOR LOOP but its not working and as well as i want to load different item in different spinner please give me idea how to do this?
public class DisciplineActivity extends Activity
{ ArrayList<String> selectDisciplineArrayList,disciplineInfoArrayList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.discipline_view);
for(int i=0;i<20;i++)
{
disciplineInfoArrayList.add("select location item:"+i);
}
// for(int i=0;i<5;i++)
//{
Spinner disciplineInfoSpinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,disciplineInfoArrayList);
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
disciplineInfoSpinner = (Spinner) findViewById(R.id.disciplineinfo_spinner);
disciplineInfoSpinner.setAdapter(spinnerArrayAdapter);
}//
}
You are creating a new Spinner and doing nothing with it.
You need to create an empty LinearLayout on your "discipline_view" layout, and then add your created Spinners on that LinearLayout, like this:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);
for(int i=0;i<5;i++) {
Spinner disciplineInfoSpinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,disciplineInfoArrayList);
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
disciplineInfoSpinner.setAdapter(spinnerArrayAdapter);
linearLayout.addView(disciplineInfoSpinner);
}

Categories

Resources